c64-ready 0.5.1 → 0.6.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.
Files changed (117) hide show
  1. package/README.md +332 -96
  2. package/bin/headless.mjs +7 -3
  3. package/bin/serve.mjs +164 -0
  4. package/dist/assets/CHANGELOG-C1nvP1iO.js +96 -0
  5. package/dist/assets/index-Cioamf6E.js +394 -0
  6. package/dist/assets/marked.esm-BOXuzyNF.js +37 -0
  7. package/dist/assets/purify.es-y41lKIN9.js +2 -0
  8. package/dist/audio-worklet-processor.js +83 -0
  9. package/dist/c64-ready/c64-ready.gif +0 -0
  10. package/dist/c64-ready/index.html +58 -0
  11. package/dist/c64.wasm +0 -0
  12. package/dist/games/cartridges/legend-of-wilf.crt +0 -0
  13. package/dist/index.html +38 -0
  14. package/dist/led-off.svg +20 -0
  15. package/dist/led-on.svg +27 -0
  16. package/dist/vite.svg +15 -0
  17. package/dist-ts/emulator/c64-emulator.d.ts +107 -0
  18. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -0
  19. package/dist-ts/emulator/c64-emulator.js +13 -1
  20. package/dist-ts/emulator/c64-emulator.js.map +1 -0
  21. package/dist-ts/emulator/c64-wasm.d.ts +42 -0
  22. package/dist-ts/emulator/c64-wasm.d.ts.map +1 -0
  23. package/dist-ts/emulator/c64-wasm.js +1 -0
  24. package/dist-ts/emulator/c64-wasm.js.map +1 -0
  25. package/dist-ts/emulator/constants.d.ts +14 -0
  26. package/dist-ts/emulator/constants.d.ts.map +1 -0
  27. package/dist-ts/emulator/constants.js +1 -0
  28. package/dist-ts/emulator/constants.js.map +1 -0
  29. package/dist-ts/emulator/input.d.ts +33 -0
  30. package/dist-ts/emulator/input.d.ts.map +1 -0
  31. package/dist-ts/emulator/input.js +26 -5
  32. package/dist-ts/emulator/input.js.map +1 -0
  33. package/dist-ts/emulator/memory.d.ts +2 -0
  34. package/dist-ts/emulator/memory.d.ts.map +1 -0
  35. package/dist-ts/emulator/memory.js +9 -0
  36. package/dist-ts/emulator/memory.js.map +1 -0
  37. package/dist-ts/headless/audio-capture.d.ts +13 -0
  38. package/dist-ts/headless/audio-capture.d.ts.map +1 -0
  39. package/dist-ts/headless/audio-capture.js +24 -0
  40. package/dist-ts/headless/audio-capture.js.map +1 -0
  41. package/dist-ts/headless/c64-headless.d.ts +36 -0
  42. package/dist-ts/headless/c64-headless.d.ts.map +1 -0
  43. package/dist-ts/headless/c64-headless.js +87 -0
  44. package/dist-ts/headless/c64-headless.js.map +1 -0
  45. package/dist-ts/headless/ffmpeg-runner.d.ts +18 -0
  46. package/dist-ts/headless/ffmpeg-runner.d.ts.map +1 -0
  47. package/dist-ts/headless/ffmpeg-runner.js +67 -0
  48. package/dist-ts/headless/ffmpeg-runner.js.map +1 -0
  49. package/dist-ts/headless/frame-capture.d.ts +13 -0
  50. package/dist-ts/headless/frame-capture.d.ts.map +1 -0
  51. package/dist-ts/headless/frame-capture.js +24 -0
  52. package/dist-ts/headless/frame-capture.js.map +1 -0
  53. package/dist-ts/headless/input-bridge.d.ts +21 -0
  54. package/dist-ts/headless/input-bridge.d.ts.map +1 -0
  55. package/dist-ts/headless/input-bridge.js +41 -0
  56. package/dist-ts/headless/input-bridge.js.map +1 -0
  57. package/dist-ts/src/counter.js +9 -0
  58. package/dist-ts/src/emulator/c64-emulator.js +308 -0
  59. package/dist-ts/src/emulator/c64-emulator.test.js +104 -0
  60. package/dist-ts/src/emulator/c64-wasm.js +149 -0
  61. package/dist-ts/src/emulator/c64-wasm.test.js +65 -0
  62. package/dist-ts/src/emulator/constants.js +9 -0
  63. package/dist-ts/src/emulator/input.js +62 -0
  64. package/dist-ts/src/emulator/input.test.js +53 -0
  65. package/dist-ts/src/emulator/memory.js +1 -0
  66. package/dist-ts/src/headless/audio-capture.js +23 -0
  67. package/dist-ts/src/headless/c64-headless.js +85 -0
  68. package/dist-ts/src/headless/ffmpeg-runner.js +33 -0
  69. package/dist-ts/src/headless/frame-capture.js +23 -0
  70. package/dist-ts/src/headless/headless.cli.test.js +46 -0
  71. package/dist-ts/src/headless/input-bridge.js +37 -0
  72. package/dist-ts/src/main.js +57 -0
  73. package/dist-ts/src/player/audio-engine.js +175 -0
  74. package/dist-ts/src/player/audio-engine.test.js +284 -0
  75. package/dist-ts/src/player/c64-player.js +105 -0
  76. package/dist-ts/src/player/c64-player.test.js +165 -0
  77. package/dist-ts/src/player/canvas-renderer.js +148 -0
  78. package/dist-ts/src/player/canvas-renderer.test.js +135 -0
  79. package/dist-ts/src/player/input-handler.js +13 -0
  80. package/dist-ts/src/player/ui-controller.js +575 -0
  81. package/dist-ts/src/player/ui-controller.test.js +67 -0
  82. package/dist-ts/src/types/emulator.js +1 -0
  83. package/dist-ts/src/types/index.js +4 -0
  84. package/dist-ts/tools/run-wrapper.js +36 -0
  85. package/dist-ts/types/emulator.d.ts +128 -0
  86. package/dist-ts/types/emulator.d.ts.map +1 -0
  87. package/dist-ts/types/emulator.js +2 -0
  88. package/dist-ts/types/emulator.js.map +1 -0
  89. package/dist-ts/types/index.d.ts +51 -0
  90. package/dist-ts/types/index.d.ts.map +1 -0
  91. package/dist-ts/types/index.js +5 -0
  92. package/dist-ts/types/index.js.map +1 -0
  93. package/package.json +40 -6
  94. package/public/audio-worklet-processor.js +83 -0
  95. package/public/led-off.svg +20 -0
  96. package/public/led-on.svg +27 -0
  97. package/src/counter.ts +9 -0
  98. package/src/emulator/c64-emulator.ts +357 -0
  99. package/src/emulator/c64-wasm.ts +180 -0
  100. package/src/emulator/constants.ts +22 -0
  101. package/src/emulator/input.ts +105 -0
  102. package/src/emulator/memory.ts +9 -0
  103. package/src/headless/headless-cli.mjs +105 -19
  104. package/src/headless/input-bridge.ts +13 -4
  105. package/src/headless/input-server.mjs +76 -0
  106. package/src/main.ts +80 -0
  107. package/src/player/audio-engine.ts +216 -0
  108. package/src/player/c64-player.ts +222 -0
  109. package/src/player/canvas-renderer.ts +139 -0
  110. package/src/player/input-handler.ts +116 -0
  111. package/src/player/styles/canvas-renderer.css +41 -0
  112. package/src/player/styles/ui-controller.css +286 -0
  113. package/src/player/ui-controller.ts +485 -0
  114. package/src/style.css +96 -0
  115. package/src/types/emulator.ts +167 -0
  116. package/src/types/index.ts +62 -0
  117. package/src/typescript.svg +1 -0
@@ -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
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
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
+ }
@@ -0,0 +1,85 @@
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
+ }
@@ -0,0 +1,33 @@
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
+ }
@@ -0,0 +1,23 @@
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
+ }
@@ -0,0 +1,46 @@
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
+ });
@@ -0,0 +1,37 @@
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
+ }
@@ -0,0 +1,57 @@
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
+ });
@@ -0,0 +1,175 @@
1
+ /**
2
+ * AudioEngine — Web Audio playback for the C64 emulator.
3
+ *
4
+ * Uses AudioWorkletNode (modern API, replaces deprecated ScriptProcessorNode).
5
+ * Replicates the original c64.js audio model using a **pull** approach:
6
+ *
7
+ * - The SID writes into a 4096-sample circular buffer as CPU cycles run.
8
+ * - The AudioWorklet processor runs on the audio thread and outputs samples
9
+ * from a ring buffer. When the ring buffer runs low it posts a
10
+ * `'need-samples'` message back to the main thread.
11
+ * - The main thread reads the current SID buffer snapshot via a registered
12
+ * reader function and posts the samples to the worklet.
13
+ *
14
+ * All timing is driven by the audio hardware clock — no setInterval drift.
15
+ *
16
+ * Also supports:
17
+ * - Auto-play detection with deferred resume on user gesture
18
+ * - Mute / unmute
19
+ * - Volume control (0–1)
20
+ */
21
+ const DEFAULT_SAMPLE_RATE = 44_100;
22
+ export class AudioEngine {
23
+ ctx = null;
24
+ workletNode = null;
25
+ gainNode = null;
26
+ _muted = false;
27
+ _volume = 0.75;
28
+ _suspended = true;
29
+ _initialised = false;
30
+ _ready = false;
31
+ /** Called when the worklet needs more samples */
32
+ _readSidBuffer = null;
33
+ /** Optional callback fired whenever muted / volume / suspended state changes */
34
+ onStateChange;
35
+ // ── Public getters ────────────────────────────────────────────────────────
36
+ get muted() {
37
+ return this._muted;
38
+ }
39
+ get volume() {
40
+ return this._volume;
41
+ }
42
+ get suspended() {
43
+ return this._suspended;
44
+ }
45
+ get ready() {
46
+ return this._ready;
47
+ }
48
+ get sampleRate() {
49
+ return this.ctx?.sampleRate ?? DEFAULT_SAMPLE_RATE;
50
+ }
51
+ // ── Init ──────────────────────────────────────────────────────────────────
52
+ /**
53
+ * Create the AudioContext and AudioWorklet. Returns `true` if audio is
54
+ * playing immediately, `false` if the browser blocked autoplay.
55
+ */
56
+ async init() {
57
+ if (this._initialised)
58
+ return !this._suspended;
59
+ this._initialised = true;
60
+ try {
61
+ this.ctx = new AudioContext({ sampleRate: DEFAULT_SAMPLE_RATE });
62
+ this.gainNode = this.ctx.createGain();
63
+ this.gainNode.gain.value = this._volume;
64
+ this.gainNode.connect(this.ctx.destination);
65
+ this.ctx.addEventListener('statechange', () => {
66
+ const wasSuspended = this._suspended;
67
+ this._suspended = this.ctx?.state === 'suspended';
68
+ if (wasSuspended !== this._suspended) {
69
+ this.fireStateChange();
70
+ }
71
+ });
72
+ this._suspended = this.ctx.state === 'suspended';
73
+ await this.loadWorklet();
74
+ // Attempt to resume (may fail due to autoplay policy)
75
+ if (this._suspended) {
76
+ this.ctx.resume().catch(() => { });
77
+ this._suspended = this.ctx.state === 'suspended';
78
+ }
79
+ this.fireStateChange();
80
+ return !this._suspended;
81
+ }
82
+ catch {
83
+ // AudioContext unavailable (e.g. test environment) — silently degrade
84
+ return false;
85
+ }
86
+ }
87
+ async loadWorklet() {
88
+ if (!this.ctx || !this.gainNode)
89
+ return;
90
+ const base = import.meta.env.BASE_URL ?? '/';
91
+ const processorUrl = `${base}audio-worklet-processor.js`.replace(/\/+/g, '/');
92
+ await this.ctx.audioWorklet.addModule(processorUrl);
93
+ this.workletNode = new AudioWorkletNode(this.ctx, 'c64-audio-processor', {
94
+ outputChannelCount: [1],
95
+ });
96
+ this.workletNode.connect(this.gainNode);
97
+ // Listen for pull requests from the worklet
98
+ this.workletNode.port.onmessage = () => {
99
+ this.feedWorklet();
100
+ };
101
+ this._ready = true;
102
+ }
103
+ // ── SID buffer reader ─────────────────────────────────────────────────────
104
+ /**
105
+ * Register a function that reads the current SID audio buffer.
106
+ * The engine calls this when the worklet requests more samples.
107
+ */
108
+ setSidBufferReader(reader) {
109
+ this._readSidBuffer = reader;
110
+ }
111
+ // ── Sample feeding ────────────────────────────────────────────────────────
112
+ /** Respond to a pull request from the worklet with fresh SID data */
113
+ feedWorklet() {
114
+ if (!this.workletNode || !this._readSidBuffer || this._suspended)
115
+ return;
116
+ const samples = this._readSidBuffer();
117
+ if (samples && samples.length > 0) {
118
+ this.workletNode.port.postMessage(samples);
119
+ }
120
+ }
121
+ // ── Playback controls ────────────────────────────────────────────────────
122
+ async resume() {
123
+ if (!this.ctx)
124
+ return;
125
+ try {
126
+ await this.ctx.resume();
127
+ this._suspended = this.ctx.state === 'suspended';
128
+ this.fireStateChange();
129
+ }
130
+ catch (err) {
131
+ console.error('AudioEngine: resume failed', err);
132
+ }
133
+ }
134
+ setMuted(muted) {
135
+ this._muted = muted;
136
+ if (this.gainNode) {
137
+ this.gainNode.gain.value = muted ? 0 : this._volume;
138
+ }
139
+ this.fireStateChange();
140
+ }
141
+ toggleMute() {
142
+ this.setMuted(!this._muted);
143
+ }
144
+ setVolume(v) {
145
+ this._volume = Math.max(0, Math.min(1, v));
146
+ if (this.gainNode && !this._muted) {
147
+ this.gainNode.gain.value = this._volume;
148
+ }
149
+ this.fireStateChange();
150
+ }
151
+ adjustVolume(delta) {
152
+ this.setVolume(this._volume + delta);
153
+ }
154
+ // ── Teardown ──────────────────────────────────────────────────────────────
155
+ async destroy() {
156
+ this.workletNode?.disconnect();
157
+ this.gainNode?.disconnect();
158
+ await this.ctx?.close();
159
+ this.workletNode = null;
160
+ this.gainNode = null;
161
+ this.ctx = null;
162
+ this._initialised = false;
163
+ this._ready = false;
164
+ this._suspended = true;
165
+ this._readSidBuffer = null;
166
+ }
167
+ // ── Internal ──────────────────────────────────────────────────────────────
168
+ fireStateChange() {
169
+ this.onStateChange?.({
170
+ muted: this._muted,
171
+ volume: this._volume,
172
+ suspended: this._suspended,
173
+ });
174
+ }
175
+ }