c64-ready 1.2.0 → 2.1.0

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.
Files changed (88) hide show
  1. package/README.md +17 -12
  2. package/dist/assets/index-Df2-qP_u.js +169 -0
  3. package/dist/index.html +1 -1
  4. package/dist-ts/emulator/c64-emulator.d.ts +3 -6
  5. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  6. package/dist-ts/emulator/c64-emulator.js +17 -46
  7. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  8. package/dist-ts/emulator/c64-wasm.d.ts +1 -1
  9. package/dist-ts/emulator/input.d.ts +9 -6
  10. package/dist-ts/emulator/input.d.ts.map +1 -1
  11. package/dist-ts/emulator/input.js +48 -56
  12. package/dist-ts/emulator/input.js.map +1 -1
  13. package/dist-ts/headless/audio-capture.d.ts +1 -1
  14. package/dist-ts/headless/c64-headless.d.ts +2 -2
  15. package/dist-ts/headless/c64-headless.js +4 -4
  16. package/dist-ts/headless/frame-capture.d.ts +1 -1
  17. package/dist-ts/headless/input-bridge.d.ts +1 -1
  18. package/dist-ts/player/audio-engine.d.ts +73 -0
  19. package/dist-ts/player/audio-engine.d.ts.map +1 -0
  20. package/dist-ts/{src/player → player}/audio-engine.js +7 -2
  21. package/dist-ts/player/audio-engine.js.map +1 -0
  22. package/dist-ts/player/c64-player.d.ts +72 -0
  23. package/dist-ts/player/c64-player.d.ts.map +1 -0
  24. package/dist-ts/player/c64-player.js +425 -0
  25. package/dist-ts/player/c64-player.js.map +1 -0
  26. package/dist-ts/player/canvas-renderer.d.ts +21 -0
  27. package/dist-ts/player/canvas-renderer.d.ts.map +1 -0
  28. package/dist-ts/{src/player → player}/canvas-renderer.js +55 -44
  29. package/dist-ts/player/canvas-renderer.js.map +1 -0
  30. package/dist-ts/player/index.d.ts +8 -0
  31. package/dist-ts/player/index.d.ts.map +1 -0
  32. package/dist-ts/player/index.js +5 -0
  33. package/dist-ts/player/index.js.map +1 -0
  34. package/dist-ts/player/input-handler.d.ts +21 -0
  35. package/dist-ts/player/input-handler.d.ts.map +1 -0
  36. package/dist-ts/player/input-handler.js +122 -0
  37. package/dist-ts/player/input-handler.js.map +1 -0
  38. package/dist-ts/player/load-formats.d.ts +15 -0
  39. package/dist-ts/player/load-formats.d.ts.map +1 -0
  40. package/dist-ts/player/load-formats.js +38 -0
  41. package/dist-ts/player/load-formats.js.map +1 -0
  42. package/dist-ts/player/ui-controller.d.ts +44 -0
  43. package/dist-ts/player/ui-controller.d.ts.map +1 -0
  44. package/dist-ts/player/ui-controller.js +844 -0
  45. package/dist-ts/player/ui-controller.js.map +1 -0
  46. package/dist-ts/types/emulator.d.ts +1 -1
  47. package/dist-ts/types/emulator.d.ts.map +1 -1
  48. package/package.json +31 -3
  49. package/src/emulator/c64-emulator.ts +15 -5
  50. package/src/player/audio-engine.ts +13 -2
  51. package/src/player/c64-player.ts +140 -58
  52. package/src/player/canvas-renderer.ts +57 -5
  53. package/src/player/index.ts +7 -0
  54. package/src/player/ui-controller.ts +34 -14
  55. package/src/types/emulator.ts +1 -1
  56. package/dist/assets/CHANGELOG-0a7A8Ekq.js +0 -391
  57. package/dist/assets/index-BESofQoh.js +0 -627
  58. package/dist-ts/emulator/c64-emulator.test.js +0 -104
  59. package/dist-ts/emulator/c64-wasm.test.js +0 -65
  60. package/dist-ts/emulator/input.test.js +0 -53
  61. package/dist-ts/src/counter.js +0 -9
  62. package/dist-ts/src/emulator/c64-emulator.js +0 -308
  63. package/dist-ts/src/emulator/c64-emulator.test.js +0 -104
  64. package/dist-ts/src/emulator/c64-wasm.js +0 -149
  65. package/dist-ts/src/emulator/c64-wasm.test.js +0 -65
  66. package/dist-ts/src/emulator/constants.js +0 -9
  67. package/dist-ts/src/emulator/input.js +0 -62
  68. package/dist-ts/src/emulator/input.test.js +0 -53
  69. package/dist-ts/src/emulator/memory.js +0 -1
  70. package/dist-ts/src/headless/audio-capture.js +0 -23
  71. package/dist-ts/src/headless/c64-headless.js +0 -85
  72. package/dist-ts/src/headless/ffmpeg-runner.js +0 -33
  73. package/dist-ts/src/headless/frame-capture.js +0 -23
  74. package/dist-ts/src/headless/headless.cli.test.js +0 -46
  75. package/dist-ts/src/headless/input-bridge.js +0 -37
  76. package/dist-ts/src/main.js +0 -57
  77. package/dist-ts/src/player/audio-engine.test.js +0 -284
  78. package/dist-ts/src/player/c64-player.js +0 -105
  79. package/dist-ts/src/player/c64-player.test.js +0 -165
  80. package/dist-ts/src/player/canvas-renderer.test.js +0 -135
  81. package/dist-ts/src/player/input-handler.js +0 -13
  82. package/dist-ts/src/player/ui-controller.js +0 -575
  83. package/dist-ts/src/player/ui-controller.test.js +0 -67
  84. package/dist-ts/src/types/emulator.js +0 -1
  85. package/dist-ts/src/types/index.js +0 -4
  86. package/dist-ts/tools/run-wrapper.js +0 -36
  87. /package/dist/assets/{marked.esm-BOXuzyNF.js → marked.esm--kBm026b.js} +0 -0
  88. /package/dist/assets/{purify.es-y41lKIN9.js → purify.es-BcoGFDcJ.js} +0 -0
@@ -1,149 +0,0 @@
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
- }
@@ -1,65 +0,0 @@
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
- });
@@ -1,9 +0,0 @@
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;
@@ -1,62 +0,0 @@
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
- }
@@ -1,53 +0,0 @@
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
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,23 +0,0 @@
1
- /**
2
- * Audio capture for headless operation
3
- */
4
- export class AudioCapture {
5
- latestAudio = null;
6
- audioQueue = [];
7
- capture(audio) {
8
- // Copy samples so the caller owns them
9
- this.latestAudio = audio.samples.slice();
10
- this.audioQueue.push(this.latestAudio);
11
- }
12
- getLatest() {
13
- return this.latestAudio;
14
- }
15
- getQueued() {
16
- const q = this.audioQueue;
17
- this.audioQueue = [];
18
- return q;
19
- }
20
- clearQueue() {
21
- this.audioQueue = [];
22
- }
23
- }
@@ -1,85 +0,0 @@
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
- import { C64Emulator } from '../emulator/c64-emulator';
7
- import { FrameCapture } from './frame-capture';
8
- import { AudioCapture } from './audio-capture';
9
- import { InputBridge } from './input-bridge';
10
- export class C64Headless {
11
- wasmUrl;
12
- config;
13
- emulator = null;
14
- frameCapture = new FrameCapture();
15
- audioCapture = new AudioCapture();
16
- inputBridge = new InputBridge();
17
- constructor(wasmUrl = '/src/emulator/c64.wasm', config) {
18
- this.wasmUrl = wasmUrl;
19
- this.config = config;
20
- // Forward remote input into the emulator when available
21
- this.inputBridge.onInput = (ev) => {
22
- this.emulator?.handleInput(ev);
23
- };
24
- }
25
- /** Load and initialise the WASM emulator */
26
- async init() {
27
- this.emulator = await C64Emulator.load(this.wasmUrl, this.config ?? {});
28
- // Wire capture callbacks
29
- this.emulator.onFrame = (frame) => this.frameCapture.capture(frame);
30
- this.emulator.onAudio = (audio) => this.audioCapture.capture(audio);
31
- }
32
- async loadGame(options) {
33
- if (!this.emulator)
34
- throw new Error('Emulator not initialised — call init() first');
35
- this.emulator.loadGame(options);
36
- }
37
- /**
38
- * Run a single emulation tick/frame and return the captured latest frame/audio.
39
- * This will start the emulator if it was not running, and restore the previous
40
- * running state afterwards.
41
- */
42
- stepAndCapture(dTime = 0) {
43
- if (!this.emulator)
44
- throw new Error('Emulator not initialised — call init() first');
45
- const wasRunning = this.emulator.isRunning();
46
- if (!wasRunning)
47
- this.emulator.start();
48
- // Tick once (dTime in ms). If 0, emulator.tick will clamp to ~60fps like browser.
49
- this.emulator.tick(dTime);
50
- const frame = this.frameCapture.getLatest();
51
- const audio = this.audioCapture.getLatest();
52
- if (!wasRunning)
53
- this.emulator.pause();
54
- return { frame, audio };
55
- }
56
- /**
57
- * Continuous run loop for streaming. Calls onFrame / onAudio for every tick
58
- * until the emulator is paused via stop().
59
- */
60
- async runLoop(onFrame, onAudio) {
61
- if (!this.emulator)
62
- throw new Error('Emulator not initialised — call init() first');
63
- this.emulator.start();
64
- // eslint-disable-next-line no-constant-condition
65
- while (this.emulator.isRunning()) {
66
- this.emulator.tick(0);
67
- const frame = this.frameCapture.getLatest();
68
- const audio = this.audioCapture.getLatest();
69
- if (frame && onFrame)
70
- onFrame(frame);
71
- if (audio && onAudio)
72
- onAudio(audio);
73
- // yield to node event loop
74
- // Use setImmediate which is available in Node; fall back to a timeout if not present
75
- // @ts-ignore
76
- await new Promise((resolve) => (typeof setImmediate === 'function' ? setImmediate(resolve) : setTimeout(resolve, 0)));
77
- }
78
- }
79
- feedInput(json) {
80
- this.inputBridge.receiveRemoteInput(json);
81
- }
82
- stop() {
83
- this.emulator?.pause();
84
- }
85
- }
@@ -1,33 +0,0 @@
1
- /**
2
- * Minimal FFmpeg runner stub for headless MVP.
3
- *
4
- * This file provides a very small wrapper around child_process spawn to demonstrate
5
- * how frames/audio could be piped to an ffmpeg process. For the MVP we expose a
6
- * start/stop API but do not implement the full piping logic — this keeps the
7
- * library safe to run in browser builds while remaining useful in Node.
8
- */
9
- export class FFmpegRunner {
10
- proc = null;
11
- /**
12
- * Start ffmpeg with the provided args. Returns true if spawn succeeded.
13
- * In browser builds this will be a no-op and return false.
14
- */
15
- start(args) {
16
- try {
17
- // Lazy require so browser builds don't attempt to bundle child_process
18
- // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
19
- const child = require('child_process');
20
- this.proc = child.spawn('ffmpeg', args, { stdio: 'ignore' });
21
- return !!this.proc;
22
- }
23
- catch (err) {
24
- return false;
25
- }
26
- }
27
- stop() {
28
- if (this.proc && typeof this.proc.kill === 'function') {
29
- this.proc.kill('SIGINT');
30
- }
31
- this.proc = null;
32
- }
33
- }
@@ -1,23 +0,0 @@
1
- /**
2
- * Frame capture for headless operation
3
- */
4
- export class FrameCapture {
5
- latestFrame = null;
6
- frameQueue = [];
7
- capture(frame) {
8
- // Store latest frame (copy to ensure consumer owns the buffer)
9
- this.latestFrame = frame.data.slice();
10
- this.frameQueue.push(this.latestFrame);
11
- }
12
- getLatest() {
13
- return this.latestFrame;
14
- }
15
- getQueued() {
16
- const q = this.frameQueue;
17
- this.frameQueue = [];
18
- return q;
19
- }
20
- clearQueue() {
21
- this.frameQueue = [];
22
- }
23
- }
@@ -1,46 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import fs from 'fs/promises';
3
- import path from 'path';
4
- import { runHeadless } from './headless-cli.mjs';
5
- describe('headless CLI', () => {
6
- it('runs with fake wasm instantiate and loads game', async () => {
7
- // create temp files inside repo temp dir
8
- const repoRoot = path.resolve(__dirname, '..', '..');
9
- const tmpDir = path.join(repoRoot, 'temp', 'test-headless');
10
- await fs.mkdir(tmpDir, { recursive: true });
11
- const wasmPath = path.join(tmpDir, 'fake.wasm');
12
- const crtPath = path.join(tmpDir, 'game.crt');
13
- await fs.writeFile(wasmPath, Buffer.from([0, 1, 2, 3]));
14
- await fs.writeFile(crtPath, Buffer.from([1, 2, 3, 4]));
15
- // fake instantiate that provides minimal exports
16
- const fakeInstantiate = async (_bin, importObject) => {
17
- const memory = importObject.env.memory;
18
- // prepare a memory buffer large enough
19
- const exports = {
20
- memory,
21
- malloc: (n) => {
22
- // simple bump allocator at offset 1024
23
- if (!exports._ptr)
24
- exports._ptr = 1024;
25
- const p = exports._ptr;
26
- exports._ptr += n + 16;
27
- return p;
28
- },
29
- free: (_p) => { },
30
- c64_loadCartridge: (_ptr, _len) => { },
31
- __wasm_call_ctors: () => { },
32
- c64_init: () => { },
33
- debugger_play: () => { },
34
- debugger_update: (_dt) => { },
35
- c64_getCycleCount: () => 123,
36
- };
37
- return { instance: { exports } };
38
- };
39
- const res = await runHeadless({ argv: ['--wasm', wasmPath, '--game', crtPath, '--frames', '2', '--verify'], instantiateFn: fakeInstantiate, repoRoot });
40
- expect(res.ok).toBe(true);
41
- // startup message
42
- expect(res.output.some((l) => l.includes('Starting headless C64'))).toBe(true);
43
- // run complete
44
- expect(res.output.some((l) => l.includes('Run complete. frames=2'))).toBe(true);
45
- });
46
- });
@@ -1,37 +0,0 @@
1
- /**
2
- * Remote input bridge (WebSocket → emulator)
3
- * Allows remote players to control the emulator
4
- */
5
- export class InputBridge {
6
- onInput;
7
- /**
8
- * Called when a remote input arrives (e.g., from WebSocket)
9
- */
10
- receiveRemoteInput(jsonString) {
11
- try {
12
- const event = JSON.parse(jsonString);
13
- if (this.onInput) {
14
- this.onInput(event);
15
- }
16
- }
17
- catch (err) {
18
- // Keep minimal dependency on console in headless mode
19
- // eslint-disable-next-line no-console
20
- console.error('Failed to parse input:', err);
21
- }
22
- }
23
- /**
24
- * Example: encode a keypress for transmission
25
- */
26
- static encodeKeypress(key) {
27
- return JSON.stringify({ type: 'key', key });
28
- }
29
- static encodeJoystick(port, direction, fire) {
30
- return JSON.stringify({
31
- type: 'joystick',
32
- joystickPort: port,
33
- direction,
34
- fire,
35
- });
36
- }
37
- }
@@ -1,57 +0,0 @@
1
- import { C64Player } from './player/c64-player';
2
- import CanvasRenderer from './player/canvas-renderer';
3
- import UIController from './player/ui-controller';
4
- const status = document.getElementById('status');
5
- const renderer = new CanvasRenderer('c64-screen');
6
- const base = import.meta.env.BASE_URL;
7
- // Create player and keep in outer scope so UI can trigger file loads
8
- const player = new C64Player({
9
- wasmUrl: `${base}c64.wasm`,
10
- gameUrl: `${base}games/cartridges/legend-of-wilf.crt`,
11
- renderer,
12
- onProgress: (pct, label) => renderer.setProgress(pct, label),
13
- });
14
- // Initialise UI with reference to the player (for audio controls)
15
- new UIController().init(player);
16
- player
17
- .start()
18
- .then(() => {
19
- renderer.hideLoader();
20
- })
21
- .catch((err) => {
22
- console.error(err);
23
- renderer.setError('ERROR');
24
- status.textContent = `Error: ${err}`;
25
- status.style.color = '#f44';
26
- });
27
- const updateFavicon = () => {
28
- const isDimmed = document.hidden;
29
- const link = document.querySelector("link[rel~='icon']");
30
- const fileName = isDimmed ? 'led-off.svg' : 'led-on.svg';
31
- const fullPath = `${base}${fileName}`.replace(/\/+/g, '/');
32
- if (link) {
33
- link.href = fullPath;
34
- }
35
- };
36
- document.addEventListener('visibilitychange', updateFavicon);
37
- window.addEventListener('focus', updateFavicon);
38
- window.addEventListener('blur', updateFavicon);
39
- updateFavicon();
40
- // Listen for files selected via the UI and load into the emulator
41
- window.addEventListener('c64-load-file', async (e) => {
42
- const detail = e.detail;
43
- const file = detail?.file;
44
- if (!file)
45
- return;
46
- try {
47
- renderer.showLoader?.();
48
- await player.loadFile(file);
49
- renderer.hideLoader?.();
50
- }
51
- catch (err) {
52
- console.error(err);
53
- renderer.setError?.('LOAD ERROR');
54
- status.textContent = `Load error: ${err}`;
55
- status.style.color = '#f44';
56
- }
57
- });