c64-ready 2.1.0 → 2.4.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 (61) hide show
  1. package/README.md +4 -1
  2. package/bin/admin.mjs +0 -0
  3. package/bin/headless.mjs +1 -0
  4. package/dist/assets/index-Dxuihfdi.js +177 -0
  5. package/dist/index.html +1 -1
  6. package/dist-ts/emulator/c64-emulator.d.ts +1 -1
  7. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  8. package/dist-ts/emulator/c64-emulator.js +1 -0
  9. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  10. package/dist-ts/emulator/c64-wasm.d.ts +4 -4
  11. package/dist-ts/emulator/c64-wasm.d.ts.map +1 -1
  12. package/dist-ts/emulator/c64-wasm.js.map +1 -1
  13. package/dist-ts/emulator/input.d.ts +9 -2
  14. package/dist-ts/emulator/input.d.ts.map +1 -1
  15. package/dist-ts/emulator/input.js +40 -10
  16. package/dist-ts/emulator/input.js.map +1 -1
  17. package/dist-ts/player/audio-engine.d.ts.map +1 -1
  18. package/dist-ts/player/audio-engine.js +4 -0
  19. package/dist-ts/player/audio-engine.js.map +1 -1
  20. package/dist-ts/player/c64-player.d.ts +10 -2
  21. package/dist-ts/player/c64-player.d.ts.map +1 -1
  22. package/dist-ts/player/c64-player.js +109 -30
  23. package/dist-ts/player/c64-player.js.map +1 -1
  24. package/dist-ts/player/index.d.ts +1 -1
  25. package/dist-ts/player/index.d.ts.map +1 -1
  26. package/dist-ts/player/input-handler.d.ts +4 -1
  27. package/dist-ts/player/input-handler.d.ts.map +1 -1
  28. package/dist-ts/player/input-handler.js +10 -11
  29. package/dist-ts/player/input-handler.js.map +1 -1
  30. package/dist-ts/player/load-formats.js +1 -1
  31. package/dist-ts/player/load-formats.js.map +1 -1
  32. package/dist-ts/player/ui-controller.d.ts.map +1 -1
  33. package/dist-ts/player/ui-controller.js +8 -1
  34. package/dist-ts/player/ui-controller.js.map +1 -1
  35. package/package.json +5 -4
  36. package/src/emulator/c64-emulator.ts +2 -1
  37. package/src/emulator/c64-wasm.ts +4 -4
  38. package/src/emulator/input.ts +50 -16
  39. package/src/headless/c64-key-map.mjs +357 -165
  40. package/src/headless/c64-wasm.mjs +2 -2
  41. package/src/headless/ffmpeg-runner.mjs +214 -75
  42. package/src/headless/headless-cli.d.ts +1 -1
  43. package/src/headless/headless-cli.mjs +137 -19
  44. package/src/headless/headless-cli.mjs.d.ts +1 -1
  45. package/src/headless/input-server.mjs +511 -67
  46. package/src/headless/webrtc-encoder.mjs +49 -25
  47. package/src/headless/webrtc-server.mjs +21 -20
  48. package/src/main.ts +3 -2
  49. package/src/player/audio-engine.ts +4 -0
  50. package/src/player/c64-player.ts +115 -34
  51. package/src/player/index.ts +8 -1
  52. package/src/player/input-handler.ts +13 -12
  53. package/src/player/load-formats.ts +1 -1
  54. package/src/player/styles/canvas-renderer.css +10 -5
  55. package/src/player/ui-controller.ts +25 -14
  56. package/dist/assets/index-Df2-qP_u.js +0 -169
  57. package/dist-ts/emulator/memory.d.ts +0 -2
  58. package/dist-ts/emulator/memory.d.ts.map +0 -1
  59. package/dist-ts/emulator/memory.js +0 -9
  60. package/dist-ts/emulator/memory.js.map +0 -1
  61. package/src/emulator/memory.ts +0 -9
@@ -18,7 +18,10 @@ import wrtc from '@roamhq/wrtc';
18
18
  const { RTCVideoSource, RTCAudioSource, rgbaToI420 } = wrtc.nonstandard;
19
19
 
20
20
  const nowMonoMs = () => {
21
- if (typeof globalThis.performance !== 'undefined' && typeof globalThis.performance.now === 'function') {
21
+ if (
22
+ typeof globalThis.performance !== 'undefined' &&
23
+ typeof globalThis.performance.now === 'function'
24
+ ) {
22
25
  return globalThis.performance.now();
23
26
  }
24
27
  return Date.now();
@@ -50,29 +53,29 @@ export class WebRTCEncoder {
50
53
  // ~1300ms *behind* the audio clock after every cart load. The browser's
51
54
  // AV sync logic then delayed video rendering until the audio clock "caught
52
55
  // up", creating the observed ~1–30s of perceived input lag.
53
- _videoOriginMs = 0; // set in init() to nowMonoMs()
56
+ _videoOriginMs = 0; // set in init() to nowMonoMs()
54
57
  _videoFrameDurationUs = 0; // microseconds per frame, set in setFps() (kept for compatibility)
55
58
 
56
59
  // RTCAudioSource.onData() requires exactly (sampleRate / 100) samples per call —
57
60
  // that is one 10 ms WebRTC audio processing frame. At 44100 Hz that is 441 samples.
58
61
  // The SID buffer is 4096 samples, so we queue incoming audio and drain it in
59
62
  // 441-sample chunks.
60
- _audioChunkSize = 441; // recalculated in init()
63
+ _audioChunkSize = 441; // recalculated in init()
61
64
  // Pre-allocated audio ring buffer — large enough to hold several SID pulls
62
65
  // without allocation. Using a ring avoids per-frame Float32Array allocs
63
66
  // (which caused GC pauses and audio stuttering at 50fps).
64
- _audioRing = null; // Float32Array, allocated in init()
67
+ _audioRing = null; // Float32Array, allocated in init()
65
68
  _audioRingSize = 0;
66
69
  _audioRingWrite = 0;
67
70
  _audioRingRead = 0;
68
71
  _audioRingCount = 0;
69
- _audioInt16 = null; // Int16Array(chunkSize), allocated in init()
72
+ _audioInt16 = null; // Int16Array(chunkSize), allocated in init()
70
73
  // Pre-allocated staging buffers — reused every frame to avoid GC pressure.
71
74
  // rgbaToI420() validates data.byteLength === width*height*4, so we cannot
72
75
  // pass a subarray of the WASM heap (whose byteLength = full heap size).
73
76
  // Copying into _rgbaBuf each frame is one memcpy (~417 KB) — negligible.
74
- _rgbaBuf = null; // Uint8ClampedArray(width*height*4)
75
- _i420Buf = null; // Uint8ClampedArray(width*height * 3/2)
77
+ _rgbaBuf = null; // Uint8ClampedArray(width*height*4)
78
+ _i420Buf = null; // Uint8ClampedArray(width*height * 3/2)
76
79
 
77
80
  /**
78
81
  * @param {{ width?: number, height?: number, sampleRate?: number }} opts
@@ -84,12 +87,12 @@ export class WebRTCEncoder {
84
87
  this._audioChunkSize = Math.floor(sampleRate / 100); // 441 @ 44100, 480 @ 48000
85
88
  // Audio ring: large enough for 8× the SID pull size (8×4096 = 32768 samples)
86
89
  // so even bursts after a cart load never overflow.
87
- this._audioRingSize = 4096 * 8;
88
- this._audioRing = new Float32Array(this._audioRingSize);
90
+ this._audioRingSize = 4096 * 8;
91
+ this._audioRing = new Float32Array(this._audioRingSize);
89
92
  this._audioRingWrite = 0;
90
- this._audioRingRead = 0;
93
+ this._audioRingRead = 0;
91
94
  this._audioRingCount = 0;
92
- this._audioInt16 = new Int16Array(this._audioChunkSize);
95
+ this._audioInt16 = new Int16Array(this._audioChunkSize);
93
96
  this._videoOriginMs = nowMonoMs();
94
97
 
95
98
  // Staging buffers with exact byte sizes that rgbaToI420 expects
@@ -141,7 +144,7 @@ export class WebRTCEncoder {
141
144
  */
142
145
  pushSilenceForGap(gapMs) {
143
146
  if (!this.audioSource || gapMs <= 0) return;
144
- const chunkSize = this._audioChunkSize; // 441 @ 44100 Hz
147
+ const chunkSize = this._audioChunkSize; // 441 @ 44100 Hz
145
148
  const sampleRate = this._sampleRate;
146
149
  // Number of silence samples needed to cover the gap
147
150
  const totalSamples = Math.round((gapMs / 1000) * sampleRate);
@@ -152,16 +155,36 @@ export class WebRTCEncoder {
152
155
  let pushed = 0;
153
156
  while (pushed + chunkSize <= totalSamples) {
154
157
  this.audioSource.onData({
155
- samples: int16,
156
- sampleRate: sampleRate,
157
- bitsPerSample: 16,
158
- channelCount: 1,
158
+ samples: int16,
159
+ sampleRate: sampleRate,
160
+ bitsPerSample: 16,
161
+ channelCount: 1,
159
162
  numberOfFrames: chunkSize,
160
163
  });
161
164
  pushed += chunkSize;
162
165
  }
163
166
  }
164
167
 
168
+ /**
169
+ * Push a small amount of silence so newly-created audio tracks have data
170
+ * before the main emulation loop delivers the first SID frame.
171
+ * @param {number} chunks Number of 10 ms audio chunks to push.
172
+ */
173
+ primeAudio(chunks = 1) {
174
+ if (!this.audioSource || chunks <= 0) return;
175
+ const chunkSize = this._audioChunkSize;
176
+ this._audioInt16.fill(0);
177
+ for (let i = 0; i < chunks; i++) {
178
+ this.audioSource.onData({
179
+ samples: this._audioInt16,
180
+ sampleRate: this._sampleRate,
181
+ bitsPerSample: 16,
182
+ channelCount: 1,
183
+ numberOfFrames: chunkSize,
184
+ });
185
+ }
186
+ }
187
+
165
188
  /**
166
189
  * Set the frame rate used to compute video timestamps.
167
190
  * Must be called after init() if the fps differs from the default 50.
@@ -185,10 +208,7 @@ export class WebRTCEncoder {
185
208
  // This is necessary because rgbaToI420 checks data.byteLength strictly.
186
209
  this._rgbaBuf.set(rgbaData.subarray(0, width * height * 4));
187
210
 
188
- rgbaToI420(
189
- { width, height, data: this._rgbaBuf },
190
- { width, height, data: this._i420Buf },
191
- );
211
+ rgbaToI420({ width, height, data: this._rgbaBuf }, { width, height, data: this._i420Buf });
192
212
 
193
213
  // Drive timestamp from wall clock (microseconds elapsed since init()).
194
214
  // After any gap (e.g. the ~1300ms c64_loadCartridge blockage) the timestamp
@@ -212,9 +232,9 @@ export class WebRTCEncoder {
212
232
  * @param {Float32Array} f32samples - SID output, sampleRate Hz mono
213
233
  */
214
234
  pushAudioFrame(f32samples) {
215
- const chunkSize = this._audioChunkSize;
216
- const ringSize = this._audioRingSize;
217
- const ring = this._audioRing;
235
+ const chunkSize = this._audioChunkSize;
236
+ const ringSize = this._audioRingSize;
237
+ const ring = this._audioRing;
218
238
 
219
239
  // Write incoming samples into the ring (wrap-around, drop on overflow)
220
240
  for (let i = 0; i < f32samples.length; i++) {
@@ -246,6 +266,10 @@ export class WebRTCEncoder {
246
266
  }
247
267
  }
248
268
 
249
- get width() { return this._width; }
250
- get height() { return this._height; }
269
+ get width() {
270
+ return this._width;
271
+ }
272
+ get height() {
273
+ return this._height;
274
+ }
251
275
  }
@@ -51,10 +51,7 @@ function buildTimedTurnCredentials({
51
51
  const safeLabel = String(usernameLabel ?? '').trim() || 'c64live';
52
52
  const expiresAt = Math.floor(nowSeconds) + normalizeTurnTtlSeconds(ttlSeconds);
53
53
  const username = `${expiresAt}:${safeLabel}`;
54
- const credential = crypto
55
- .createHmac('sha1', safeSecret)
56
- .update(username)
57
- .digest('base64');
54
+ const credential = crypto.createHmac('sha1', safeSecret).update(username).digest('base64');
58
55
 
59
56
  return { username, credential };
60
57
  }
@@ -116,11 +113,12 @@ function buildIceServers({
116
113
  if (verbose) {
117
114
  const stunCount = stunUrls.length;
118
115
  const turnCount = turnUrls.length;
119
- const turnMode = turnUrls.length > 0 && turnSecret
120
- ? 'timed'
121
- : turnUrls.length > 0 && turnUsername && turnPassword
122
- ? 'static'
123
- : 'disabled';
116
+ const turnMode =
117
+ turnUrls.length > 0 && turnSecret
118
+ ? 'timed'
119
+ : turnUrls.length > 0 && turnUsername && turnPassword
120
+ ? 'static'
121
+ : 'disabled';
124
122
  console.error(
125
123
  `[webrtc] ICE config stunUrls=${stunCount} turnUrls=${turnCount} turnMode=${turnMode}`,
126
124
  );
@@ -177,16 +175,17 @@ export function createWebRTCServer({
177
175
  onPeerConnected,
178
176
  onDataChannelInput,
179
177
  } = {}) {
180
- const buildRuntimeIceServers = () => buildIceServers({
181
- iceStunUrls,
182
- iceTurnUrls,
183
- iceTurnSecret,
184
- iceTurnTtlSeconds,
185
- iceTurnUsernameLabel,
186
- iceTurnUsername,
187
- iceTurnPassword,
188
- verbose,
189
- });
178
+ const buildRuntimeIceServers = () =>
179
+ buildIceServers({
180
+ iceStunUrls,
181
+ iceTurnUrls,
182
+ iceTurnSecret,
183
+ iceTurnTtlSeconds,
184
+ iceTurnUsernameLabel,
185
+ iceTurnUsername,
186
+ iceTurnPassword,
187
+ verbose,
188
+ });
190
189
 
191
190
  const iceServers = buildRuntimeIceServers();
192
191
 
@@ -533,7 +532,9 @@ export function createWebRTCServer({
533
532
  if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
534
533
  const requestIceServers = buildRuntimeIceServers();
535
534
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
536
- res.end(buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe, requestIceServers));
535
+ res.end(
536
+ buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe, requestIceServers),
537
+ );
537
538
  } else if (req.method === 'GET' && req.url === '/ice-config') {
538
539
  const requestIceServers = buildRuntimeIceServers();
539
540
  res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
package/src/main.ts CHANGED
@@ -27,11 +27,12 @@ const player = new C64Player({
27
27
  gameUrl,
28
28
  gameType,
29
29
  renderer,
30
+ audio: { assetBaseUrl: base },
30
31
  onProgress: (pct, label) => renderer.setProgress(pct, label),
31
32
  });
32
33
 
33
34
  // Initialise UI with reference to the player (for audio controls)
34
- new UIController().init(player);
35
+ new UIController({ assetBaseUrl: base }).init(player);
35
36
 
36
37
  player
37
38
  .start()
@@ -99,7 +100,7 @@ window.addEventListener('c64-controller-disconnected', (e: Event) => {
99
100
  const detail = (e as CustomEvent).detail;
100
101
  status.textContent = `Controller Disconnected : ${detail.index} - ${detail.name}`;
101
102
  status.style.color = '#9ecbff';
102
- })
103
+ });
103
104
 
104
105
  window.addEventListener('c64-load-tool', async (e: Event) => {
105
106
  const detail = (e as CustomEvent).detail as
@@ -101,6 +101,7 @@ export class AudioEngine {
101
101
  this._suspended = this.ctx?.state === 'suspended';
102
102
  if (wasSuspended !== this._suspended) {
103
103
  this.fireStateChange();
104
+ this.feedWorklet();
104
105
  }
105
106
  });
106
107
 
@@ -140,6 +141,7 @@ export class AudioEngine {
140
141
  };
141
142
 
142
143
  this._ready = true;
144
+ this.feedWorklet();
143
145
  }
144
146
 
145
147
  // ── SID buffer reader ─────────────────────────────────────────────────────
@@ -150,6 +152,7 @@ export class AudioEngine {
150
152
  */
151
153
  setSidBufferReader(reader: SidBufferReader): void {
152
154
  this._readSidBuffer = reader;
155
+ this.feedWorklet();
153
156
  }
154
157
 
155
158
  // ── Sample feeding ────────────────────────────────────────────────────────
@@ -171,6 +174,7 @@ export class AudioEngine {
171
174
  await this.ctx.resume();
172
175
  this._suspended = this.ctx.state === 'suspended';
173
176
  this.fireStateChange();
177
+ this.feedWorklet();
174
178
  } catch (err) {
175
179
  console.error('AudioEngine: resume failed', err);
176
180
  }
@@ -1,9 +1,8 @@
1
1
  import { C64Emulator } from '../emulator/c64-emulator';
2
- import { domKeyToC64Actions } from '../emulator/input';
3
2
  import { getUnsupportedCrtReason, parseCrtInfo } from '../emulator/crt-info';
4
3
  import type { GameLoadOptions } from '../types';
5
4
  import type { JoystickPort } from '../emulator/constants';
6
- import type { InputMode } from '../emulator/input';
5
+ import type { InputMode, KeyboardJoystickMap } from '../emulator/input';
7
6
  import type CanvasRenderer from './canvas-renderer';
8
7
  import { AudioEngine, type AudioEngineOptions } from './audio-engine';
9
8
  import InputHandler from './input-handler';
@@ -11,6 +10,14 @@ import { getLoadTypeLabel, inferLoadTypeFromFilename } from './load-formats';
11
10
 
12
11
  export type ProgressCallback = (percent: number, label: string) => void;
13
12
 
13
+ const C64_KEYBOARD_BUFFER_LENGTH_ADDR = 0x00c6;
14
+ const C64_KEYBOARD_BUFFER_ADDR = 0x0277;
15
+ const C64_KEYBOARD_BUFFER_MAX_LENGTH = 8;
16
+ const PRG_AUTORUN_DELAY_MS = 650;
17
+ const DISK_AUTOLOAD_DELAY_MS = 1500;
18
+ const DISK_AUTOLOAD_RETURN_DELAY_MS = 250;
19
+ const PRG_AUTORUN_BUFFER_TIMEOUT_MS = 2000;
20
+
14
21
  export interface C64PlayerOptions {
15
22
  wasmUrl: string;
16
23
  gameUrl: string;
@@ -27,6 +34,9 @@ export class C64Player {
27
34
  private inputHandler: InputHandler | null = null;
28
35
  private disableCrtPreloadChecks: boolean = false;
29
36
  private destroyed: boolean = false;
37
+ private diskSessionActive: boolean = false;
38
+ private startupLoadInProgress: boolean = false;
39
+ private startupDiskAutoloadPending: boolean = false;
30
40
  readonly audio: AudioEngine;
31
41
  private readonly options: Required<Pick<C64PlayerOptions, 'wasmUrl' | 'gameUrl' | 'gameType'>> &
32
42
  C64PlayerOptions;
@@ -47,10 +57,20 @@ export class C64Player {
47
57
  let shouldAutoRunPrgAfterStart = false;
48
58
 
49
59
  if (gameData !== undefined && gameData !== null) {
50
- await this.loadGameData(gameData, gameType, gameSource ?? 'inline game data', onProgress);
60
+ this.startupLoadInProgress = true;
61
+ try {
62
+ await this.loadGameData(gameData, gameType, gameSource ?? 'inline game data', onProgress);
63
+ } finally {
64
+ this.startupLoadInProgress = false;
65
+ }
51
66
  shouldAutoRunPrgAfterStart = gameType === 'prg';
52
67
  } else if (gameUrl && gameUrl !== 'null') {
53
- await this.loadGame(gameUrl, gameType, onProgress);
68
+ this.startupLoadInProgress = true;
69
+ try {
70
+ await this.loadGame(gameUrl, gameType, onProgress);
71
+ } finally {
72
+ this.startupLoadInProgress = false;
73
+ }
54
74
  shouldAutoRunPrgAfterStart = gameType === 'prg';
55
75
  }
56
76
 
@@ -58,6 +78,10 @@ export class C64Player {
58
78
  if (shouldAutoRunPrgAfterStart) {
59
79
  await this.autoRunPrgIfRunning();
60
80
  }
81
+ if (this.startupDiskAutoloadPending) {
82
+ this.startupDiskAutoloadPending = false;
83
+ await this.autoLoadDiskIfRunning();
84
+ }
61
85
 
62
86
  // Initialise audio in the background — never blocks game startup
63
87
  this.initAudio();
@@ -79,15 +103,14 @@ export class C64Player {
79
103
  window.dispatchEvent(new CustomEvent('c64-audio-state', { detail: state }));
80
104
  };
81
105
 
106
+ this.audio.setSidBufferReader(() => this.emulator?.getSidBuffer() ?? null);
107
+
82
108
  // Fire-and-forget init
83
109
  this.audio.init().then((autoplayOk) => {
84
110
  if (!this.emulator) return;
85
111
  // Tell the SID what sample rate we're using (matches AudioContext)
86
112
  this.emulator.setSampleRate(this.audio.sampleRate);
87
113
 
88
- // Give the engine a reader that snapshots the SID circular buffer
89
- this.audio.setSidBufferReader(() => this.emulator?.getSidBuffer() ?? null);
90
-
91
114
  if (!autoplayOk) {
92
115
  window.dispatchEvent(new CustomEvent('c64-audio-suspended'));
93
116
  }
@@ -196,6 +219,8 @@ export class C64Player {
196
219
  if (!this.emulator) return;
197
220
  try {
198
221
  this.emulator.removeCartridge();
222
+ this.diskSessionActive = false;
223
+ this.startupDiskAutoloadPending = false;
199
224
  window.dispatchEvent(new CustomEvent('c64-detach', { detail: {} }));
200
225
  window.dispatchEvent(new CustomEvent('c64-close-menu'));
201
226
  } catch (e) {
@@ -222,6 +247,8 @@ export class C64Player {
222
247
  await this.emulator.reboot();
223
248
  this.attachInputAndRenderer(this.emulator, this.options.renderer);
224
249
  this.emulator.start();
250
+ this.diskSessionActive = false;
251
+ this.startupDiskAutoloadPending = false;
225
252
  this.emulator.setSampleRate(this.audio.sampleRate);
226
253
  this.audio.setSidBufferReader(() => this.emulator?.getSidBuffer() ?? null);
227
254
  window.dispatchEvent(new CustomEvent('c64-reboot', { detail: {} }));
@@ -257,6 +284,11 @@ export class C64Player {
257
284
  this.inputHandler?.setKeyboardJoystickPort(port);
258
285
  }
259
286
 
287
+ /** Change which keyboard codes map to joystick controls. */
288
+ setKeyboardJoystickMap(map: KeyboardJoystickMap): void {
289
+ this.inputHandler?.setKeyboardJoystickMap(map);
290
+ }
291
+
260
292
  /**
261
293
  * Change the input mode ('joystick' | 'keyboard' | 'mixed').
262
294
  * - 'joystick' — arrows + ControlLeft control the joystick only (default)
@@ -306,8 +338,54 @@ export class C64Player {
306
338
 
307
339
  private async autoRunPrgIfRunning(): Promise<void> {
308
340
  if (!this.emulator || !this.emulator.isRunning()) return;
309
- await waitMs(220);
310
- await this.typeCommand('run\n');
341
+ await waitMs(PRG_AUTORUN_DELAY_MS);
342
+ await this.insertTextIntoKeyboardBuffer('run\n');
343
+ }
344
+
345
+ private async autoLoadDiskIfRunning(): Promise<void> {
346
+ if (!this.emulator || !this.emulator.isRunning()) return;
347
+ await waitMs(DISK_AUTOLOAD_DELAY_MS);
348
+ await this.insertTextIntoKeyboardBuffer('LOAD"*",8,1');
349
+ await waitMs(DISK_AUTOLOAD_RETURN_DELAY_MS);
350
+ await this.insertTextIntoKeyboardBuffer('\n');
351
+ await this.waitForKeyboardBufferEmpty();
352
+ await this.insertTextIntoKeyboardBuffer('run\n');
353
+ }
354
+
355
+ private async prepareFirstDiskLoad(): Promise<void> {
356
+ if (!this.emulator || this.startupLoadInProgress) return;
357
+ try {
358
+ this.emulator.removeCartridge();
359
+ } catch {
360
+ this.emulator.reset();
361
+ }
362
+ this.emulator.start();
363
+ await waitMs(120);
364
+ }
365
+
366
+ private async insertTextIntoKeyboardBuffer(text: string): Promise<void> {
367
+ if (!this.emulator) return;
368
+
369
+ const bytes = normaliseKeyboardBufferText(text);
370
+ while (bytes.length > 0) {
371
+ await this.waitForKeyboardBufferEmpty();
372
+
373
+ const chunk = bytes.splice(0, C64_KEYBOARD_BUFFER_MAX_LENGTH);
374
+ this.emulator.cpuWrite(C64_KEYBOARD_BUFFER_LENGTH_ADDR, chunk.length);
375
+ for (let i = 0; i < chunk.length; i += 1) {
376
+ this.emulator.cpuWrite(C64_KEYBOARD_BUFFER_ADDR + i, chunk[i]);
377
+ }
378
+ }
379
+ }
380
+
381
+ private async waitForKeyboardBufferEmpty(): Promise<void> {
382
+ const startedAt = Date.now();
383
+ while (this.emulator?.cpuRead(C64_KEYBOARD_BUFFER_LENGTH_ADDR)) {
384
+ if (Date.now() - startedAt >= PRG_AUTORUN_BUFFER_TIMEOUT_MS) {
385
+ throw new Error('Timed out waiting for C64 keyboard buffer before PRG auto-run');
386
+ }
387
+ await waitMs(50);
388
+ }
311
389
  }
312
390
 
313
391
  private async insertGameData(
@@ -325,12 +403,27 @@ export class C64Player {
325
403
  if (type === 'crt') {
326
404
  this.handleCrtPreloadChecks(data, source, onProgress);
327
405
  }
406
+ const shouldAutoLoadDisk = type === 'd64' && !this.diskSessionActive;
407
+ if (shouldAutoLoadDisk) {
408
+ await this.prepareFirstDiskLoad();
409
+ }
328
410
  this.emulator.loadGame({ type, data });
329
411
  if (type === 'prg') {
412
+ this.diskSessionActive = false;
330
413
  await this.autoRunPrgIfRunning();
414
+ } else if (type === 'd64') {
415
+ this.diskSessionActive = true;
416
+ if (shouldAutoLoadDisk) {
417
+ if (this.startupLoadInProgress) this.startupDiskAutoloadPending = true;
418
+ else await this.autoLoadDiskIfRunning();
419
+ }
420
+ } else {
421
+ this.diskSessionActive = false;
331
422
  }
332
423
  onProgress?.(100, 'READY!');
333
- window.dispatchEvent(new CustomEvent('c64-load-success', { detail: { ...eventDetail, type } }));
424
+ window.dispatchEvent(
425
+ new CustomEvent('c64-load-success', { detail: { ...eventDetail, type } }),
426
+ );
334
427
  } catch (err) {
335
428
  onProgress?.(0, 'FAILED');
336
429
  console.error('Failed to insert cartridge or load game:', err);
@@ -343,30 +436,6 @@ export class C64Player {
343
436
  }
344
437
  }
345
438
 
346
- private async typeCommand(command: string): Promise<void> {
347
- if (!this.emulator) return;
348
-
349
- for (const char of command) {
350
- const domKey = char === '\n' ? 'enter' : char;
351
-
352
- const down = domKeyToC64Actions(domKey, false, 'keydown');
353
- for (const act of down) {
354
- if (act.action === 'press') this.emulator.keyDown(act.key);
355
- else this.emulator.keyUp(act.key);
356
- }
357
-
358
- await waitMs(22);
359
-
360
- const up = domKeyToC64Actions(domKey, false, 'keyup');
361
- for (const act of up) {
362
- if (act.action === 'press') this.emulator.keyDown(act.key);
363
- else this.emulator.keyUp(act.key);
364
- }
365
-
366
- await waitMs(22);
367
- }
368
- }
369
-
370
439
  private emitSnapshotLoadInfo(type: GameLoadOptions['type'], source: string): void {
371
440
  if (type !== 'snapshot') return;
372
441
 
@@ -474,6 +543,18 @@ function waitMs(ms: number): Promise<void> {
474
543
  return new Promise((resolve) => setTimeout(resolve, ms));
475
544
  }
476
545
 
546
+ function normaliseKeyboardBufferText(text: string): number[] {
547
+ const bytes: number[] = [];
548
+ const normalised = text.toUpperCase().replace(/\r\n/g, '\n');
549
+
550
+ for (let i = 0; i < normalised.length; i += 1) {
551
+ const code = normalised.charCodeAt(i);
552
+ bytes.push(code === 10 ? 13 : code);
553
+ }
554
+
555
+ return bytes;
556
+ }
557
+
477
558
  function normaliseGameData(
478
559
  gameData: Uint8Array<ArrayBufferLike> | ArrayBufferLike | string,
479
560
  ): Uint8Array<ArrayBufferLike> {
@@ -4,4 +4,11 @@ export type { C64PlayerOptions, ProgressCallback } from './c64-player';
4
4
  export { AudioEngine } from './audio-engine';
5
5
  export type { AudioEngineOptions, AudioStateChangeCallback, SidBufferReader } from './audio-engine';
6
6
  export { default as InputHandler } from './input-handler';
7
- export type { C64Config, C64State, FrameBuffer, AudioBuffer, InputEvent, GameLoadOptions } from '../types';
7
+ export type {
8
+ C64Config,
9
+ C64State,
10
+ FrameBuffer,
11
+ AudioBuffer,
12
+ InputEvent,
13
+ GameLoadOptions,
14
+ } from '../types';
@@ -1,5 +1,5 @@
1
- import { EmulatorInput, JOYSTICK_KEY_CODES, MIXED_JOYSTICK_KEYS } from '../emulator/input';
2
- import type { InputMode } from '../emulator/input';
1
+ import { EmulatorInput } from '../emulator/input';
2
+ import type { InputMode, KeyboardJoystickMap } from '../emulator/input';
3
3
  import type { JoystickPort } from '../emulator/constants';
4
4
  import type { C64Emulator } from '../emulator/c64-emulator';
5
5
 
@@ -31,6 +31,11 @@ export default class InputHandler {
31
31
  this.emulatorInput.setKeyboardPort(port);
32
32
  }
33
33
 
34
+ /** Change which keyboard codes map to joystick controls. */
35
+ setKeyboardJoystickMap(map: KeyboardJoystickMap): void {
36
+ this.emulatorInput.setKeyboardJoystickMap(map);
37
+ }
38
+
34
39
  /** Change the input mode ('joystick' | 'keyboard' | 'mixed') */
35
40
  setInputMode(mode: InputMode): void {
36
41
  this.emulatorInput.setInputMode(mode);
@@ -51,11 +56,7 @@ export default class InputHandler {
51
56
  private onCaptureKeyDown(e: KeyboardEvent): void {
52
57
  // Block joystick-mapped keys (standard + mixed mode) when overlays are
53
58
  // visible or the document is unfocused. Use the union of both key sets.
54
- const JOY_KEYS = new Set([
55
- ...(JOYSTICK_KEY_CODES as string[]),
56
- ...Object.keys(MIXED_JOYSTICK_KEYS),
57
- ]);
58
- if (!JOY_KEYS.has(e.code)) return;
59
+ if (!this.isJoystickKey(e)) return;
59
60
 
60
61
  // Block if document is unfocused. Prefer the Visibility API (document.hidden)
61
62
  // which is stable under JSDOM; fall back to hasFocus() only if hidden is unavailable.
@@ -102,11 +103,7 @@ export default class InputHandler {
102
103
 
103
104
  private onCaptureKeyUp(e: KeyboardEvent): void {
104
105
  // Only block joystick-mapped keys (standard + mixed mode)
105
- const JOY_KEYS = new Set([
106
- ...(JOYSTICK_KEY_CODES as string[]),
107
- ...Object.keys(MIXED_JOYSTICK_KEYS),
108
- ]);
109
- if (!JOY_KEYS.has(e.code)) return;
106
+ if (!this.isJoystickKey(e)) return;
110
107
 
111
108
  // Mirror the same blocking logic for keyup events
112
109
  try {
@@ -137,4 +134,8 @@ export default class InputHandler {
137
134
  // ignore DOM errors
138
135
  }
139
136
  }
137
+
138
+ private isJoystickKey(e: KeyboardEvent): boolean {
139
+ return this.emulatorInput.isJoystickKeyCode(e.code);
140
+ }
140
141
  }
@@ -49,7 +49,7 @@ export function getAcceptForLoadTypeSelection(selection: LoadTypeSelection): str
49
49
  const exts =
50
50
  selection === 'auto'
51
51
  ? LOAD_FORMAT_OPTIONS.flatMap((f) => f.extensions)
52
- : LOAD_FORMAT_OPTIONS.find((f) => f.type === selection)?.extensions ?? [];
52
+ : (LOAD_FORMAT_OPTIONS.find((f) => f.type === selection)?.extensions ?? []);
53
53
  return exts.join(',');
54
54
  }
55
55
 
@@ -3,7 +3,9 @@
3
3
  position: relative;
4
4
  width: 768px;
5
5
  margin-top: 12px;
6
- transition: opacity 0.6s ease, transform 0.6s ease;
6
+ transition:
7
+ opacity 0.6s ease,
8
+ transform 0.6s ease;
7
9
  }
8
10
  .c64-loader.hidden {
9
11
  opacity: 0;
@@ -31,11 +33,14 @@
31
33
  background: linear-gradient(90deg, #6c6cff 0%, #a8a8ff 50%, #6c6cff 100%);
32
34
  background-size: 200% 100%;
33
35
  border-radius: 2px;
34
- transition: width 0.5s cubic-bezier(.22,.61,.36,1);
36
+ transition: width 0.5s cubic-bezier(0.22, 0.61, 0.36, 1);
35
37
  animation: c64-shimmer 1.5s linear infinite;
36
38
  }
37
39
  @keyframes c64-shimmer {
38
- 0% { background-position: 200% 0; }
39
- 100% { background-position: -200% 0; }
40
+ 0% {
41
+ background-position: 200% 0;
42
+ }
43
+ 100% {
44
+ background-position: -200% 0;
45
+ }
40
46
  }
41
-