diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2026-10-26 08:32:08 +0100 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2026-10-26 08:42:53 +0100 |
| commit | 4957ca8373273721017fc8106b52d5bc6b2a0180 (patch) | |
| tree | 6372e708f63b61927b93dec2e70162546947c7fe /src | |
| parent | bbc8cadc76aa6419a318d8aeccfb0c25b7a30115 (diff) | |
Implement Audio Device and Remaining ASM Consts
We abstract over SDL's audio subsystem and implement an audio
device that fits into PICO-8's model. We fixed the implementation
for the PICO-8 window focus and key buffer and can now actually
boot into PICO-8 games with working sounds and controls!
There are a few issues that remain:
1. There is no "exit" option in the pause menu, I think it thinks
that we are on the BBS, and maybe there is someway to fix this?
2. The clipboard textarea is not implemented at all; we should
keep a text buffer in `pw_input` and interact with SDL's
clipboard system
3. Multicart's don't always work; in particular Undune II tries
to download from the BBS, I would like to shim this somehow
to support both `LOAD("FOO.P8")` and `LOAD("#FOO")` forms
transparently.
Diffstat (limited to 'src')
| -rw-r--r-- | src/audio.c | 223 | ||||
| -rw-r--r-- | src/audio.h | 68 | ||||
| -rw-r--r-- | src/env.c | 89 | ||||
| -rw-r--r-- | src/env.h | 2 | ||||
| -rw-r--r-- | src/game.c | 32 | ||||
| -rw-r--r-- | src/game.h | 2 | ||||
| -rw-r--r-- | src/input.c | 35 | ||||
| -rw-r--r-- | src/input.h | 20 | ||||
| -rw-r--r-- | src/picow.c | 6 | ||||
| -rw-r--r-- | src/png.h | 1 | ||||
| -rw-r--r-- | src/wasmrt.c | 19 | ||||
| -rw-r--r-- | src/wasmrt.h | 13 |
12 files changed, 499 insertions, 11 deletions
diff --git a/src/audio.c b/src/audio.c new file mode 100644 index 0000000..cbe5be3 --- /dev/null +++ b/src/audio.c @@ -0,0 +1,223 @@ +#include <SDL3/SDL_log.h> + +#include "audio.h" + +struct pw_audio *pw_audio_init(void) { + // PICO-8 exposes a `_mix(len0, len1)` function for copying audio data + // from an internal buffer to the host's audio context. From the + // Emscripten bundle, we see a few things: + // + // - It takes two lengths, one is the number of samples at the internal + // sample rate, and the other at the external sample rate + // - The internal sample rate is always 22050 Hz and uses 16-bit signed + // integer samples + // + // For us, this means we can let SDL do all the resampling for us and + // just choose a format and sample rate that matches PICO-8, meaning no + // resampling is done by the engine, and we can just call `_mix(l, l)`. + SDL_AudioSpec spec = { + .format = SDL_AUDIO_S16, + .channels = 1, + .freq = 22050, + }; + SDL_AudioStream *stream = SDL_OpenAudioDeviceStream( + SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &spec, NULL, NULL); + if (!stream) { + return NULL; + } + + struct pw_audio *audio = SDL_calloc(1, sizeof(*audio)); + if (!audio) { + SDL_DestroyAudioStream(stream); + return NULL; + } + + audio->stream = stream; + return audio; +} + +void pw_audio_free(struct pw_audio *audio) { + if (!audio) { + SDL_InvalidParamError("error"); + return; + } + + if (audio->stream) { + SDL_DestroyAudioStream(audio->stream); + } + SDL_free(audio); +} + +bool pw_audio_start(struct pw_audio *audio, uint32_t size) { + if (!audio || !audio->stream || audio->size) { + return SDL_InvalidParamError("audio"); + } + + bool ok = SDL_ResumeAudioStreamDevice(audio->stream); + if (ok) { + audio->size = size; + } + + return ok; +} + +static void destroy_stream(struct pw_audio *audio) { + SDL_DestroyAudioStream(audio->stream); + audio->stream = NULL; + audio->size = 0; +} + +bool pw_audio_stop(struct pw_audio *audio) { + if (!audio || !audio->stream) { + return SDL_InvalidParamError("audio"); + } + + if (!audio->size) { + return true; + } + + // If we fail to pause and clear the stream, then there is clearly + // something wrong with it, so mark the stream as destroyed meaning + // our audio device is dead. + if (!SDL_PauseAudioStreamDevice(audio->stream) || + !SDL_ClearAudioStream(audio->stream)) { + SDL_LogCritical(0, "audio stream cannot be stopped"); + destroy_stream(audio); + return false; + } + + audio->size = 0; + return true; +} + +bool pw_audio_ready(struct pw_audio *audio) { + if (!audio) { + return SDL_InvalidParamError("error"); + } + + return audio->stream && audio->size; +} + +static bool unlock_stream(struct pw_audio *audio) { + bool ok = SDL_UnlockAudioStream(audio->stream); + + // If we get in this state, something is seriously weird, and means + // we will likely not recover audio. Log and close the audio device + // to prevent further use. + if (!ok) { + SDL_LogCritical(0, "audio stream mutex poisoned: %s", SDL_GetError()); + destroy_stream(audio); + } + + return ok; +} + +static int16_t no_samples[] = {0}; + +int16_t *pw_audio_lock(struct pw_audio *audio, uint32_t *len) { + if (!audio || !audio->stream || !audio->size || audio->lock) { + SDL_InvalidParamError("audio"); + return NULL; + } + if (!len) { + SDL_InvalidParamError("len"); + return NULL; + } + + // Pick a buffer to use for collecting samples, since the `inuse` flag + // is reset by an audio callback, we need to make sure to hold a lock + // to the audio device to prevent threading issues. + if (!SDL_LockAudioStream(audio->stream)) { + return false; + } + + int16_t *data = NULL; + uint32_t request = 0; + + int queued = SDL_GetAudioStreamQueued(audio->stream); + if (queued < 0) { + goto cleanup; + } + + uint32_t q = + (uint32_t)SDL_min(queued, INT32_MAX) / sizeof(*audio->buffers->data); + if (q >= audio->size) { + data = no_samples; + goto cleanup; + } + + size_t i = 0; + struct pw_audio_buffer *buffer = NULL; + for (i = 0; i < SDL_arraysize(audio->buffers); ++i) { + if (!audio->buffers[i].inuse) { + buffer = &audio->buffers[i]; + break; + } + } + if (!buffer) { + SDL_SetError("no remaining audio buffers"); + goto cleanup; + } + + data = buffer->data; + request = SDL_min(audio->size - q, PW_AUDIO_BUFFER_MAX); + + audio->lock = i * PW_AUDIO_BUFFER_MAX + request; + buffer->inuse = true; + +cleanup: + if (!unlock_stream(audio)) { + return NULL; + } + + if (data) { + *len = request; + } + return data; +} + +static void data_complete(void *userdata, const void *buf, int buflen) { + (void)buflen; + + struct pw_audio *audio = userdata; + for (size_t i = 0; i < SDL_arraysize(audio->buffers); ++i) { + struct pw_audio_buffer *b = audio->buffers + i; + if (b->data == buf && b->inuse) { + b->inuse = false; + return; + } + } + + SDL_LogWarn(0, "could not find completed in-use buffer"); +} + +bool pw_audio_unlock(struct pw_audio *audio) { + if (!audio || !audio->stream || !audio->size || !audio->lock) { + return SDL_InvalidParamError("audio"); + } + + size_t i = audio->lock / PW_AUDIO_BUFFER_MAX; + size_t len = audio->lock % PW_AUDIO_BUFFER_MAX; + + if (!SDL_LockAudioStream(audio->stream)) { + return false; + } + + bool ok = false; + + struct pw_audio_buffer *buffer = audio->buffers + i; + if (!buffer->inuse) { + goto cleanup; + } + + size_t sz = len * sizeof(*buffer->data); + ok = SDL_PutAudioStreamDataNoCopy(audio->stream, buffer->data, sz, + data_complete, audio); + if (!ok) { + buffer->inuse = false; + } + +cleanup: + audio->lock = 0; + return unlock_stream(audio) && ok; +} diff --git a/src/audio.h b/src/audio.h new file mode 100644 index 0000000..2f70e8f --- /dev/null +++ b/src/audio.h @@ -0,0 +1,68 @@ +#ifndef PW_AUDIO_H +#define PW_AUDIO_H + +#include <SDL3/SDL_audio.h> + +#define PW_AUDIO_BUFFER_COUNT 8 +#define PW_AUDIO_BUFFER_MAX 4096 + +/** + * An audio buffer that we pass to the SDL audio stream. + * + * This allows buffer reuse and avoid double copying from Web Assembly + * linear memory (where a copy is required in order to be portable on + * big-endian platforms where data is written backwards). + */ +struct pw_audio_buffer { + bool inuse; + int16_t data[PW_AUDIO_BUFFER_MAX]; +}; + +/** + * PICO-8 audio stream. + */ +struct pw_audio { + SDL_AudioStream *stream; + uint32_t size; + uint32_t lock; + struct pw_audio_buffer buffers[PW_AUDIO_BUFFER_COUNT]; +}; + +/** + * Initializes the PICO-8 audio stream. + */ +struct pw_audio *pw_audio_init(void); + +/** + * Frees the PICO-8 audio stream and all of its resources. + */ +void pw_audio_free(struct pw_audio *audio); + +/** + * Starts playing audio from the stream with the specified buffer size. + */ +bool pw_audio_start(struct pw_audio *audio, uint32_t size); + +/** + * Stops playing audio from the stream. + */ +bool pw_audio_stop(struct pw_audio *audio); + +/** + * Whether or not the audio system is ready. + */ +bool pw_audio_ready(struct pw_audio *audio); + +/** + * Locks the audio device returning a buffer to write samples to. + * + * The audio stream expects `len` 16-bit samples to be written. + */ +int16_t *pw_audio_lock(struct pw_audio *audio, uint32_t *len); + +/** + * Unlocks the audio device. + */ +bool pw_audio_unlock(struct pw_audio *audio); + +#endif @@ -55,7 +55,6 @@ struct w2c_env *pw_env_init(size_t memory) { } env->memory.size = pages * wasm2c_pico8_pagesize_env_memory; env->memory.data_end = env->memory.data + env->memory.size; - SDL_Log("allocated %" SDL_PRIu64, env->memory.size); env->table.data = SDL_calloc(wasm2c_pico8_min_env_table, sizeof(*env->table.data)); @@ -319,8 +318,9 @@ uint32_t w2c_env_0x5FSDL_Init(struct w2c_env *env, uint32_t flags) { } void w2c_env_0x5FSDL_LockAudio(struct w2c_env *env) { + // Our Wasm runtime runs on a single thread, so there is nothing to lock + // for its internal audio buffer. (void)env; - env_unimplemented("_SDL_LockAudio"); } uint32_t w2c_env_0x5FSDL_LockSurface(struct w2c_env *env, uint32_t surface) { @@ -443,8 +443,9 @@ uint32_t w2c_env_0x5FSDL_SetVideoMode(struct w2c_env *env, uint32_t w, } void w2c_env_0x5FSDL_UnlockAudio(struct w2c_env *env) { + // Our Wasm runtime runs on a single thread, so there is nothing to unlock + // for its internal audio buffer. (void)env; - env_unimplemented("_SDL_UnlockAudio"); } void w2c_env_0x5FSDL_UnlockSurface(struct w2c_env *env, uint32_t surface) { @@ -744,18 +745,81 @@ uint32_t w2c_env_0x5Femscripten_asm_const_i(struct w2c_env *env, case 27: // Touch device detection, this seems to do a few things like reading mouse // coordinates from `asm_const` and making a larger audio buffer (I guess - // because phones would run slower `requestAnimationFrame` callbacks?). + // because phones would run slower audio data request callbacks?). // TODO(nlordell): Add touch detection to `pw_input`. return 0; case 28: - // `document.hidden` - which has no meaning for us. - return 0; + return (uint32_t)!(pw_input_window(env->context.input) & PW_WINDOW_VISIBLE); case 29: case 30: case 31: // All "listeners" are automatically installed in that we get them from SDL // events without asking, making these a no-op. return 0; + case 33: + return (uint32_t)pw_input_get_pointer_lock(env->context.input); + case 34: + // Whether or not `pico8_mouse` is set - we always keep track of the mouse + // so this is always true. + return 1; + case 35: { + struct pw_coordinates pos; + pw_input_mouse(env->context.input, &pos); + return pos.x; + } + case 36: { + struct pw_coordinates pos; + pw_input_mouse(env->context.input, &pos); + return pos.y; + } + case 37: + return (uint32_t)pw_input_key(env->context.input, NULL); + case 38: { + int32_t key; + pw_input_key(env->context.input, &key); + return (uint32_t)key; + } + case 39: { + int32_t dx; + pw_input_wheel(env->context.input, &dx, NULL); + return (uint32_t)dx; + } + case 40: { + int32_t dy; + pw_input_wheel(env->context.input, NULL, &dy); + return (uint32_t)dy; + } + case 41: + return (uint32_t)!!(pw_input_window(env->context.input) & PW_WINDOW_FOCUS); + case 42: + // PICO-8 keeps track of clicks on the page that are outside of the canvas + // area - this does not apply to us as the whole page is outside of the + // canvas and we already specify this information somewhat with the window + // flags, so always return `false`. + return 0; + case 43: + case 44: + // PICO-8 uses a text area for handling clipboard events, we don't need to + // do this as our SDL application handles them already; no-op. + return 0; + case 45: + return (uint32_t)pw_input_mouse(env->context.input, NULL); + case 46: + case 48: + // Machinery for creating directories, we have implicit directories in our + // file-system so these are all no-ops. + return 0; + case 49: + env->data.state.pointerlock = false; + return 0; + case 50: + return 0; + case 51: + case 53: + case 54: + case 55: + // TODO(nlordell): Handle clipboard text area. + return 0; default: env_badasm("i", code); } @@ -783,6 +847,15 @@ uint32_t w2c_env_0x5Femscripten_asm_const_ii(struct w2c_env *env, uint32_t code, return 0; } return (uint32_t)env->data.gpio[a]; + case 32: + if (!pw_audio_start(env->context.audio, a)) { + SDL_LogWarn(0, "failed to setup audio: %s", SDL_GetError()); + } + return 0; + case 47: + // Machinery for creating directories, we have implicit directories in our + // file-system so these are all no-ops. + return 0; default: env_badasm("ii", code); } @@ -808,6 +881,10 @@ uint32_t w2c_env_0x5Femscripten_asm_const_iii(struct w2c_env *env, env->data.gpio[a] = (uint8_t)(b & 0xff); } return 0; + case 52: + case 56: + // TODO(nlordell): Handle clipboard text area. + return 0; default: env_badasm("iii", code); } @@ -1,6 +1,7 @@ #ifndef PW_WENV_H #define PW_WENV_H +#include "audio.h" #include "cart.h" #include "fb.h" #include "fs.h" @@ -18,6 +19,7 @@ */ struct pw_env_ctx { struct pw_framebuffer *fb; + struct pw_audio *audio; struct pw_input *input; struct pw_cart_data *cartdat; struct pw_fs *userdat; @@ -26,6 +26,11 @@ struct pw_game *pw_game_init(SDL_Renderer *renderer, enum pw_scale_mode mode, goto error; } + game->audio = pw_audio_init(); + if (!game->audio) { + goto error; + } + game->input = pw_input_init(window); if (!game->input) { goto error; @@ -45,6 +50,9 @@ error: if (game->fb) { pw_fb_free(game->fb); } + if (game->audio) { + pw_audio_free(game->audio); + } if (game->input) { pw_input_free(game->input); } @@ -62,12 +70,13 @@ void pw_game_free(struct pw_game *game) { return; } + pw_fb_free(game->fb); + pw_audio_free(game->audio); + pw_input_free(game->input); + pw_env_free(game->env); if (game->cartdat) { pw_cart_data_free(game->cartdat); } - pw_input_free(game->input); - pw_fb_free(game->fb); - pw_env_free(game->env); pw_fs_free(game->userdat); SDL_free(game); } @@ -93,6 +102,7 @@ bool pw_game_start(struct pw_game *game, struct pw_players *players, if (!pw_env_link(game->env, (struct pw_env_ctx){ .fb = game->fb, + .audio = game->audio, .input = game->input, .cartdat = game->cartdat, .userdat = game->userdat, @@ -173,7 +183,21 @@ bool pw_game_iterate(struct pw_game *game) { } w2c_pico8_dynCall_v(&game->instance, game->env->data.mainloop); - w2c_pico8_0x5Fmix_0(&game->instance, 42, 1337); + + // TODO(nlordell): we need to improve error handling here, right now + // it just silently swallows errors. + if (pw_audio_ready(game->audio)) { + uint32_t len; + int16_t *data = pw_audio_lock(game->audio, &len); + if (!data || !len) { + goto mixdone; + } + + uint32_t samples = w2c_pico8_0x5Fmix_0(&game->instance, len, len); + wasm_rt_memory_load16v(&game->env->memory, samples, (uint16_t *)data, len); + pw_audio_unlock(game->audio); + } +mixdone: wasm_rt_trap_unregister(); @@ -4,6 +4,7 @@ #include <SDL3/SDL_events.h> #include <SDL3/SDL_render.h> +#include "audio.h" #include "cart.h" #include "env.h" #include "fb.h" @@ -19,6 +20,7 @@ struct pw_game { struct w2c_pico8 instance; struct w2c_env *env; struct pw_framebuffer *fb; + struct pw_audio *audio; struct pw_input *input; struct pw_cart_data *cartdat; struct pw_fs *userdat; diff --git a/src/input.c b/src/input.c index e082393..93aed4e 100644 --- a/src/input.c +++ b/src/input.c @@ -410,6 +410,25 @@ bool pw_input_iterate(struct pw_input *input, struct pw_framebuffer *fb) { return update_mouse(input, fb); } +enum pw_window_flags pw_input_window(struct pw_input *input) { + enum pw_window_flags result = PW_WINDOW_NONE; + if (!input) { + SDL_InvalidParamError("input"); + return result; + } + + SDL_WindowFlags flags = SDL_GetWindowFlags(input->window); + if (!(flags & + (SDL_WINDOW_MINIMIZED | SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED))) { + result |= PW_WINDOW_VISIBLE; + } + if (flags & SDL_WINDOW_INPUT_FOCUS) { + result |= PW_WINDOW_FOCUS; + } + + return result; +} + size_t pw_input_players(struct pw_input *input) { if (!input) { SDL_InvalidParamError("input"); @@ -451,6 +470,22 @@ enum pw_keymod pw_input_keymod(struct pw_input *input) { return input->keyboard.mod; } +bool pw_input_key(struct pw_input *input, int32_t *key) { + if (!input) { + if (key) { + *key = -1; + } + return SDL_InvalidParamError("input"); + } + + struct pw_keyboard_queue *q = &input->keyboard.text; + if (key) { + return dequeue_item(q, (uint32_t *)key); + } else { + return q->start != q->end; + } +} + enum pw_mouse_button pw_input_mouse(struct pw_input *input, struct pw_coordinates *pos) { if (!input) { diff --git a/src/input.h b/src/input.h index d521ce0..261b9f3 100644 --- a/src/input.h +++ b/src/input.h @@ -11,6 +11,15 @@ #define PW_KEYBOARD_BUFFER_SIZE 256 /** + * PICO-8 window flags. + */ +enum pw_window_flags { + PW_WINDOW_NONE = 0, + PW_WINDOW_VISIBLE = 1 << 0, + PW_WINDOW_FOCUS = 1 << 1, +}; + +/** * PICO-8 controller buttons. */ enum pw_button { @@ -153,6 +162,11 @@ bool pw_input_event(struct pw_input *input, struct pw_players *players, bool pw_input_iterate(struct pw_input *input, struct pw_framebuffer *fb); /** + * Returns PICO-8 window flags. + */ +enum pw_window_flags pw_input_window(struct pw_input *input); + +/** * Gets the number of connected players. */ size_t pw_input_players(struct pw_input *input); @@ -168,6 +182,12 @@ enum pw_button pw_input_btn(struct pw_input *input, size_t player); enum pw_keymod pw_input_keymod(struct pw_input *input); /** + * Gets the next buffered key. Passing `NULL` as `key` returns whether + * or not there are any keys buffered. + */ +bool pw_input_key(struct pw_input *input, int32_t *key); + +/** * Gets the current mouse button state. */ enum pw_mouse_button pw_input_mouse(struct pw_input *input, diff --git a/src/picow.c b/src/picow.c index f171e22..1918889 100644 --- a/src/picow.c +++ b/src/picow.c @@ -57,7 +57,7 @@ SDL_AppResult SDL_AppInit(void **appstate, int argc, char **argv) { } *appstate = state; - if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) { + if (!SDL_InitSubSystem(SDL_INIT_AUDIO | SDL_INIT_GAMEPAD | SDL_INIT_VIDEO)) { return failf("failed to initialize SDL"); } @@ -89,6 +89,10 @@ SDL_AppResult SDL_AppInit(void **appstate, int argc, char **argv) { SDL_LogWarn(0, "failed to enable V-sync: %s", SDL_GetError()); } + if (!SDL_HideCursor()) { + SDL_LogWarn(0, "unable to hide cursor: %s", SDL_GetError()); + } + if (state->config->debug) { state->debug = pw_debug_init(state->renderer); if (!state->debug) { @@ -15,6 +15,7 @@ union pw_png_pixel { uint8_t a; } ch; }; +SDL_COMPILE_TIME_ASSERT(pw_png_pixel_size, sizeof(union pw_png_pixel) == 4); /** * Loads a PNG with exact dimensions. diff --git a/src/wasmrt.c b/src/wasmrt.c index 6ec73fd..c75d897 100644 --- a/src/wasmrt.c +++ b/src/wasmrt.c @@ -151,6 +151,25 @@ size_t wasm_rt_memory_loada_unchecked(struct wasm_rt_memory_t const *mem, return sz; } +void wasm_rt_memory_load16v(struct wasm_rt_memory_t const *mem, uint32_t addr, + uint16_t *values, uint32_t len) { + wasm_rt_memory_check(mem, addr, sizeof(*values) * len); + wasm_rt_memory_load16v_unchecked(mem, addr, values, len); +} + +void wasm_rt_memory_load16v_unchecked(struct wasm_rt_memory_t const *mem, + uint32_t addr, uint16_t *values, + uint32_t len) { +#if SDL_BYTEORDER == SDL_LIL_ENDIAN + SDL_memcpy(values, mem->data + addr, sizeof(*values) * len); +#else + for (uint32_t i = 0; i < len; i++) { + SDL_memcpy(values + i, mem->data_end - addr - sizeof(*values) * i, + sizeof(*values)); + } +#endif +} + void wasm_rt_memory_store(struct wasm_rt_memory_t *mem, uint32_t addr, void const *src, uint32_t len) { wasm_rt_memory_check(mem, addr, len); diff --git a/src/wasmrt.h b/src/wasmrt.h index 8149590..ca1efdd 100644 --- a/src/wasmrt.h +++ b/src/wasmrt.h @@ -218,6 +218,19 @@ size_t wasm_rt_memory_loada_unchecked(struct wasm_rt_memory_t const *mem, uint32_t addr, char *buf, size_t sz); /** + * Loads 16-bit values from memory. + */ +void wasm_rt_memory_load16v(struct wasm_rt_memory_t const *mem, uint32_t addr, + uint16_t *values, uint32_t len); + +/** + * Loads 16-bit values from memory without bounds checks. + */ +void wasm_rt_memory_load16v_unchecked(struct wasm_rt_memory_t const *mem, + uint32_t addr, uint16_t *values, + uint32_t len); + +/** * Stores bytes to memory. */ void wasm_rt_memory_store(struct wasm_rt_memory_t *mem, uint32_t addr, |
