From 7ee2fd6933dd03276394bf8fb1cdd14dcf05f413 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Wed, 9 Sep 2026 08:56:41 -0400 Subject: [PATCH] refactor(pico8): move audio to a worklet, extract the pacer, share pad state Audio ran on the main thread and rebuilt the graph every frame: an AudioBuffer and a one-shot AudioBufferSourceNode per frame, roughly 18k nodes and 80MB of garbage per ten minutes of play. A single AudioWorkletNode now drains a ring buffer on the audio thread, so playback survives a stalled main thread. The route gets no COOP/COEP, so samples cross by transfer rather than through a SharedArrayBuffer, and the worklet hands each buffer straight back for the player to refill: 231 posts and 231 recycles over a four-second cart, so steady-state playback allocates nothing. The runtime fills a caller-owned buffer instead of returning a fresh slice, which drops the last copy. Frame pacing moves to pico8Pacer, and audio scheduling to pico8Audio, so the two pieces most likely to be wrong are unit-testable without a component. Both had no coverage while the wasm bindings did; they now have 19 tests between them, including the catch-up cap and the buffer recycling. useGamepad keeps the knowledge about raw pad state, so export isUsablePad, PAD_BUTTON and AXIS_THRESHOLD rather than restating them here. The button index map is now keyed by name, with the event-detail lookup derived from it. Vite inlines assets under 4KB as data: URIs, which addModule cannot be relied on to accept, so the worklet is pinned to a real file. Co-Authored-By: Claude Opus 5 (1M context) --- .../src/v2/composables/useGamepad/index.ts | 54 +++--- frontend/src/v2/views/Player/Pico8.vue | 112 ++++------- .../src/v2/views/Player/pico8Audio.test.ts | 183 ++++++++++++++++++ frontend/src/v2/views/Player/pico8Audio.ts | 100 ++++++++++ .../src/v2/views/Player/pico8AudioWorklet.js | 51 +++++ .../src/v2/views/Player/pico8Pacer.test.ts | 93 +++++++++ frontend/src/v2/views/Player/pico8Pacer.ts | 52 +++++ .../src/v2/views/Player/pico8Runtime.test.ts | 4 +- frontend/src/v2/views/Player/pico8Runtime.ts | 25 ++- frontend/vite.config.js | 4 + 10 files changed, 572 insertions(+), 106 deletions(-) create mode 100644 frontend/src/v2/views/Player/pico8Audio.test.ts create mode 100644 frontend/src/v2/views/Player/pico8Audio.ts create mode 100644 frontend/src/v2/views/Player/pico8AudioWorklet.js create mode 100644 frontend/src/v2/views/Player/pico8Pacer.test.ts create mode 100644 frontend/src/v2/views/Player/pico8Pacer.ts diff --git a/frontend/src/v2/composables/useGamepad/index.ts b/frontend/src/v2/composables/useGamepad/index.ts index b9de05191..244ce528e 100644 --- a/frontend/src/v2/composables/useGamepad/index.ts +++ b/frontend/src/v2/composables/useGamepad/index.ts @@ -50,31 +50,35 @@ const ACTIONS_DISABLED_PATHS = new Set(["/controller-debug"]); const INITIAL_DELAY_MS = 350; const REPEAT_MS = 120; -const AXIS_THRESHOLD = 0.5; +export const AXIS_THRESHOLD = 0.5; -// Standard-mapping button index → short symbolic name. Used as the -// `name` field on the `gamepad:buttondown` custom event so views can -// filter without memorising W3C indices. Kept exhaustive over the -// standard 0..16 range; anything past that ships as `name: undefined`. -const BUTTON_NAMES: Record = { - 0: "a", - 1: "b", - 2: "x", - 3: "y", - 4: "lb", - 5: "rb", - 6: "lt", - 7: "rt", - 8: "back", - 9: "start", - 10: "l3", - 11: "r3", - 12: "dpad-up", - 13: "dpad-down", - 14: "dpad-left", - 15: "dpad-right", - 16: "home", -}; +// Short symbolic name → W3C standard-mapping button index, so a view can +// read raw pad state without memorising indices. Exhaustive over the standard +// 0..16 range; anything past that has no name. +export const PAD_BUTTON = { + a: 0, + b: 1, + x: 2, + y: 3, + lb: 4, + rb: 5, + lt: 6, + rt: 7, + back: 8, + start: 9, + l3: 10, + r3: 11, + "dpad-up": 12, + "dpad-down": 13, + "dpad-left": 14, + "dpad-right": 15, + home: 16, +} as const; + +// The `name` field on the `gamepad:buttondown` event; `undefined` past 16. +const BUTTON_NAMES: Record = Object.fromEntries( + Object.entries(PAD_BUTTON).map(([name, index]) => [index, name]), +); export interface GamepadButtonEventDetail { /** W3C standard-mapping button index. */ @@ -108,7 +112,7 @@ const BUTTON_MAP: Record = { // Firefox keeps disconnected entries in the getGamepads() array, // and their stale analog values drift across the press threshold, // firing index-based actions with no user input. #3851. -function isUsablePad(pad: Gamepad | null): pad is Gamepad { +export function isUsablePad(pad: Gamepad | null): pad is Gamepad { return pad !== null && pad.connected; } diff --git a/frontend/src/v2/views/Player/Pico8.vue b/frontend/src/v2/views/Player/Pico8.vue index e427af0f8..32c13539c 100644 --- a/frontend/src/v2/views/Player/Pico8.vue +++ b/frontend/src/v2/views/Player/Pico8.vue @@ -10,12 +10,19 @@ import type { DetailedRom } from "@/stores/roms"; import { getDownloadPath } from "@/utils"; import PlayerShell from "@/v2/components/Player/PlayerShell.vue"; import { useFullscreenPref } from "@/v2/composables/useFullscreenPref"; +import { + AXIS_THRESHOLD, + isUsablePad, + PAD_BUTTON, +} from "@/v2/composables/useGamepad"; import { useInputModality } from "@/v2/composables/useInputModality"; import { useIsAlive } from "@/v2/composables/useIsAlive"; import { usePlaySession } from "@/v2/composables/usePlaySession"; import { usePlayerHero } from "@/v2/composables/usePlayerHero"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useUnloadGuard } from "@/v2/composables/useUnloadGuard"; +import { createPico8Audio, type Pico8Audio } from "./pico8Audio"; +import { createPico8Pacer, type Pico8Pacer } from "./pico8Pacer"; import { createPico8Runtime, PICO8_FRAME_RATE, @@ -48,18 +55,14 @@ const { } = useFullscreen(stage); let runtime: Pico8Runtime | null = null; +let audio: Pico8Audio | null = null; +let pacer: Pico8Pacer | null = null; let animationFrame = 0; -let lastFrameTime = 0; -let frameAccumulator = 0; let previousHeld = 0; let keyboardMask = 0; let mouseX = 0; let mouseY = 0; let mouseButtons = 0; -let audioContext: AudioContext | null = null; -let audioGain: GainNode | null = null; -let nextAudioTime = 0; -let frameDuration = 1000 / PICO8_FRAME_RATE; const input = { keyDown: 0, keyHeld: 0, mouseX: 0, mouseY: 0, mouseButtons: 0 }; @@ -72,14 +75,13 @@ const keyboardMap: Record = { KeyX: PICO8_INPUT_BITS.b, }; -// W3C standard-mapping button index to PICO-8 bit. const padButtonBits = [ - [0, PICO8_INPUT_BITS.a], - [1, PICO8_INPUT_BITS.b], - [12, PICO8_INPUT_BITS.up], - [13, PICO8_INPUT_BITS.down], - [14, PICO8_INPUT_BITS.left], - [15, PICO8_INPUT_BITS.right], + [PAD_BUTTON.a, PICO8_INPUT_BITS.a], + [PAD_BUTTON.b, PICO8_INPUT_BITS.b], + [PAD_BUTTON["dpad-up"], PICO8_INPUT_BITS.up], + [PAD_BUTTON["dpad-down"], PICO8_INPUT_BITS.down], + [PAD_BUTTON["dpad-left"], PICO8_INPUT_BITS.left], + [PAD_BUTTON["dpad-right"], PICO8_INPUT_BITS.right], ] as const; // Per stick axis, the bit for a negative then a positive deflection. @@ -87,7 +89,6 @@ const padAxisBits = [ [PICO8_INPUT_BITS.left, PICO8_INPUT_BITS.right], [PICO8_INPUT_BITS.up, PICO8_INPUT_BITS.down], ] as const; -const PAD_AXIS_THRESHOLD = 0.5; // Pointer button number to the mask FAKE-08 expects (left, middle, right). const mouseButtonBits = [0x01, 0x04, 0x02]; @@ -148,17 +149,15 @@ function onKeyUp(event: KeyboardEvent) { function readGamepadMask() { let mask = 0; for (const gamepad of navigator.getGamepads?.() ?? []) { - // Firefox keeps disconnected entries, whose stale analog values drift - // across the threshold and press buttons on their own. #3851. - if (!gamepad?.connected) continue; + if (!isUsablePad(gamepad)) continue; const { buttons, axes } = gamepad; for (const [index, bit] of padButtonBits) { if (buttons[index]?.pressed) mask |= bit; } for (let axis = 0; axis < padAxisBits.length; axis += 1) { const value = axes[axis] ?? 0; - if (value < -PAD_AXIS_THRESHOLD) mask |= padAxisBits[axis][0]; - if (value > PAD_AXIS_THRESHOLD) mask |= padAxisBits[axis][1]; + if (value < -AXIS_THRESHOLD) mask |= padAxisBits[axis][0]; + if (value > AXIS_THRESHOLD) mask |= padAxisBits[axis][1]; } } return mask; @@ -242,39 +241,18 @@ function onControlKeyUp(bit: number) { touchMask.value &= ~bit; } -function scheduleAudio(samples: Int16Array) { - if (!audioContext || !audioGain || samples.length === 0) return; - const buffer = audioContext.createBuffer( - 1, - samples.length, - audioContext.sampleRate, - ); - const channel = buffer.getChannelData(0); - for (let index = 0; index < samples.length; index += 1) { - channel[index] = samples[index] / 32768; - } - const source = audioContext.createBufferSource(); - source.buffer = buffer; - source.connect(audioGain); - const startAt = Math.max(audioContext.currentTime, nextAudioTime); - source.start(startAt); - nextAudioTime = startAt + buffer.duration; -} - function runFrame(timestamp: number) { - if (!gameRunning.value || !runtime) return; - frameAccumulator += Math.min(timestamp - lastFrameTime, 250); - lastFrameTime = timestamp; + const active = runtime; + if (!gameRunning.value || !active || !pacer) return; - let steps = 0; try { - while (frameAccumulator >= frameDuration && steps < 3) { - runtime.advance(readInput()); - scheduleAudio(runtime.getAudioSamples()); - frameAccumulator -= frameDuration; - steps += 1; + const steps = pacer.tick(timestamp); + for (let step = 0; step < steps; step += 1) { + active.advance(readInput()); + audio?.pump((target) => active.readAudio(target)); } - if (steps > 0) runtime.render(); + // Several emulated frames may land in one tick, but only the last is seen. + if (steps > 0) active.render(); } catch (error) { showPlayError(error); return; @@ -283,20 +261,11 @@ function runFrame(timestamp: number) { } function startLoop() { - frameDuration = 1000 / (runtime?.frameRate || PICO8_FRAME_RATE); - lastFrameTime = performance.now(); - frameAccumulator = frameDuration; + pacer = createPico8Pacer(runtime?.frameRate || PICO8_FRAME_RATE); + pacer.reset(performance.now()); animationFrame = requestAnimationFrame(runFrame); } -function closeAudio() { - const context = audioContext; - audioContext = null; - audioGain = null; - nextAudioTime = 0; - if (context) void context.close().catch(() => {}); -} - function resetInput() { previousHeld = 0; keyboardMask = 0; @@ -311,7 +280,9 @@ function releaseGame() { animationFrame = 0; runtime?.dispose(); runtime = null; - closeAudio(); + pacer = null; + audio?.close(); + audio = null; resetInput(); playSession.flush(); playingStore.setPlaying(false); @@ -363,22 +334,19 @@ async function onPlay() { runtime = nextRuntime; nextRuntime = null; + // A cart is playable without sound, so a failed audio graph only warns. try { - audioContext = new AudioContext({ + audio = await createPico8Audio({ sampleRate: runtime.audioSampleRate, + samplesPerFrame: runtime.samplesPerFrame, }); - } catch { - try { - audioContext = new AudioContext(); - } catch { - audioContext = null; - } + } catch (error) { + console.warn("[PICO-8] Audio is unavailable", error); + audio = null; } - if (audioContext) { - audioGain = audioContext.createGain(); - audioGain.gain.value = 0.75; - audioGain.connect(audioContext.destination); - void audioContext.resume().catch(() => {}); + if (!gameRunning.value) { + releaseGame(); + return; } loading.value = false; diff --git a/frontend/src/v2/views/Player/pico8Audio.test.ts b/frontend/src/v2/views/Player/pico8Audio.test.ts new file mode 100644 index 000000000..4ea62ec4a --- /dev/null +++ b/frontend/src/v2/views/Player/pico8Audio.test.ts @@ -0,0 +1,183 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { createPico8Audio } from "./pico8Audio"; + +vi.mock("./pico8AudioWorklet.js?url", () => ({ default: "/worklet.js" })); + +const addModule = vi.fn(async () => {}); +const posted: { chunk: Int16Array; transfer: Transferable[] }[] = []; + +class FakePort { + onmessage: ((event: MessageEvent) => void) | null = null; + + postMessage(chunk: Int16Array, transfer: Transferable[]) { + posted.push({ chunk, transfer }); + } + + /** Stand in for the worklet handing the storage back. */ + recycle(buffer: ArrayBufferLike) { + this.onmessage?.({ + data: new Int16Array(buffer), + } as MessageEvent); + } +} + +const port = new FakePort(); +const nodeConnect = vi.fn(); +const nodeDisconnect = vi.fn(); +const gainDisconnect = vi.fn(); +const contextClose = vi.fn(async () => {}); +const gain = { + gain: { value: 0 }, + connect: vi.fn(), + disconnect: gainDisconnect, +}; + +let sampleRateAsked: number | undefined; +let contextThrows = false; + +beforeEach(() => { + posted.length = 0; + vi.clearAllMocks(); + contextThrows = false; + sampleRateAsked = undefined; + port.onmessage = null; + + vi.stubGlobal( + "AudioContext", + class { + audioWorklet = { addModule }; + destination = {}; + constructor(options?: { sampleRate?: number }) { + if (contextThrows) throw new Error("bad sample rate"); + sampleRateAsked = options?.sampleRate; + } + createGain() { + return gain; + } + close = contextClose; + resume = vi.fn(async () => {}); + }, + ); + vi.stubGlobal( + "AudioWorkletNode", + class { + port = port; + connect = nodeConnect.mockReturnValue(gain); + disconnect = nodeDisconnect; + }, + ); + // node.connect(gain).connect(destination) + gain.connect.mockReturnValue(gain); +}); + +const open = () => + createPico8Audio({ sampleRate: 22050, samplesPerFrame: 735 }); + +describe("createPico8Audio", () => { + it("opens the graph at the runtime's sample rate", async () => { + const audio = await open(); + + expect(audio).not.toBeNull(); + expect(sampleRateAsked).toBe(22050); + expect(addModule).toHaveBeenCalledWith("/worklet.js"); + expect(gain.gain.value).toBeCloseTo(0.75); + }); + + it("falls back to the device rate when the asked-for one is refused", async () => { + let first = true; + vi.stubGlobal( + "AudioContext", + class { + audioWorklet = { addModule }; + destination = {}; + constructor(options?: { sampleRate?: number }) { + if (first) { + first = false; + throw new Error("bad sample rate"); + } + sampleRateAsked = options?.sampleRate; + } + createGain() { + return gain; + } + close = contextClose; + resume = vi.fn(async () => {}); + }, + ); + + expect(await open()).not.toBeNull(); + expect(sampleRateAsked).toBeUndefined(); + }); + + it("returns null when Web Audio is missing entirely", async () => { + contextThrows = true; + expect(await open()).toBeNull(); + }); + + it("closes the context when the worklet module fails to load", async () => { + addModule.mockRejectedValueOnce(new Error("blocked")); + + await expect(open()).rejects.toThrow("blocked"); + expect(contextClose).toHaveBeenCalled(); + }); + + it("forwards only the samples the runtime wrote, transferring the buffer", async () => { + const audio = await open(); + + audio?.pump((target) => { + target[0] = 100; + target[1] = -100; + return 2; + }); + + expect(posted).toHaveLength(1); + expect([...posted[0].chunk]).toEqual([100, -100]); + expect(posted[0].transfer).toHaveLength(1); + }); + + it("posts nothing for a silent frame", async () => { + const audio = await open(); + + audio?.pump(() => 0); + + expect(posted).toHaveLength(0); + }); + + it("reuses recycled storage instead of allocating per frame", async () => { + const audio = await open(); + + // Drain the two pooled buffers, then hand one back. + audio?.pump(() => 1); + audio?.pump(() => 1); + const returned = new ArrayBuffer(735 * 2); + port.recycle(returned); + audio?.pump(() => 1); + + expect(posted[2].chunk.buffer).toBe(returned); + }); + + it("recycles a full-length view even when the worklet returns a short one", async () => { + const audio = await open(); + const buffer = new ArrayBuffer(735 * 2); + + // The worklet reads 2 samples and hands back a 2-long view of the buffer. + port.onmessage?.({ + data: new Int16Array(buffer, 0, 2), + } as MessageEvent); + audio?.pump((target) => target.length); + + expect(posted[0].chunk).toHaveLength(735); + }); + + it("stops forwarding once closed", async () => { + const audio = await open(); + audio?.close(); + + audio?.pump(() => 1); + + expect(posted).toHaveLength(0); + expect(nodeDisconnect).toHaveBeenCalled(); + expect(gainDisconnect).toHaveBeenCalled(); + expect(contextClose).toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/v2/views/Player/pico8Audio.ts b/frontend/src/v2/views/Player/pico8Audio.ts new file mode 100644 index 000000000..5b3161cfa --- /dev/null +++ b/frontend/src/v2/views/Player/pico8Audio.ts @@ -0,0 +1,100 @@ +import workletUrl from "./pico8AudioWorklet.js?url"; + +const GAIN = 0.75; + +export interface Pico8AudioOptions { + sampleRate: number; + /** Samples one emulated frame can produce, which sizes the pooled buffers. */ + samplesPerFrame: number; +} + +export interface Pico8Audio { + /** + * Hand a pooled buffer to `fill` and forward however many samples it wrote. + * + * @param fill Writes samples into the buffer and returns the count. + */ + pump: (fill: (target: Int16Array) => number) => void; + close: () => void; +} + +function openContext(sampleRate: number): AudioContext | null { + try { + return new AudioContext({ sampleRate }); + } catch { + // Firefox rejects a rate the device cannot run at; its own is fine, since + // the worklet is resampled by the graph either way. + try { + return new AudioContext(); + } catch { + return null; + } + } +} + +/** + * Open the PICO-8 audio graph: one worklet node fed from a buffer pool. + * + * @param options The runtime's sample rate and per-frame sample budget. + * @returns The sink, or null when Web Audio is unavailable. + */ +export async function createPico8Audio( + options: Pico8AudioOptions, +): Promise { + const context = openContext(options.sampleRate); + if (!context) return null; + + let node: AudioWorkletNode; + try { + await context.audioWorklet.addModule(workletUrl); + node = new AudioWorkletNode(context, "pico8-audio", { + numberOfInputs: 0, + numberOfOutputs: 1, + outputChannelCount: [1], + }); + } catch (error) { + void context.close().catch(() => {}); + throw error; + } + + const gain = context.createGain(); + gain.gain.value = GAIN; + node.connect(gain).connect(context.destination); + void context.resume().catch(() => {}); + + // Two buffers cover a frame in flight plus the one being refilled. + const pool: Int16Array[] = [ + new Int16Array(options.samplesPerFrame), + new Int16Array(options.samplesPerFrame), + ]; + // The worklet returns a view sized to what it read, so re-wrap the whole + // buffer to keep every pooled entry a full frame long. + node.port.onmessage = (event: MessageEvent) => { + pool.push(new Int16Array(event.data.buffer)); + }; + + let closed = false; + + return { + pump(fill) { + if (closed) return; + const target = pool.pop() ?? new Int16Array(options.samplesPerFrame); + const written = fill(target); + if (written <= 0) { + pool.push(target); + return; + } + const chunk = + written === target.length ? target : target.subarray(0, written); + node.port.postMessage(chunk, [target.buffer]); + }, + close() { + if (closed) return; + closed = true; + node.port.onmessage = null; + node.disconnect(); + gain.disconnect(); + void context.close().catch(() => {}); + }, + }; +} diff --git a/frontend/src/v2/views/Player/pico8AudioWorklet.js b/frontend/src/v2/views/Player/pico8AudioWorklet.js new file mode 100644 index 000000000..42d9cc067 --- /dev/null +++ b/frontend/src/v2/views/Player/pico8AudioWorklet.js @@ -0,0 +1,51 @@ +// Audio sink for the PICO-8 player, running on the audio thread so playback +// survives a stalled main thread. The player posts Int16 frames in; this +// buffers them and drains one render quantum at a time. +// +// The player route gets no COOP/COEP, so SharedArrayBuffer is unavailable and +// samples arrive by transfer. Each buffer is transferred straight back once +// copied, so steady-state playback allocates nothing on either thread. + +// Roughly a quarter second at PICO-8's rate, so a late frame does not +// underrun while a long stall still drops rather than drifting. +const RING_CAPACITY = 8192; + +class Pico8AudioProcessor extends AudioWorkletProcessor { + constructor() { + super(); + this.ring = new Float32Array(RING_CAPACITY); + this.read = 0; + this.available = 0; + this.port.onmessage = (event) => this.enqueue(event.data); + } + + enqueue(samples) { + const count = Math.min(samples.length, RING_CAPACITY - this.available); + let write = (this.read + this.available) % RING_CAPACITY; + for (let index = 0; index < count; index += 1) { + this.ring[write] = samples[index] / 32768; + write = write + 1 === RING_CAPACITY ? 0 : write + 1; + } + this.available += count; + // Hand the storage back for the player to refill. + this.port.postMessage(samples, [samples.buffer]); + } + + process(_inputs, outputs) { + const channel = outputs[0][0]; + if (!channel) return true; + + const drained = Math.min(channel.length, this.available); + for (let index = 0; index < drained; index += 1) { + channel[index] = this.ring[this.read]; + this.read = this.read + 1 === RING_CAPACITY ? 0 : this.read + 1; + } + this.available -= drained; + // An underrun outputs silence rather than repeating the last block, which + // would ring audibly on a cart that pauses. + channel.fill(0, drained); + return true; + } +} + +registerProcessor("pico8-audio", Pico8AudioProcessor); diff --git a/frontend/src/v2/views/Player/pico8Pacer.test.ts b/frontend/src/v2/views/Player/pico8Pacer.test.ts new file mode 100644 index 000000000..367789087 --- /dev/null +++ b/frontend/src/v2/views/Player/pico8Pacer.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from "vitest"; +import { createPico8Pacer } from "./pico8Pacer"; + +// 30 fps carts get a 33.33ms budget per emulated frame. +const FRAME = 1000 / 30; + +describe("createPico8Pacer", () => { + it("runs one frame on the first tick so the cart paints immediately", () => { + const pacer = createPico8Pacer(30); + pacer.reset(1000); + + expect(pacer.tick(1000)).toBe(1); + }); + + // Individual ticks jitter between 0 and 2 on exact frame boundaries, since + // 1000/30 is not representable; what matters is that the total does not drift. + it("emulates one frame per display frame without drifting", () => { + const pacer = createPico8Pacer(30); + pacer.reset(0); + + let total = 0; + for (let tick = 0; tick <= 300; tick += 1) + total += pacer.tick(tick * FRAME); + + // 301 ticks, so 301 frames give or take whatever partial frame is still + // banked. A pacer that drifted would be out by far more than one. + expect(total).toBeGreaterThanOrEqual(300); + expect(total).toBeLessThanOrEqual(301); + }); + + it("skips a frame when the display is faster than the cart", () => { + const pacer = createPico8Pacer(30); + pacer.reset(0); + pacer.tick(0); + + // 60Hz display, 30 fps cart: every other tick has nothing to do. + expect(pacer.tick(FRAME / 2)).toBe(0); + expect(pacer.tick(FRAME)).toBe(1); + }); + + it("catches up on a short stall", () => { + const pacer = createPico8Pacer(30); + pacer.reset(0); + pacer.tick(0); + + expect(pacer.tick(FRAME * 2)).toBe(2); + }); + + it("caps catch-up so a long stall cannot run the cart at speed", () => { + const pacer = createPico8Pacer(30); + pacer.reset(0); + pacer.tick(0); + + expect(pacer.tick(FRAME * 50)).toBe(3); + }); + + it("drops the debt a capped tick could not spend", () => { + const pacer = createPico8Pacer(30); + pacer.reset(0); + pacer.tick(0); + pacer.tick(FRAME * 50); + + // Without dropping it, the next ticks would stay pinned at the cap. + expect(pacer.tick(FRAME * 51)).toBe(1); + }); + + it("ignores a timestamp that goes backwards", () => { + const pacer = createPico8Pacer(30); + pacer.reset(1000); + pacer.tick(1000); + + expect(pacer.tick(500)).toBe(0); + }); + + it("honours a 60 fps cart", () => { + const pacer = createPico8Pacer(60); + pacer.reset(0); + pacer.tick(0); + + expect(pacer.tick(1000 / 60)).toBe(1); + expect(pacer.tick(1000 / 60 + 1000 / 120)).toBe(0); + }); + + it("re-anchors on reset so a replay does not inherit the old clock", () => { + const pacer = createPico8Pacer(30); + pacer.reset(0); + pacer.tick(0); + pacer.tick(FRAME); + + pacer.reset(9_000_000); + expect(pacer.tick(9_000_000)).toBe(1); + }); +}); diff --git a/frontend/src/v2/views/Player/pico8Pacer.ts b/frontend/src/v2/views/Player/pico8Pacer.ts new file mode 100644 index 000000000..4932ba39c --- /dev/null +++ b/frontend/src/v2/views/Player/pico8Pacer.ts @@ -0,0 +1,52 @@ +// Frame pacing for the PICO-8 player, kept apart from the view so the +// catch-up rules are unit-testable without a canvas or a rAF loop. + +/** Longest gap a single tick may carry, so a backgrounded tab does not spin. */ +const MAX_ELAPSED_MS = 250; +/** Emulated frames one tick may run before it must paint. */ +const MAX_CATCH_UP = 3; + +export interface Pico8Pacer { + /** Anchor the clock, priming one frame so the first tick renders. */ + reset: (now: number) => void; + /** + * Advance the clock. + * + * @param now A monotonic timestamp in milliseconds. + * @returns How many emulated frames to run before painting. + */ + tick: (now: number) => number; +} + +/** + * Build a pacer for a cart's target frame rate. + * + * @param frameRate Frames per second the cart asks for (PICO-8 uses 30 or 60). + * @returns The pacer. + */ +export function createPico8Pacer(frameRate: number): Pico8Pacer { + const frameDuration = 1000 / frameRate; + let last = 0; + let accumulator = 0; + + return { + reset(now) { + last = now; + accumulator = frameDuration; + }, + tick(now) { + accumulator += Math.min(now - last, MAX_ELAPSED_MS); + last = now; + + let steps = 0; + while (accumulator >= frameDuration && steps < MAX_CATCH_UP) { + accumulator -= frameDuration; + steps += 1; + } + // Drop debt beyond the cap instead of carrying it into the next tick, + // which would keep the loop permanently behind after one long stall. + if (steps === MAX_CATCH_UP) accumulator = 0; + return steps; + }, + }; +} diff --git a/frontend/src/v2/views/Player/pico8Runtime.test.ts b/frontend/src/v2/views/Player/pico8Runtime.test.ts index 93cdc3dd0..e3a48d12d 100644 --- a/frontend/src/v2/views/Player/pico8Runtime.test.ts +++ b/frontend/src/v2/views/Player/pico8Runtime.test.ts @@ -88,7 +88,9 @@ describe("createPico8Runtime", () => { expect(context.putImageData).toHaveBeenCalled(); const image = context.putImageData.mock.calls[0][0] as ImageData; expect([...image.data.slice(0, 8)]).toEqual([1, 2, 3, 255, 4, 5, 6, 255]); - expect([...runtime.getAudioSamples()]).toEqual([1000, -1000]); + const audio = new Int16Array(runtime.samplesPerFrame); + expect(runtime.readAudio(audio)).toBe(2); + expect([...audio.slice(0, 2)]).toEqual([1000, -1000]); expect(runtime.frameRate).toBe(30); expect(runtime.audioSampleRate).toBe(22050); diff --git a/frontend/src/v2/views/Player/pico8Runtime.ts b/frontend/src/v2/views/Player/pico8Runtime.ts index 9ded48514..3339a31e7 100644 --- a/frontend/src/v2/views/Player/pico8Runtime.ts +++ b/frontend/src/v2/views/Player/pico8Runtime.ts @@ -17,7 +17,6 @@ const PICO8_WASM_PATH = "/assets/pico8/fake08.wasm"; const PICO8_SCRIPT_PATH = "/assets/pico8/fake08.js"; const FRAMEBUFFER_BYTES = (PICO8_WIDTH * PICO8_HEIGHT) / 2; const PALETTE_BYTES = 16 * 4; -const EMPTY_SAMPLES = new Int16Array(0); export interface Fake08Module { HEAPU8: Uint8Array; @@ -90,10 +89,18 @@ export interface Pico8Input { export interface Pico8Runtime { readonly frameRate: number; readonly audioSampleRate: number; + /** Samples a single frame can produce, for sizing the caller's buffer. */ + readonly samplesPerFrame: number; loadCart: (bytes: Uint8Array) => void; advance: (input: Pico8Input) => void; render: () => void; - getAudioSamples: () => Int16Array; + /** + * Copy this frame's audio into the caller's buffer. + * + * @param target Destination, at least `samplesPerFrame` long. + * @returns How many samples were written. + */ + readAudio: (target: Int16Array) => number; dispose: () => void; } @@ -203,14 +210,15 @@ export async function createPico8Runtime( module._f08_step_frame(); } - function getAudioSamples() { - if (disposed) return EMPTY_SAMPLES; + function readAudio(target: Int16Array) { + if (disposed) return 0; const written = module._f08_fill_audio_buffer( audioPointer, - samplesPerFrame, + Math.min(samplesPerFrame, target.length), ); - if (written <= 0) return EMPTY_SAMPLES; - return new Int16Array(module.HEAPU8.buffer, audioPointer, written).slice(); + if (written <= 0) return 0; + target.set(new Int16Array(module.HEAPU8.buffer, audioPointer, written)); + return written; } function dispose() { @@ -223,10 +231,11 @@ export async function createPico8Runtime( return { frameRate: module._f08_get_target_fps() || PICO8_FRAME_RATE, audioSampleRate: module._f08_get_audio_sample_rate(), + samplesPerFrame, loadCart, advance, render, - getAudioSamples, + readAudio, dispose, }; } diff --git a/frontend/vite.config.js b/frontend/vite.config.js index 2d472b74e..d885789e6 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -112,6 +112,10 @@ export default defineConfig(({ mode }) => { }, build: { target: "esnext", + // AudioWorklet.addModule is only dependable with a real URL, and Vite + // inlines any asset under 4KB as a data: URI, so keep the worklet out. + assetsInlineLimit: (filePath) => + filePath.endsWith("pico8AudioWorklet.js") ? false : undefined, // Browser targets for CSS (prefixing + down-leveling) come from the // shared `.browserslistrc`. Never hand-write a `-webkit-` twin next to a // standard property: Lightning CSS collapses the pair to whichever is