c64-ready 0.5.1 → 0.6.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 (117) hide show
  1. package/README.md +332 -96
  2. package/bin/headless.mjs +7 -3
  3. package/bin/serve.mjs +162 -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
@@ -1,6 +1,6 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
- import { fileURLToPath } from 'url';
3
+ import {fileURLToPath} from 'url';
4
4
  import FFmpegRunner from './ffmpeg-runner.mjs';
5
5
 
6
6
  /**
@@ -26,6 +26,8 @@ export async function runHeadless(options = {}) {
26
26
  let raw = false;
27
27
  let output = null;
28
28
  let durationSec = 0; // 0 means no --duration was passed → stream forever when recording
29
+ let enableInput = false;
30
+ let wsPort = 9001;
29
31
  for (let i = 0; i < argv.length; i++) {
30
32
  const a = argv[i];
31
33
  if (a === '--wasm' || a === '-w') wasmArg = argv[++i];
@@ -42,8 +44,10 @@ export async function runHeadless(options = {}) {
42
44
  else if (a === '--fps') fps = Number(argv[++i]);
43
45
  else if (a === '--use-fixed-dt') useFixedDt = true;
44
46
  else if (a === '--use-wall-clock') useFixedDt = false;
47
+ else if (a === '--input') enableInput = true;
48
+ else if (a === '--ws-port') wsPort = Number(argv[++i]);
45
49
  else if (a === '--help' || a === '-h') {
46
- return { ok: false, output: 'help' };
50
+ return {ok: false, output: 'help'};
47
51
  }
48
52
  }
49
53
 
@@ -60,7 +64,8 @@ export async function runHeadless(options = {}) {
60
64
  try {
61
65
  await fs.access(p);
62
66
  return p;
63
- } catch (_) {}
67
+ } catch (_) {
68
+ }
64
69
  }
65
70
  return null;
66
71
  }
@@ -70,7 +75,7 @@ export async function runHeadless(options = {}) {
70
75
  const found = await findFirstExisting(defaultWasmPaths);
71
76
  if (found) wasmPath = found;
72
77
  }
73
- if (!wasmPath) return { ok: false, err: 'no-wasm' };
78
+ if (!wasmPath) return {ok: false, err: 'no-wasm'};
74
79
 
75
80
  let gamePath = gameArg ?? null;
76
81
  // If the user requested no game, ensure we do not load any default cartridge
@@ -101,8 +106,8 @@ export async function runHeadless(options = {}) {
101
106
  );
102
107
  if (typeof instantiateFn === 'function') {
103
108
  try {
104
- const mem = new WebAssembly.Memory({ initial: 256 });
105
- const importObject = { env: { memory: mem }, wasi_snapshot_preview1: {} };
109
+ const mem = new WebAssembly.Memory({initial: 256});
110
+ const importObject = {env: {memory: mem}, wasi_snapshot_preview1: {}};
106
111
  const res = await instantiateFn(wasmAb, importObject);
107
112
  const inst = res && (res.instance ?? res);
108
113
  exports = inst.exports ?? inst;
@@ -110,7 +115,7 @@ export async function runHeadless(options = {}) {
110
115
  if (exports && !exports.memory) exports.memory = mem;
111
116
  if (exports && exports.memory) {
112
117
  const buf = exports.memory.buffer;
113
- heap = { heapU8: new Uint8Array(buf), heapF32: new Float32Array(buf), heapU32: new Uint32Array(buf) };
118
+ heap = {heapU8: new Uint8Array(buf), heapF32: new Float32Array(buf), heapU32: new Uint32Array(buf)};
114
119
  }
115
120
  if (exports && typeof exports.c64_init === 'function') exports.c64_init();
116
121
  if (exports && typeof exports.sid_setSampleRate === 'function') exports.sid_setSampleRate(44100);
@@ -187,7 +192,58 @@ export async function runHeadless(options = {}) {
187
192
  if (!wrapperUsed) {
188
193
  out.push('ERROR: dist-ts wrapper failed to load — cannot run headless');
189
194
  console.error('[headless] FATAL: dist-ts wrapper unavailable. Run: npx tsc -p tsconfig.build2.json');
190
- return { ok: false, output: out };
195
+ return {ok: false, output: out};
196
+ }
197
+
198
+ // ── Input server (WebSocket) ──────────────────────────────────────────────
199
+ // Start the embedded WebSocket input server when --input is passed.
200
+ // Remote clients connect and send JSON InputEvent messages which are
201
+ // forwarded directly to the WASM joystick/keyboard exports.
202
+ let inputServer = null;
203
+ if (enableInput) {
204
+ try {
205
+ const { createInputServer } = await import('./input-server.mjs');
206
+ const dirMap = { up: 0x1, down: 0x2, left: 0x4, right: 0x8 };
207
+ inputServer = createInputServer({
208
+ port: wsPort,
209
+ verbose,
210
+ onInput: (event) => {
211
+ if (!exports) return;
212
+ try {
213
+ if (event.type === 'joystick') {
214
+ const port = ((event.joystickPort ?? 2) - 1); // 1-based → 0-based
215
+ const dir = event.direction ? (dirMap[event.direction] ?? 0) : 0;
216
+ const fire = (event.fire || event.fire1) ? 0x10 : 0;
217
+
218
+ if (event.action === 'release') {
219
+ if (dir) exports.c64_joystick_release(port, dir);
220
+ if (fire) exports.c64_joystick_release(port, fire);
221
+ } else {
222
+ // Default to push for backwards compat (action missing)
223
+ if (dir) exports.c64_joystick_push(port, dir);
224
+ if (fire) exports.c64_joystick_push(port, fire);
225
+ }
226
+ } else if (event.type === 'key') {
227
+ const keyCode = Number(event.key);
228
+ if (!Number.isNaN(keyCode)) {
229
+ if (event.action === 'up') {
230
+ exports.keyboard_keyReleased(keyCode);
231
+ } else {
232
+ // Default to keyPressed for backwards compat (action missing)
233
+ exports.keyboard_keyPressed(keyCode);
234
+ }
235
+ }
236
+ }
237
+ } catch (err) {
238
+ if (verbose) console.error('[headless] input dispatch error:', err);
239
+ }
240
+ },
241
+ });
242
+ out.push(`Input server listening on ws://0.0.0.0:${wsPort}`);
243
+ } catch (e) {
244
+ console.error('[headless] Failed to start input server:', e && e.message ? e.message : e);
245
+ out.push(`input-server-failed: ${String(e)}`);
246
+ }
191
247
  }
192
248
 
193
249
  // Run state and timing
@@ -212,11 +268,14 @@ export async function runHeadless(options = {}) {
212
268
  const SID_BUFFER_SIZE = 4096;
213
269
  let sidSampleAccum = 0; // samples accumulated since last sid_getAudioBuffer call
214
270
 
215
- // Resolve output path once — URL stays verbatim, file paths resolve to repoRoot
271
+ // Resolve output path once — treat remote URLs verbatim, local file paths
272
+ // should be resolved relative to the current working directory (process.cwd()).
273
+ // If no output provided, fall back to repoRoot/temp as before.
274
+ const isRemoteUrl = (s) => /^[a-zA-Z]+:\/\//.test(s);
216
275
  const outPathResolved = output
217
- ? (/^[a-zA-Z]+:\/\//.test(output) ? output : path.resolve(repoRoot, output))
276
+ ? (isRemoteUrl(output) ? output : path.resolve(process.cwd(), output))
218
277
  : path.join(repoRoot, 'temp', `c64-record-${Date.now()}.mp4`);
219
- const isRtmpOutput = /^[a-zA-Z]+:\/\//.test(outPathResolved);
278
+ const isRtmpOutput = isRemoteUrl(outPathResolved);
220
279
 
221
280
  // Setup ffmpeg runner if recording requested
222
281
  let ffmpegRunner = null;
@@ -225,7 +284,17 @@ export async function runHeadless(options = {}) {
225
284
  // Helper: start (or restart) ffmpeg. Returns true on success.
226
285
  async function startFfmpeg() {
227
286
  ffmpegRunner = new FFmpegRunner();
228
- const started = await ffmpegRunner.start({ output: outPathResolved, width: 384, height: 272, fps, duration: durationSec, raw, verbose, audio, sampleRate: audioSampleRate });
287
+ const started = await ffmpegRunner.start({
288
+ output: outPathResolved,
289
+ width: 384,
290
+ height: 272,
291
+ fps,
292
+ duration: durationSec,
293
+ raw,
294
+ verbose,
295
+ audio,
296
+ sampleRate: audioSampleRate
297
+ });
229
298
  return started;
230
299
  }
231
300
 
@@ -236,7 +305,7 @@ export async function runHeadless(options = {}) {
236
305
  const msg = 'ffmpeg-record-failed:start-failed';
237
306
  out.push(msg);
238
307
  console.error('[headless] ' + msg);
239
- return { ok: false, output: out };
308
+ return {ok: false, output: out};
240
309
  } else {
241
310
  const msg = `Recording to ${outPathResolved} (${durationSec ? durationSec + 's' : 'endless'} @ ${fps}fps${audio ? ' +audio' : ''})`;
242
311
  out.push(msg);
@@ -349,7 +418,8 @@ export async function runHeadless(options = {}) {
349
418
  const sidBase = sidPtr >> 2;
350
419
  // Copy the full 4096-sample buffer so ffmpeg gets a consistent chunk
351
420
  audioChunk = heap.heapF32.slice(sidBase, sidBase + SID_BUFFER_SIZE);
352
- } catch (_) {}
421
+ } catch (_) {
422
+ }
353
423
  }
354
424
  }
355
425
  await ffmpegRunner.writeFrame(videoFrame, audioChunk);
@@ -366,7 +436,8 @@ export async function runHeadless(options = {}) {
366
436
  }
367
437
  }
368
438
  }
369
- } catch (_) {}
439
+ } catch (_) {
440
+ }
370
441
  frameCount++;
371
442
  // diagnostics
372
443
  windowCount++;
@@ -380,12 +451,13 @@ export async function runHeadless(options = {}) {
380
451
  }
381
452
  if (verify && frameCount % 60 === 0) {
382
453
  const cycleCount = exports.c64_getCycleCount ? exports.c64_getCycleCount() : null;
383
- out.push(JSON.stringify({ pid: process.pid, frame: frameCount, cycles: cycleCount }));
454
+ out.push(JSON.stringify({pid: process.pid, frame: frameCount, cycles: cycleCount}));
384
455
  // Also emit a stderr heartbeat so interactive runs show progress.
385
456
  try {
386
457
  const pc = exports.c64_getPC ? exports.c64_getPC() : null;
387
458
  console.error(`[headless] verify: frame=${frameCount} pc=${pc} cycles=${cycleCount}`);
388
- } catch (_) {}
459
+ } catch (_) {
460
+ }
389
461
  } else if (frameCount % 120 === 0) {
390
462
  //out.push(`HEADLESS: frame=${frameCount}`);
391
463
  }
@@ -398,6 +470,17 @@ export async function runHeadless(options = {}) {
398
470
 
399
471
  const elapsed = (Date.now() - runStartTime) / 1000;
400
472
  out.push(`Run complete. frames=${frameCount} elapsed=${elapsed.toFixed(2)}s`);
473
+
474
+ // ── Shut down input server ────────────────────────────────────────────────
475
+ if (inputServer) {
476
+ try {
477
+ await inputServer.close();
478
+ if (verbose) console.error('[headless] input server closed');
479
+ } catch (e) {
480
+ console.error('[headless] input server close error:', e && e.message ? e.message : e);
481
+ }
482
+ }
483
+
401
484
  if (record && ffmpegRunner) {
402
485
  // Clear audio interval if it was used (currently null/no-op)
403
486
  if (audioInterval) {
@@ -425,7 +508,7 @@ export async function runHeadless(options = {}) {
425
508
  out.push(`ffmpeg-stop-failed: ${String(e)}`);
426
509
  }
427
510
  }
428
- return { ok: !ffmpegDied, output: out };
511
+ return {ok: !ffmpegDied, output: out};
429
512
  }
430
513
 
431
514
  export default runHeadless;
@@ -448,7 +531,10 @@ try {
448
531
  if (!res.ok) process.exit(1);
449
532
  }
450
533
  process.exit(0);
451
- })().catch((e) => { console.error(e); process.exit(1); });
534
+ })().catch((e) => {
535
+ console.error(e);
536
+ process.exit(1);
537
+ });
452
538
  }
453
539
  } catch (e) {
454
540
  // ignore errors in CLI wrapper detection
@@ -25,16 +25,25 @@ export class InputBridge {
25
25
  }
26
26
 
27
27
  /**
28
- * Example: encode a keypress for transmission
28
+ * Encode a keypress for transmission
29
29
  */
30
- static encodeKeypress(key: string): string {
31
- return JSON.stringify({ type: 'key', key });
30
+ static encodeKeypress(key: string | number, action: 'down' | 'up' = 'down'): string {
31
+ return JSON.stringify({ type: 'key', key, action });
32
32
  }
33
33
 
34
- static encodeJoystick(port: 1 | 2, direction?: string, fire?: boolean): string {
34
+ /**
35
+ * Encode a joystick event for transmission
36
+ */
37
+ static encodeJoystick(
38
+ port: 1 | 2,
39
+ action: 'push' | 'release',
40
+ direction?: string,
41
+ fire?: boolean,
42
+ ): string {
35
43
  return JSON.stringify({
36
44
  type: 'joystick',
37
45
  joystickPort: port,
46
+ action,
38
47
  direction,
39
48
  fire,
40
49
  });
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Embedded WebSocket input server for remote control.
3
+ *
4
+ * Accepts browser connections on a configurable port (default 9001).
5
+ * Parses incoming JSON messages as InputEvent objects and forwards
6
+ * them to the emulator via an onInput callback.
7
+ *
8
+ * Sends a hello handshake on connect with protocol version and
9
+ * joystick bitmask reference so clients can self-configure.
10
+ */
11
+
12
+ import { WebSocketServer } from 'ws';
13
+
14
+ /**
15
+ * @param {Object} opts
16
+ * @param {number} [opts.port=9001] - Listen port
17
+ * @param {Function} opts.onInput - Called with (inputEvent: object) for each valid message
18
+ * @param {boolean} [opts.verbose] - Log connections/messages to stderr
19
+ * @returns {{ wss: WebSocketServer, close: () => Promise<void> }}
20
+ */
21
+ export function createInputServer(opts = {}) {
22
+ const port = opts.port ?? 9001;
23
+ const onInput = opts.onInput;
24
+ const verbose = opts.verbose ?? false;
25
+
26
+ const wss = new WebSocketServer({ port });
27
+ let clientCount = 0;
28
+
29
+ wss.on('listening', () => {
30
+ console.error(`[input-server] WebSocket listening on ws://0.0.0.0:${port}`);
31
+ });
32
+
33
+ wss.on('connection', (ws, req) => {
34
+ clientCount++;
35
+ const addr = req.socket.remoteAddress;
36
+ if (verbose) console.error(`[input-server] client connected from ${addr} (${clientCount} total)`);
37
+
38
+ ws.on('message', (data) => {
39
+ try {
40
+ const msg = JSON.parse(typeof data === 'string' ? data : data.toString('utf8'));
41
+ if (verbose) console.error(`[input-server] rx:`, JSON.stringify(msg));
42
+ if (onInput) onInput(msg);
43
+ } catch (err) {
44
+ if (verbose) console.error(`[input-server] bad message:`, err.message);
45
+ }
46
+ });
47
+
48
+ ws.on('close', () => {
49
+ clientCount--;
50
+ if (verbose) console.error(`[input-server] client disconnected (${clientCount} remaining)`);
51
+ });
52
+
53
+ ws.on('error', (err) => {
54
+ console.error(`[input-server] ws error:`, err.message);
55
+ });
56
+
57
+ // Send a welcome/handshake so the client knows the protocol version
58
+ ws.send(JSON.stringify({
59
+ type: 'hello',
60
+ protocol: 'c64-input',
61
+ version: 1,
62
+ joystickBitmask: { up: 0x1, down: 0x2, left: 0x4, right: 0x8, fire: 0x10 },
63
+ }));
64
+ });
65
+
66
+ wss.on('error', (err) => {
67
+ console.error(`[input-server] server error:`, err.message);
68
+ });
69
+
70
+ const close = () => new Promise((resolve) => {
71
+ wss.close(() => resolve());
72
+ });
73
+
74
+ return { wss, close };
75
+ }
76
+
package/src/main.ts ADDED
@@ -0,0 +1,80 @@
1
+ import { C64Player } from './player/c64-player';
2
+ import CanvasRenderer from './player/canvas-renderer';
3
+ import UIController from './player/ui-controller';
4
+
5
+ const status = document.getElementById('status')!;
6
+ const renderer = new CanvasRenderer('c64-screen');
7
+ const base = import.meta.env.BASE_URL;
8
+
9
+ // Create player and keep in outer scope so UI can trigger file loads
10
+ const player = new C64Player({
11
+ wasmUrl: `${base}c64.wasm`,
12
+ gameUrl: `${base}games/cartridges/legend-of-wilf.crt`,
13
+ renderer,
14
+ onProgress: (pct, label) => renderer.setProgress(pct, label),
15
+ });
16
+
17
+ // Initialise UI with reference to the player (for audio controls)
18
+ new UIController().init(player);
19
+
20
+ player
21
+ .start()
22
+ .then(() => {
23
+ renderer.hideLoader();
24
+ })
25
+ .catch((err) => {
26
+ console.error(err);
27
+ renderer.setError('ERROR');
28
+ status.textContent = `Error: ${err}`;
29
+ status.style.color = '#f44';
30
+ });
31
+
32
+ /**
33
+ * @method updateFavicon
34
+ *
35
+ * PowerLED blink on and off when browser focus is on/off.
36
+ * PRO
37
+ */
38
+ const updateFavicon = () => {
39
+ const isDimmed = document.hidden;
40
+ const link = document.querySelector("link[rel~='icon']") as HTMLLinkElement;
41
+ const fileName = isDimmed ? 'led-off.svg' : 'led-on.svg';
42
+ const fullPath = `${base}${fileName}`.replace(/\/+/g, '/');
43
+ if (link) {
44
+ link.href = fullPath;
45
+ }
46
+ };
47
+
48
+ document.addEventListener('visibilitychange', updateFavicon);
49
+ window.addEventListener('focus', updateFavicon);
50
+ window.addEventListener('blur', updateFavicon);
51
+ updateFavicon();
52
+
53
+ // Listen for files selected via the UI and load into the emulator
54
+ window.addEventListener('c64-load-file', async (e: Event) => {
55
+ const detail = (e as CustomEvent).detail;
56
+ const file: File | undefined = detail?.file;
57
+ if (!file) return;
58
+ try {
59
+ renderer.showLoader?.();
60
+ await player.loadFile(file);
61
+ renderer.hideLoader?.();
62
+ } catch (err) {
63
+ console.error(err);
64
+ renderer.setError?.('LOAD ERROR');
65
+ status.textContent = `Load error: ${err}`;
66
+ status.style.color = '#f44';
67
+ }
68
+ });
69
+
70
+ // Global listener for load errors dispatched by C64Player
71
+ window.addEventListener('c64-load-error', (e: Event) => {
72
+ const detail = (e as CustomEvent).detail as
73
+ | { error?: string; url?: string; file?: string; type?: string }
74
+ | undefined;
75
+ const msg = detail?.error ?? 'Unknown load error';
76
+ console.error('C64 load error event:', detail);
77
+ renderer.setError?.('LOAD ERROR');
78
+ status.textContent = `Load error: ${msg}`;
79
+ status.style.color = '#f44';
80
+ });
@@ -0,0 +1,216 @@
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
+
22
+ export type AudioStateChangeCallback = (state: {
23
+ muted: boolean;
24
+ volume: number;
25
+ suspended: boolean;
26
+ }) => void;
27
+
28
+ const DEFAULT_SAMPLE_RATE = 44_100;
29
+
30
+ /** Function the AudioEngine calls to read the current SID audio buffer */
31
+ export type SidBufferReader = () => Float32Array | null;
32
+
33
+ export class AudioEngine {
34
+ private ctx: AudioContext | null = null;
35
+ private workletNode: AudioWorkletNode | null = null;
36
+ private gainNode: GainNode | null = null;
37
+
38
+ private _muted = false;
39
+ private _volume = 0.75;
40
+ private _suspended = true;
41
+ private _initialised = false;
42
+ private _ready = false;
43
+
44
+ /** Called when the worklet needs more samples */
45
+ private _readSidBuffer: SidBufferReader | null = null;
46
+
47
+ /** Optional callback fired whenever muted / volume / suspended state changes */
48
+ onStateChange?: AudioStateChangeCallback;
49
+
50
+ // ── Public getters ────────────────────────────────────────────────────────
51
+
52
+ get muted(): boolean {
53
+ return this._muted;
54
+ }
55
+
56
+ get volume(): number {
57
+ return this._volume;
58
+ }
59
+
60
+ get suspended(): boolean {
61
+ return this._suspended;
62
+ }
63
+
64
+ get ready(): boolean {
65
+ return this._ready;
66
+ }
67
+
68
+ get sampleRate(): number {
69
+ return this.ctx?.sampleRate ?? DEFAULT_SAMPLE_RATE;
70
+ }
71
+
72
+ // ── Init ──────────────────────────────────────────────────────────────────
73
+
74
+ /**
75
+ * Create the AudioContext and AudioWorklet. Returns `true` if audio is
76
+ * playing immediately, `false` if the browser blocked autoplay.
77
+ */
78
+ async init(): Promise<boolean> {
79
+ if (this._initialised) return !this._suspended;
80
+ this._initialised = true;
81
+
82
+ try {
83
+ this.ctx = new AudioContext({ sampleRate: DEFAULT_SAMPLE_RATE });
84
+
85
+ this.gainNode = this.ctx.createGain();
86
+ this.gainNode.gain.value = this._volume;
87
+ this.gainNode.connect(this.ctx.destination);
88
+
89
+ this.ctx.addEventListener('statechange', () => {
90
+ const wasSuspended = this._suspended;
91
+ this._suspended = this.ctx?.state === 'suspended';
92
+ if (wasSuspended !== this._suspended) {
93
+ this.fireStateChange();
94
+ }
95
+ });
96
+
97
+ this._suspended = this.ctx.state === 'suspended';
98
+
99
+ await this.loadWorklet();
100
+
101
+ // Attempt to resume (may fail due to autoplay policy)
102
+ if (this._suspended) {
103
+ this.ctx.resume().catch(() => {});
104
+ this._suspended = this.ctx.state === 'suspended';
105
+ }
106
+
107
+ this.fireStateChange();
108
+ return !this._suspended;
109
+ } catch {
110
+ // AudioContext unavailable (e.g. test environment) — silently degrade
111
+ return false;
112
+ }
113
+ }
114
+
115
+ private async loadWorklet(): Promise<void> {
116
+ if (!this.ctx || !this.gainNode) return;
117
+ const base = import.meta.env.BASE_URL ?? '/';
118
+ const processorUrl = `${base}audio-worklet-processor.js`.replace(/\/+/g, '/');
119
+ await this.ctx.audioWorklet.addModule(processorUrl);
120
+
121
+ this.workletNode = new AudioWorkletNode(this.ctx, 'c64-audio-processor', {
122
+ outputChannelCount: [1],
123
+ });
124
+ this.workletNode.connect(this.gainNode);
125
+
126
+ // Listen for pull requests from the worklet
127
+ this.workletNode.port.onmessage = () => {
128
+ this.feedWorklet();
129
+ };
130
+
131
+ this._ready = true;
132
+ }
133
+
134
+ // ── SID buffer reader ─────────────────────────────────────────────────────
135
+
136
+ /**
137
+ * Register a function that reads the current SID audio buffer.
138
+ * The engine calls this when the worklet requests more samples.
139
+ */
140
+ setSidBufferReader(reader: SidBufferReader): void {
141
+ this._readSidBuffer = reader;
142
+ }
143
+
144
+ // ── Sample feeding ────────────────────────────────────────────────────────
145
+
146
+ /** Respond to a pull request from the worklet with fresh SID data */
147
+ private feedWorklet(): void {
148
+ if (!this.workletNode || !this._readSidBuffer || this._suspended) return;
149
+ const samples = this._readSidBuffer();
150
+ if (samples && samples.length > 0) {
151
+ this.workletNode.port.postMessage(samples);
152
+ }
153
+ }
154
+
155
+ // ── Playback controls ────────────────────────────────────────────────────
156
+
157
+ async resume(): Promise<void> {
158
+ if (!this.ctx) return;
159
+ try {
160
+ await this.ctx.resume();
161
+ this._suspended = this.ctx.state === 'suspended';
162
+ this.fireStateChange();
163
+ } catch (err) {
164
+ console.error('AudioEngine: resume failed', err);
165
+ }
166
+ }
167
+
168
+ setMuted(muted: boolean): void {
169
+ this._muted = muted;
170
+ if (this.gainNode) {
171
+ this.gainNode.gain.value = muted ? 0 : this._volume;
172
+ }
173
+ this.fireStateChange();
174
+ }
175
+
176
+ toggleMute(): void {
177
+ this.setMuted(!this._muted);
178
+ }
179
+
180
+ setVolume(v: number): void {
181
+ this._volume = Math.max(0, Math.min(1, v));
182
+ if (this.gainNode && !this._muted) {
183
+ this.gainNode.gain.value = this._volume;
184
+ }
185
+ this.fireStateChange();
186
+ }
187
+
188
+ adjustVolume(delta: number): void {
189
+ this.setVolume(this._volume + delta);
190
+ }
191
+
192
+ // ── Teardown ──────────────────────────────────────────────────────────────
193
+
194
+ async destroy(): Promise<void> {
195
+ this.workletNode?.disconnect();
196
+ this.gainNode?.disconnect();
197
+ await this.ctx?.close();
198
+ this.workletNode = null;
199
+ this.gainNode = null;
200
+ this.ctx = null;
201
+ this._initialised = false;
202
+ this._ready = false;
203
+ this._suspended = true;
204
+ this._readSidBuffer = null;
205
+ }
206
+
207
+ // ── Internal ──────────────────────────────────────────────────────────────
208
+
209
+ private fireStateChange(): void {
210
+ this.onStateChange?.({
211
+ muted: this._muted,
212
+ volume: this._volume,
213
+ suspended: this._suspended,
214
+ });
215
+ }
216
+ }