c64-ready 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,104 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { C64Emulator } from './c64-emulator';
3
+ import { C64WASM } from './c64-wasm';
4
+ const FRAME_BYTES = 384 * 272 * 4;
5
+ describe('C64Emulator', () => {
6
+ beforeEach(() => {
7
+ vi.restoreAllMocks();
8
+ });
9
+ function makeFakeWasm() {
10
+ const heapU8 = new Uint8Array(FRAME_BYTES + 64);
11
+ for (let i = 0; i < 16; i++) {
12
+ heapU8[i] = i + 1;
13
+ }
14
+ const heapF32 = new Float32Array(4096 + 32);
15
+ heapF32[0] = 0.25;
16
+ heapF32[1] = -0.5;
17
+ const exports = {
18
+ c64_init: vi.fn(),
19
+ c64_reset: vi.fn(),
20
+ debugger_update: vi.fn(() => 1),
21
+ c64_getPixelBuffer: vi.fn(() => 0),
22
+ sid_getAudioBuffer: vi.fn(() => 0),
23
+ sid_dumpBuffer: vi.fn(() => 2),
24
+ c64_loadPRG: vi.fn(),
25
+ c64_insertDisk: vi.fn(),
26
+ c64_loadCartridge: vi.fn(),
27
+ c64_loadSnapshot: vi.fn(),
28
+ c64_ramRead: vi.fn(() => 0xab),
29
+ c64_getSnapshotSize: vi.fn(() => 4),
30
+ malloc: vi.fn(() => 8),
31
+ c64_getSnapshot: vi.fn((ptr) => {
32
+ heapU8.set([9, 8, 7, 6], ptr);
33
+ }),
34
+ free: vi.fn(),
35
+ };
36
+ const wasm = {
37
+ exports,
38
+ heap: {
39
+ heapU8,
40
+ heapF32,
41
+ heapU32: new Uint32Array(heapU8.buffer),
42
+ },
43
+ allocAndWrite: vi.fn(() => 16),
44
+ free: vi.fn(),
45
+ };
46
+ return { wasm, exports, heapU8 };
47
+ }
48
+ it('loads and initializes through C64WASM.load', async () => {
49
+ const { wasm, exports } = makeFakeWasm();
50
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
51
+ const emulator = await C64Emulator.load('/custom.wasm');
52
+ expect(C64WASM.load).toHaveBeenCalledWith('/custom.wasm');
53
+ expect(exports.c64_init).toHaveBeenCalledOnce();
54
+ expect(emulator.ramRead(0)).toBe(0xab);
55
+ });
56
+ it('does not tick when paused', async () => {
57
+ const { wasm, exports } = makeFakeWasm();
58
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
59
+ const emulator = await C64Emulator.load();
60
+ emulator.tick(12);
61
+ expect(exports.debugger_update).not.toHaveBeenCalled();
62
+ expect(emulator.getFrameCount()).toBe(0);
63
+ });
64
+ it('emits frame callback while running', async () => {
65
+ const { wasm, exports } = makeFakeWasm();
66
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
67
+ const emulator = await C64Emulator.load();
68
+ const onFrame = vi.fn();
69
+ emulator.onFrame = onFrame;
70
+ emulator.start();
71
+ emulator.tick(10);
72
+ expect(exports.debugger_update).toHaveBeenCalledWith(10);
73
+ expect(emulator.getFrameCount()).toBe(1);
74
+ expect(onFrame).toHaveBeenCalledOnce();
75
+ expect(onFrame.mock.calls[0][0].width).toBe(384);
76
+ });
77
+ it('provides SID audio buffer via getSidBuffer', async () => {
78
+ const { wasm } = makeFakeWasm();
79
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
80
+ const emulator = await C64Emulator.load();
81
+ const buf = emulator.getSidBuffer();
82
+ expect(buf).toBeInstanceOf(Float32Array);
83
+ expect(buf.length).toBe(4096);
84
+ });
85
+ it('always frees allocated memory after loadGame', async () => {
86
+ const { wasm, exports } = makeFakeWasm();
87
+ exports.c64_loadPRG.mockImplementation(() => {
88
+ throw new Error('bad prg');
89
+ });
90
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
91
+ const emulator = await C64Emulator.load();
92
+ expect(() => emulator.loadGame({ type: 'prg', data: new Uint8Array([1, 2]) })).toThrow('bad prg');
93
+ expect(wasm.free).toHaveBeenCalledWith(16);
94
+ });
95
+ it('returns a copied framebuffer in getFrameBuffer', async () => {
96
+ const { wasm, heapU8 } = makeFakeWasm();
97
+ vi.spyOn(C64WASM, 'load').mockResolvedValue(wasm);
98
+ const emulator = await C64Emulator.load();
99
+ const frame = emulator.getFrameBuffer();
100
+ heapU8[0] = 250;
101
+ expect(frame.data[0]).toBe(1);
102
+ expect(frame.data.length).toBe(FRAME_BYTES);
103
+ });
104
+ });
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Low-level wrapper around the C64 WebAssembly binary (Emscripten-compiled)
3
+ *
4
+ * Responsibilities:
5
+ * - Fetch and instantiate the WASM binary
6
+ * - Provide the Emscripten/WASI imports the binary requires
7
+ * - Manage WebAssembly.Memory and keep heap views up to date
8
+ * - Forward raw WASM export calls to C64Emulator
9
+ *
10
+ * NOT responsible for: game logic, input handling, frame loop, or UI.
11
+ * Consumers should use C64Emulator, not this class directly.
12
+ */
13
+ export class C64WASM {
14
+ /** Raw WASM exports — available to C64Emulator */
15
+ exports = null;
16
+ /** Typed views into WASM linear memory */
17
+ heap = null;
18
+ wasmMemory = null;
19
+ // ---------------------------------------------------------------------------
20
+ // Bootstrap
21
+ // ---------------------------------------------------------------------------
22
+ /**
23
+ * Fetch, instantiate and initialise the WASM binary.
24
+ * C64Emulator calls this via the static C64Emulator.load() factory.
25
+ */
26
+ static async load(wasmUrl = '/src/emulator/c64.wasm') {
27
+ const response = await fetch(wasmUrl);
28
+ if (!response.ok)
29
+ throw new Error(`Failed to fetch ${wasmUrl}: ${response.status}`);
30
+ const binary = await response.arrayBuffer();
31
+ const instance = new C64WASM();
32
+ await instance.instantiate(binary);
33
+ return instance;
34
+ }
35
+ // Emscripten layout constants (must match the compiled binary)
36
+ static DYNAMICTOP_PTR = 5583504;
37
+ static DYNAMIC_BASE = 10826544;
38
+ static INITIAL_PAGES = 256; // 16 MB
39
+ async instantiate(wasmBinary, extraEnv) {
40
+ const mem = new WebAssembly.Memory({ initial: C64WASM.INITIAL_PAGES });
41
+ this.wasmMemory = mem;
42
+ const importObject = {
43
+ env: { ...this.makeEnvImports(mem), ...(extraEnv ?? {}) },
44
+ wasi_snapshot_preview1: this.makeWasiImports(mem),
45
+ };
46
+ try {
47
+ const result = await WebAssembly.instantiate(wasmBinary, importObject);
48
+ this.exports = result.instance.exports;
49
+ this.updateHeapViews();
50
+ // Initialise the sbrk heap pointer so malloc knows where free memory starts
51
+ new DataView(mem.buffer).setUint32(C64WASM.DYNAMICTOP_PTR, C64WASM.DYNAMIC_BASE, true);
52
+ this.exports.__wasm_call_ctors();
53
+ }
54
+ catch (err) {
55
+ throw new Error(`WASM instantiation failed: ${err}`, { cause: err });
56
+ }
57
+ }
58
+ // ---------------------------------------------------------------------------
59
+ // Memory
60
+ // ---------------------------------------------------------------------------
61
+ /** Allocate a buffer in WASM heap, write data, return pointer */
62
+ allocAndWrite(data) {
63
+ if (!this.exports || !this.heap)
64
+ throw new Error('WASM not ready');
65
+ const ptr = this.exports.malloc(data.length);
66
+ // malloc may have grown memory, so refresh views before writing
67
+ this.updateHeapViews();
68
+ this.heap.heapU8.set(data, ptr);
69
+ return ptr;
70
+ }
71
+ free(ptr) {
72
+ this.exports?.free(ptr);
73
+ }
74
+ /** Refresh heap views — must be called after any memory.grow() */
75
+ updateHeapViews() {
76
+ if (!this.wasmMemory)
77
+ throw new Error('WASM memory not initialized');
78
+ const buffer = this.wasmMemory.buffer;
79
+ this.heap = {
80
+ heapU8: new Uint8Array(buffer),
81
+ heapF32: new Float32Array(buffer),
82
+ heapU32: new Uint32Array(buffer),
83
+ };
84
+ }
85
+ // ---------------------------------------------------------------------------
86
+ // Emscripten env imports
87
+ // ---------------------------------------------------------------------------
88
+ makeEnvImports(mem) {
89
+ return {
90
+ memory: mem,
91
+ emscripten_get_sbrk_ptr: () => C64WASM.DYNAMICTOP_PTR,
92
+ emscripten_resize_heap: (requestedSize) => {
93
+ const PAGE_MULTIPLE = 65536;
94
+ const maxHeapSize = 2147483648 - PAGE_MULTIPLE;
95
+ if (requestedSize > maxHeapSize)
96
+ return 0;
97
+ const oldSize = mem.buffer.byteLength;
98
+ const minHeapSize = 16777216;
99
+ for (let cutDown = 1; cutDown <= 4; cutDown *= 2) {
100
+ let overGrown = oldSize * (1 + 0.2 / cutDown);
101
+ overGrown = Math.min(overGrown, requestedSize + 100663296);
102
+ const newSize = Math.min(maxHeapSize, Math.ceil(Math.max(minHeapSize, requestedSize, overGrown) / PAGE_MULTIPLE) *
103
+ PAGE_MULTIPLE);
104
+ try {
105
+ mem.grow((newSize - mem.buffer.byteLength + 65535) >>> 16);
106
+ this.updateHeapViews();
107
+ return 1;
108
+ }
109
+ catch {
110
+ // retry with less aggressive growth
111
+ }
112
+ }
113
+ return 0;
114
+ },
115
+ emscripten_memcpy_big: (dest, src, num) => {
116
+ new Uint8Array(mem.buffer).copyWithin(dest, src, src + num);
117
+ return dest;
118
+ },
119
+ setTempRet0: (_val) => { },
120
+ emscripten_asm_const_iii: (_code, _sig, _val) => 0,
121
+ table: new WebAssembly.Table({ initial: 512, maximum: 512, element: 'anyfunc' }),
122
+ };
123
+ }
124
+ // ---------------------------------------------------------------------------
125
+ // WASI imports (only fd_write is used by this binary)
126
+ // ---------------------------------------------------------------------------
127
+ makeWasiImports(mem) {
128
+ return {
129
+ fd_write: (fd, iovs, iovs_len, nwritten) => {
130
+ const view = new DataView(mem.buffer);
131
+ const u8 = new Uint8Array(mem.buffer);
132
+ let written = 0;
133
+ for (let i = 0; i < iovs_len; i++) {
134
+ const ptr = view.getUint32(iovs + i * 8, true);
135
+ const len = view.getUint32(iovs + i * 8 + 4, true);
136
+ // Only forward stderr (fd 2) to the console — stdout (fd 1) is
137
+ // extremely noisy (SID dumps buffer length every frame).
138
+ if (fd === 2) {
139
+ const text = new TextDecoder().decode(u8.subarray(ptr, ptr + len));
140
+ console.error(text);
141
+ }
142
+ written += len;
143
+ }
144
+ view.setUint32(nwritten, written, true);
145
+ return 0;
146
+ },
147
+ };
148
+ }
149
+ }
@@ -0,0 +1,65 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { C64WASM } from './c64-wasm';
3
+ describe('C64WASM', () => {
4
+ beforeEach(() => {
5
+ vi.restoreAllMocks();
6
+ });
7
+ it('throws when updateHeapViews is called before memory init', () => {
8
+ const wasm = new C64WASM();
9
+ expect(() => wasm.updateHeapViews()).toThrow('WASM memory not initialized');
10
+ });
11
+ it('instantiates wasm and calls ctors', async () => {
12
+ const ctors = vi.fn();
13
+ const instantiateSpy = vi.spyOn(WebAssembly, 'instantiate').mockResolvedValue({
14
+ instance: {
15
+ exports: {
16
+ __wasm_call_ctors: ctors,
17
+ },
18
+ },
19
+ module: {},
20
+ });
21
+ const wasm = new C64WASM();
22
+ await wasm.instantiate(new ArrayBuffer(8));
23
+ expect(instantiateSpy).toHaveBeenCalledOnce();
24
+ expect(wasm.exports).toBeTruthy();
25
+ expect(wasm.heap).toBeTruthy();
26
+ expect(ctors).toHaveBeenCalledOnce();
27
+ });
28
+ it('wraps instantiate failures with a clear error', async () => {
29
+ vi.spyOn(WebAssembly, 'instantiate').mockRejectedValue(new Error('boom'));
30
+ const wasm = new C64WASM();
31
+ await expect(wasm.instantiate(new ArrayBuffer(8))).rejects.toThrow('WASM instantiation failed');
32
+ });
33
+ it('allocates and writes bytes to heap', () => {
34
+ const mem = new WebAssembly.Memory({ initial: 1 });
35
+ const wasm = new C64WASM();
36
+ // Expose the private wasmMemory so updateHeapViews works
37
+ wasm.wasmMemory = mem;
38
+ wasm.exports = {
39
+ malloc: vi.fn(() => 4),
40
+ free: vi.fn(),
41
+ };
42
+ wasm.updateHeapViews();
43
+ const data = new Uint8Array([10, 20, 30]);
44
+ const ptr = wasm.allocAndWrite(data);
45
+ expect(ptr).toBe(4);
46
+ expect(Array.from(wasm.heap.heapU8.slice(4, 7))).toEqual([10, 20, 30]);
47
+ });
48
+ it('load fetches binary and delegates to instantiate', async () => {
49
+ const arrayBuffer = new ArrayBuffer(16);
50
+ const fetchMock = vi.fn().mockResolvedValue({
51
+ ok: true,
52
+ arrayBuffer: vi.fn().mockResolvedValue(arrayBuffer),
53
+ });
54
+ vi.stubGlobal('fetch', fetchMock);
55
+ const instantiateSpy = vi.spyOn(C64WASM.prototype, 'instantiate').mockResolvedValue();
56
+ const wasm = await C64WASM.load('/roms/c64.wasm');
57
+ expect(fetchMock).toHaveBeenCalledWith('/roms/c64.wasm');
58
+ expect(instantiateSpy).toHaveBeenCalledWith(arrayBuffer);
59
+ expect(wasm).toBeInstanceOf(C64WASM);
60
+ });
61
+ it('load throws when fetch is not ok', async () => {
62
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 404 }));
63
+ await expect(C64WASM.load('/missing.wasm')).rejects.toThrow('Failed to fetch /missing.wasm: 404');
64
+ });
65
+ });
@@ -0,0 +1,9 @@
1
+ export const JOYSTICK_PORT_1 = 1;
2
+ export const JOYSTICK_PORT_2 = 2;
3
+ export const JOYSTICK_DIRECTION = {
4
+ UP: 0x1,
5
+ DOWN: 0x2,
6
+ LEFT: 0x4,
7
+ RIGHT: 0x8,
8
+ };
9
+ export const JOYSTICK_FIRE_1 = 0x10;
@@ -0,0 +1,62 @@
1
+ import { JOYSTICK_DIRECTION, JOYSTICK_FIRE_1, JOYSTICK_PORT_2 } from './constants';
2
+ const KEY_TO_JOYSTICK = {
3
+ ArrowUp: JOYSTICK_DIRECTION.UP,
4
+ ArrowDown: JOYSTICK_DIRECTION.DOWN,
5
+ ArrowLeft: JOYSTICK_DIRECTION.LEFT,
6
+ ArrowRight: JOYSTICK_DIRECTION.RIGHT,
7
+ ControlLeft: JOYSTICK_FIRE_1,
8
+ };
9
+ export class EmulatorInput {
10
+ emulator;
11
+ target;
12
+ pressedControls = new Set();
13
+ keyDownHandler = (event) => {
14
+ this.handleKeyDown(event);
15
+ };
16
+ keyUpHandler = (event) => {
17
+ this.handleKeyUp(event);
18
+ };
19
+ constructor(emulator, target = window) {
20
+ this.emulator = emulator;
21
+ this.target = target;
22
+ }
23
+ attach() {
24
+ this.target.addEventListener('keydown', this.keyDownHandler);
25
+ this.target.addEventListener('keyup', this.keyUpHandler);
26
+ }
27
+ detach() {
28
+ this.target.removeEventListener('keydown', this.keyDownHandler);
29
+ this.target.removeEventListener('keyup', this.keyUpHandler);
30
+ this.releaseAll();
31
+ }
32
+ handleKeyDown(event) {
33
+ const control = this.getMappedControl(event);
34
+ if (!control || this.pressedControls.has(control)) {
35
+ return;
36
+ }
37
+ this.pressedControls.add(control);
38
+ this.emulator.joystickPush(JOYSTICK_PORT_2, KEY_TO_JOYSTICK[control]);
39
+ event.preventDefault();
40
+ }
41
+ handleKeyUp(event) {
42
+ const control = this.getMappedControl(event);
43
+ if (!control) {
44
+ return;
45
+ }
46
+ this.pressedControls.delete(control);
47
+ this.emulator.joystickRelease(JOYSTICK_PORT_2, KEY_TO_JOYSTICK[control]);
48
+ event.preventDefault();
49
+ }
50
+ getMappedControl(event) {
51
+ if (event.code in KEY_TO_JOYSTICK) {
52
+ return event.code;
53
+ }
54
+ return null;
55
+ }
56
+ releaseAll() {
57
+ for (const control of this.pressedControls) {
58
+ this.emulator.joystickRelease(JOYSTICK_PORT_2, KEY_TO_JOYSTICK[control]);
59
+ }
60
+ this.pressedControls.clear();
61
+ }
62
+ }
@@ -0,0 +1,53 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { EmulatorInput } from './input';
3
+ import { JOYSTICK_DIRECTION, JOYSTICK_FIRE_1, JOYSTICK_PORT_2 } from './constants';
4
+ describe('EmulatorInput', () => {
5
+ beforeEach(() => {
6
+ vi.restoreAllMocks();
7
+ });
8
+ it('maps cursor keys to joystick port 2', () => {
9
+ const emulator = {
10
+ joystickPush: vi.fn(),
11
+ joystickRelease: vi.fn(),
12
+ };
13
+ const input = new EmulatorInput(emulator, window);
14
+ input.attach();
15
+ const down = new KeyboardEvent('keydown', { code: 'ArrowLeft', cancelable: true });
16
+ window.dispatchEvent(down);
17
+ expect(down.defaultPrevented).toBe(true);
18
+ expect(emulator.joystickPush).toHaveBeenCalledWith(JOYSTICK_PORT_2, JOYSTICK_DIRECTION.LEFT);
19
+ const up = new KeyboardEvent('keyup', { code: 'ArrowLeft', cancelable: true });
20
+ window.dispatchEvent(up);
21
+ expect(up.defaultPrevented).toBe(true);
22
+ expect(emulator.joystickRelease).toHaveBeenCalledWith(JOYSTICK_PORT_2, JOYSTICK_DIRECTION.LEFT);
23
+ input.detach();
24
+ });
25
+ it('maps left control to fire1 and ignores held key repeats', () => {
26
+ const emulator = {
27
+ joystickPush: vi.fn(),
28
+ joystickRelease: vi.fn(),
29
+ };
30
+ const input = new EmulatorInput(emulator, window);
31
+ input.attach();
32
+ window.dispatchEvent(new KeyboardEvent('keydown', { code: 'ControlLeft', cancelable: true }));
33
+ window.dispatchEvent(new KeyboardEvent('keydown', { code: 'ControlLeft', cancelable: true }));
34
+ expect(emulator.joystickPush).toHaveBeenCalledTimes(1);
35
+ expect(emulator.joystickPush).toHaveBeenCalledWith(JOYSTICK_PORT_2, JOYSTICK_FIRE_1);
36
+ window.dispatchEvent(new KeyboardEvent('keyup', { code: 'ControlLeft', cancelable: true }));
37
+ expect(emulator.joystickRelease).toHaveBeenCalledWith(JOYSTICK_PORT_2, JOYSTICK_FIRE_1);
38
+ input.detach();
39
+ });
40
+ it('releases any held controls when detached', () => {
41
+ const emulator = {
42
+ joystickPush: vi.fn(),
43
+ joystickRelease: vi.fn(),
44
+ };
45
+ const input = new EmulatorInput(emulator, window);
46
+ input.attach();
47
+ window.dispatchEvent(new KeyboardEvent('keydown', { code: 'ArrowUp', cancelable: true }));
48
+ window.dispatchEvent(new KeyboardEvent('keydown', { code: 'ControlLeft', cancelable: true }));
49
+ input.detach();
50
+ expect(emulator.joystickRelease).toHaveBeenCalledWith(JOYSTICK_PORT_2, JOYSTICK_DIRECTION.UP);
51
+ expect(emulator.joystickRelease).toHaveBeenCalledWith(JOYSTICK_PORT_2, JOYSTICK_FIRE_1);
52
+ });
53
+ });
File without changes
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "c64-ready",
3
+ "license": "MIT",
4
+ "version": "0.5.1",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=24.14"
8
+ },
9
+ "scripts": {
10
+ "start": "npm run dev",
11
+ "dev": "vite",
12
+ "build": "tsc && vite build",
13
+ "headless:build": "npx tsc -p tsconfig.build.json",
14
+ "headless:start": "node bin/headless.mjs",
15
+ "release": "./tools/release.sh",
16
+ "preview": "vite preview",
17
+ "test": "vitest run",
18
+ "test:watch": "vitest",
19
+ "lint": "eslint src/",
20
+ "lint:fix": "eslint src/ --fix",
21
+ "format": "prettier --write src/"
22
+ },
23
+ "bin": {
24
+ "c64-headless": "bin/headless.mjs"
25
+ },
26
+ "files": [
27
+ "bin/",
28
+ "src/headless/",
29
+ "dist-ts/emulator/",
30
+ "public/c64.wasm",
31
+ "public/games/cartridges/*",
32
+ "tsconfig.build2.json"
33
+ ],
34
+ "devDependencies": {
35
+ "ts-node": "^10.9.1",
36
+ "@eslint/js": "^10.0.1",
37
+ "@types/dompurify": "^3.0.5",
38
+ "@types/gif.js": "^0.2.5",
39
+ "@types/marked": "^5.0.2",
40
+ "@types/node": "^25.5.0",
41
+ "eslint": "^10.1.0",
42
+ "eslint-config-prettier": "^10.1.8",
43
+ "eslint-plugin-prettier": "^5.5.5",
44
+ "gif.js": "^0.2.0",
45
+ "jsdom": "^26.1.0",
46
+ "prettier": "^3.8.1",
47
+ "typescript": "~5.9.3",
48
+ "typescript-eslint": "^8.57.1",
49
+ "vite": "^8.0.0-beta.13",
50
+ "vitest": "^3.2.4"
51
+ },
52
+ "dependencies": {
53
+ "dompurify": "^3.0.5",
54
+ "marked": "^5.0.2"
55
+ },
56
+ "overrides": {
57
+ "vite": "^8.0.0-beta.13"
58
+ }
59
+ }
Binary file
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Audio capture for headless operation
3
+ */
4
+
5
+ import type { AudioBuffer } from '../types';
6
+
7
+ export class AudioCapture {
8
+ private latestAudio: Float32Array | null = null;
9
+ private audioQueue: Float32Array[] = [];
10
+
11
+ capture(audio: AudioBuffer): void {
12
+ // Copy samples so the caller owns them
13
+ this.latestAudio = audio.samples.slice();
14
+ this.audioQueue.push(this.latestAudio);
15
+ }
16
+
17
+ getLatest(): Float32Array | null {
18
+ return this.latestAudio;
19
+ }
20
+
21
+ getQueued(): Float32Array[] {
22
+ const q = this.audioQueue;
23
+ this.audioQueue = [];
24
+ return q;
25
+ }
26
+
27
+ clearQueue(): void {
28
+ this.audioQueue = [];
29
+ }
30
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Headless C64 emulator for server-side streaming / testing
3
+ * Minimal MVP implementation: load WASM, wire frame/audio capture and input bridge,
4
+ * expose step/run methods for consuming frames and audio in Node environments.
5
+ */
6
+
7
+ import { C64Emulator } from '../emulator/c64-emulator';
8
+ import { FrameCapture } from './frame-capture';
9
+ import { AudioCapture } from './audio-capture';
10
+ import { InputBridge } from './input-bridge';
11
+ import type { GameLoadOptions, FrameBuffer, AudioBuffer, C64Config, InputEvent } from '../types';
12
+
13
+ export class C64Headless {
14
+ private wasmUrl: string;
15
+ private config?: Partial<C64Config>;
16
+ private emulator: C64Emulator | null = null;
17
+ private frameCapture = new FrameCapture();
18
+ private audioCapture = new AudioCapture();
19
+ readonly inputBridge = new InputBridge();
20
+
21
+ constructor(wasmUrl: string = '/src/emulator/c64.wasm', config?: Partial<C64Config>) {
22
+ this.wasmUrl = wasmUrl;
23
+ this.config = config;
24
+
25
+ // Forward remote input into the emulator when available
26
+ this.inputBridge.onInput = (ev: InputEvent) => {
27
+ this.emulator?.handleInput(ev);
28
+ };
29
+ }
30
+
31
+ /** Load and initialise the WASM emulator */
32
+ async init(): Promise<void> {
33
+ this.emulator = await C64Emulator.load(this.wasmUrl, this.config ?? {});
34
+
35
+ // Wire capture callbacks
36
+ this.emulator.onFrame = (frame: FrameBuffer) => this.frameCapture.capture(frame);
37
+ this.emulator.onAudio = (audio: AudioBuffer) => this.audioCapture.capture(audio);
38
+ }
39
+
40
+ async loadGame(options: GameLoadOptions): Promise<void> {
41
+ if (!this.emulator) throw new Error('Emulator not initialised — call init() first');
42
+ this.emulator.loadGame(options);
43
+ }
44
+
45
+ /**
46
+ * Run a single emulation tick/frame and return the captured latest frame/audio.
47
+ * This will start the emulator if it was not running, and restore the previous
48
+ * running state afterwards.
49
+ */
50
+ stepAndCapture(dTime: number = 0): { frame: Uint8Array | null; audio: Float32Array | null } {
51
+ if (!this.emulator) throw new Error('Emulator not initialised — call init() first');
52
+
53
+ const wasRunning = this.emulator.isRunning();
54
+ if (!wasRunning) this.emulator.start();
55
+
56
+ // Tick once (dTime in ms). If 0, emulator.tick will clamp to ~60fps like browser.
57
+ this.emulator.tick(dTime);
58
+
59
+ const frame = this.frameCapture.getLatest();
60
+ const audio = this.audioCapture.getLatest();
61
+
62
+ if (!wasRunning) this.emulator.pause();
63
+
64
+ return { frame, audio };
65
+ }
66
+
67
+ /**
68
+ * Continuous run loop for streaming. Calls onFrame / onAudio for every tick
69
+ * until the emulator is paused via stop().
70
+ */
71
+ async runLoop(
72
+ onFrame?: (data: Uint8Array) => void,
73
+ onAudio?: (data: Float32Array) => void,
74
+ ): Promise<void> {
75
+ if (!this.emulator) throw new Error('Emulator not initialised — call init() first');
76
+ this.emulator.start();
77
+
78
+ while (this.emulator.isRunning()) {
79
+ this.emulator.tick(0);
80
+ const frame = this.frameCapture.getLatest();
81
+ const audio = this.audioCapture.getLatest();
82
+ if (frame && onFrame) onFrame(frame);
83
+ if (audio && onAudio) onAudio(audio);
84
+ // yield to node event loop
85
+ // Use setImmediate which is available in Node; fall back to a timeout if not present
86
+ await new Promise<void>((resolve) =>
87
+ typeof (globalThis as unknown as { setImmediate?: (cb: () => void) => void })
88
+ .setImmediate === 'function'
89
+ ? (globalThis as unknown as { setImmediate?: (cb: () => void) => void }).setImmediate!(
90
+ resolve,
91
+ )
92
+ : setTimeout(resolve, 0),
93
+ );
94
+ }
95
+ }
96
+
97
+ feedInput(json: string): void {
98
+ this.inputBridge.receiveRemoteInput(json);
99
+ }
100
+
101
+ stop(): void {
102
+ this.emulator?.pause();
103
+ }
104
+ }