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
@@ -179,6 +179,11 @@ function inferLoadType(filename = '') {
179
179
  return 'crt';
180
180
  }
181
181
 
182
+ export function shouldAutoLoadDisk(autoLoadDisk, diskSessionActive) {
183
+ if (typeof autoLoadDisk === 'boolean') return autoLoadDisk;
184
+ return !diskSessionActive;
185
+ }
186
+
182
187
  function formatSnapshotFilename(now = new Date()) {
183
188
  const pad = (value) => String(value).padStart(2, '0');
184
189
  return `snapshot-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.c64`;
@@ -188,6 +193,12 @@ function sleepMs(ms) {
188
193
  return new Promise((resolve) => setTimeout(resolve, ms));
189
194
  }
190
195
 
196
+ const DISK_AUTOLOAD_RETURN_DELAY_MS = 250;
197
+ const C64_KEYBOARD_BUFFER_LENGTH_ADDR = 0x00c6;
198
+ const C64_KEYBOARD_BUFFER_ADDR = 0x0277;
199
+ const C64_KEYBOARD_BUFFER_MAX_LENGTH = 8;
200
+ const PRG_AUTORUN_BUFFER_TIMEOUT_MS = 2000;
201
+
191
202
  async function typeCommandText(exports, text, opts = {}) {
192
203
  if (!exports) return;
193
204
  const settleMs = Number.isFinite(opts.settleMs) ? opts.settleMs : 120;
@@ -215,6 +226,52 @@ async function typeCommandText(exports, text, opts = {}) {
215
226
  }
216
227
  }
217
228
 
229
+ async function waitForKeyboardBufferEmpty(exports, timeoutMs = PRG_AUTORUN_BUFFER_TIMEOUT_MS) {
230
+ if (!exports || typeof exports.c64_cpuRead !== 'function') return;
231
+ const startedAt = Date.now();
232
+ while (exports.c64_cpuRead(C64_KEYBOARD_BUFFER_LENGTH_ADDR)) {
233
+ if (Date.now() - startedAt >= timeoutMs) {
234
+ throw new Error('Timed out waiting for C64 keyboard buffer before auto-RUN');
235
+ }
236
+ await sleepMs(50);
237
+ }
238
+ }
239
+
240
+ async function insertTextIntoKeyboardBuffer(exports, text) {
241
+ if (!exports || typeof exports.c64_cpuWrite !== 'function') return;
242
+ const bytes = [];
243
+ const normalised = text.toUpperCase().replace(/\r\n/g, '\n');
244
+ for (let i = 0; i < normalised.length; i += 1) {
245
+ const code = normalised.charCodeAt(i);
246
+ bytes.push(code === 10 ? 13 : code);
247
+ }
248
+ while (bytes.length > 0) {
249
+ await waitForKeyboardBufferEmpty(exports);
250
+ const chunk = bytes.splice(0, C64_KEYBOARD_BUFFER_MAX_LENGTH);
251
+ exports.c64_cpuWrite(C64_KEYBOARD_BUFFER_LENGTH_ADDR, chunk.length);
252
+ for (let i = 0; i < chunk.length; i += 1) {
253
+ exports.c64_cpuWrite(C64_KEYBOARD_BUFFER_ADDR + i, chunk[i]);
254
+ }
255
+ }
256
+ }
257
+
258
+ export async function autoLoadDiskWithRun(exports, { isCancelled = () => false } = {}) {
259
+ if (!exports) return;
260
+ if (isCancelled()) return;
261
+ console.error('[event] disk-autoload keyboard-load-start command=LOAD"*",8,1');
262
+ await insertTextIntoKeyboardBuffer(exports, 'LOAD"*",8,1');
263
+ if (isCancelled()) return;
264
+ await sleepMs(DISK_AUTOLOAD_RETURN_DELAY_MS);
265
+ if (isCancelled()) return;
266
+ console.error('[event] disk-autoload keyboard-return');
267
+ await insertTextIntoKeyboardBuffer(exports, '\n');
268
+ await waitForKeyboardBufferEmpty(exports);
269
+ if (isCancelled()) return;
270
+ console.error('[event] disk-autoload keyboard-run');
271
+ await insertTextIntoKeyboardBuffer(exports, 'run\n');
272
+ console.error('[event] disk-autoload done');
273
+ }
274
+
218
275
  // ── Build info ────────────────────────────────────────────────────────────────
219
276
  // Read once at module load so every createInputServer call gets the same values.
220
277
  const _repoRootForBuildInfo = path.resolve(new URL('../../', import.meta.url).pathname);
@@ -282,6 +339,12 @@ export async function runHeadless(options = {}) {
282
339
  let adminToken = process.env.C64_ADMIN_TOKEN ?? '';
283
340
  let logFile = false;
284
341
  let logRetainDays = 7;
342
+ let hostTimeoutMs = Number(process.env.HOST_TIMEOUT_MS ?? '');
343
+ if (!Number.isFinite(hostTimeoutMs) || hostTimeoutMs <= 0) hostTimeoutMs = undefined;
344
+ let attractModeEnabled = ['1', 'true', 'yes', 'on'].includes(String(process.env.ATTRACT_MODE_ENABLED ?? '').toLowerCase());
345
+ let attractModeAutostart = ['1', 'true', 'yes', 'on'].includes(String(process.env.ATTRACT_MODE_AUTOSTART ?? '').toLowerCase());
346
+ let attractModeBaseUrl = process.env.ATTRACT_MODE_BASE_URL ?? '';
347
+ let attractModeManifest = process.env.ATTRACT_MODE_PLAYLIST_MANIFEST ?? 'playlists.json';
285
348
  for (let i = 0; i < argv.length; i++) {
286
349
  const a = argv[i];
287
350
  if (a === '--wasm' || a === '-w') wasmArg = argv[++i];
@@ -298,6 +361,7 @@ export async function runHeadless(options = {}) {
298
361
  else if (a === '--log-events') logEvents = true;
299
362
  else if (a === '--log-file') logFile = true;
300
363
  else if (a === '--log-retain-days') logRetainDays = Number(argv[++i]);
364
+ else if (a === '--host-timeout-ms') hostTimeoutMs = Number(argv[++i]);
301
365
  else if (a === '--fps') fps = Number(argv[++i]);
302
366
  else if (a === '--input') enableInput = true;
303
367
  else if (a === '--ws-port') wsPort = Number(argv[++i]);
@@ -308,10 +372,15 @@ export async function runHeadless(options = {}) {
308
372
  else if (a === '--webrtc-max-bitrate-kbps') webrtcMaxBitrateKbps = Number(argv[++i]);
309
373
  else if (a === '--webrtc-output-fps') webrtcOutputFps = Number(argv[++i]);
310
374
  else if (a === '--admin-token') adminToken = argv[++i] ?? '';
375
+ else if (a === '--attract-mode') attractModeEnabled = true;
376
+ else if (a === '--attract-mode-autostart') attractModeAutostart = true;
377
+ else if (a === '--attract-mode-base-url') attractModeBaseUrl = argv[++i] ?? '';
378
+ else if (a === '--attract-mode-manifest') attractModeManifest = argv[++i] ?? 'playlists.json';
311
379
  else if (a === '--help' || a === '-h') {
312
380
  return { ok: false, output: 'help' };
313
381
  }
314
382
  }
383
+ if (!Number.isFinite(hostTimeoutMs) || hostTimeoutMs <= 0) hostTimeoutMs = undefined;
315
384
  const adminTokenSafe = String(adminToken ?? '').trim();
316
385
 
317
386
  const webrtcMinBitrateKbpsSafe =
@@ -469,6 +538,8 @@ export async function runHeadless(options = {}) {
469
538
  let c64wasm = null; // ← hoisted: needed by onCommand for allocAndWrite
470
539
  let C64WASMClass = null;
471
540
  let wrapperUsed = false;
541
+ let diskSessionActive = false;
542
+ let mediaCommandEpoch = 0;
472
543
  // SID audio constants — hoisted so the SID-cache block and the frame loop
473
544
  // both see them regardless of declaration order.
474
545
  const SID_BUFFER_SIZE = 4096;
@@ -558,22 +629,38 @@ export async function runHeadless(options = {}) {
558
629
  try {
559
630
  const gameData = await fs.readFile(gamePath);
560
631
  const gameArr = new Uint8Array(gameData);
561
- const cartInfo = parseCrtInfo(gameArr, path.basename(gamePath));
562
- if (cartInfo) {
563
- console.error(cartInfo.line);
564
- const unsupportedReason = getUnsupportedCrtReason(cartInfo);
565
- if (unsupportedReason) {
566
- throw new Error(unsupportedReason);
632
+ const gameType = inferLoadType(gamePath);
633
+ if (gameType === 'crt') {
634
+ const cartInfo = parseCrtInfo(gameArr, path.basename(gamePath));
635
+ if (cartInfo) {
636
+ console.error(cartInfo.line);
637
+ const unsupportedReason = getUnsupportedCrtReason(cartInfo);
638
+ if (unsupportedReason) {
639
+ throw new Error(unsupportedReason);
640
+ }
567
641
  }
568
642
  }
569
643
  const ptr = c64wasm.allocAndWrite(gameArr);
570
644
  c64wasm.updateHeapViews();
571
645
  heap = c64wasm.heap;
572
- exports.c64_loadCartridge(ptr, gameData.length);
573
- // free(ptr), c64_reset, debugger_set_speed, debugger_play intentionally
574
- // omitted: c64_loadCartridge already resets and resumes the machine
575
- // internally. Calling them re-triggers the ROM boot sequence — the same
576
- // root cause of post-load input lag fixed for the load-crt command path.
646
+ if (gameType === 'crt') {
647
+ exports.c64_loadCartridge(ptr, gameData.length);
648
+ // free(ptr), c64_reset, debugger_set_speed, debugger_play intentionally
649
+ // omitted: c64_loadCartridge already resets and resumes the machine
650
+ // internally. Calling them re-triggers the ROM boot sequence — the same
651
+ // root cause of post-load input lag fixed for the load-crt command path.
652
+ } else if (gameType === 'prg') {
653
+ exports.c64_loadPRG(ptr, gameData.length, 1);
654
+ await typeCommandText(exports, 'run\n');
655
+ } else if (gameType === 'd64') {
656
+ exports.c64_setDriveEnabled(1);
657
+ exports.c64_insertDisk(ptr, gameData.length);
658
+ diskSessionActive = true;
659
+ await autoLoadDiskWithRun(exports);
660
+ } else if (gameType === 'snapshot') {
661
+ exports.c64_reset();
662
+ exports.c64_loadSnapshot(ptr, gameData.length);
663
+ }
577
664
  } catch (e) {
578
665
  out.push(`Failed to load game: ${String(e)}`);
579
666
  }
@@ -676,6 +763,7 @@ export async function runHeadless(options = {}) {
676
763
  port: wsPort,
677
764
  verbose,
678
765
  logEvents,
766
+ hostTimeoutMs,
679
767
  validateKickToken,
680
768
  validateAdminToken: (token) => {
681
769
  if (!adminTokenSafe) return false;
@@ -688,9 +776,20 @@ export async function runHeadless(options = {}) {
688
776
  getWebrtcPeerSnapshot: () => getWebrtcPeerSnapshot(),
689
777
  disconnectWebrtcPeersByAddr: (addr, reason) => disconnectWebrtcPeersByAddr(addr, reason),
690
778
  disconnectAllWebrtcPeers: (reason) => disconnectAllWebrtcPeers(reason),
779
+ attractMode: {
780
+ enabled: attractModeEnabled,
781
+ autostart: attractModeAutostart,
782
+ baseUrl: attractModeBaseUrl,
783
+ manifest: attractModeManifest,
784
+ },
691
785
  onCommand: async (cmd) => {
692
786
  if (!exports) return;
787
+ if (cmd.type === 'hard-reset' || cmd.type === 'reboot' || cmd.type === 'detach-crt') {
788
+ mediaCommandEpoch += 1;
789
+ }
693
790
  if (cmd.type === 'load-file' || cmd.type === 'load-crt') {
791
+ mediaCommandEpoch += 1;
792
+ const loadEpoch = mediaCommandEpoch;
694
793
  const requestedType =
695
794
  cmd.type === 'load-crt' ? 'crt' : (cmd.fileType ?? inferLoadType(cmd.filename));
696
795
  // Decode base64 → Uint8Array immediately and release the large
@@ -733,15 +832,23 @@ export async function runHeadless(options = {}) {
733
832
  }
734
833
  }
735
834
  exports.c64_loadCartridge(ptr, byteLen);
835
+ diskSessionActive = false;
736
836
  } else if (loadType === 'prg') {
737
837
  exports.c64_loadPRG(ptr, byteLen, 1);
838
+ diskSessionActive = false;
738
839
  await typeCommandText(exports, 'run\n');
739
840
  } else if (loadType === 'd64') {
841
+ if (logEvents)
842
+ console.error(`[event] disk-mount-start filename=${filename} bytes=${byteLen}`);
740
843
  exports.c64_setDriveEnabled(1);
741
844
  exports.c64_insertDisk(ptr, byteLen);
845
+ if (logEvents)
846
+ console.error(`[event] disk-mount-done filename=${filename} bytes=${byteLen}`);
847
+ diskSessionActive = true;
742
848
  } else if (loadType === 'snapshot') {
743
849
  exports.c64_reset();
744
850
  exports.c64_loadSnapshot(ptr, byteLen);
851
+ diskSessionActive = false;
745
852
  } else {
746
853
  throw new Error(`Unsupported load-file type: ${loadType}`);
747
854
  }
@@ -763,14 +870,16 @@ export async function runHeadless(options = {}) {
763
870
  // the audio RTP clock jumps forward by the same amount the video
764
871
  // RTP clock advanced during the blockage.
765
872
  resetSidRing();
766
- if (webrtcEncoder) {
767
- webrtcEncoder.pushSilenceForGap(gapMs);
768
- if (verbose)
769
- console.error(
770
- `[headless] pushed ${gapMs}ms silence to re-align audio RTP after cart load`,
771
- );
873
+ if (loadType === 'crt' || loadType === 'snapshot') {
874
+ if (webrtcEncoder) {
875
+ webrtcEncoder.pushSilenceForGap(gapMs);
876
+ if (verbose)
877
+ console.error(
878
+ `[headless] pushed ${gapMs}ms silence to re-align audio RTP after ${loadType} load`,
879
+ );
880
+ }
881
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
772
882
  }
773
- if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
774
883
  if (verbose)
775
884
  console.error(
776
885
  `[headless] file loaded: ${filename} (${loadType}, ${byteLen} bytes, gap=${gapMs}ms)`,
@@ -786,10 +895,15 @@ export async function runHeadless(options = {}) {
786
895
  console.error(
787
896
  `[event] error cart-load-failed filename=${filename} err=${err && err.message ? err.message : err}`,
788
897
  );
789
- reject(err);
898
+ reject(err);
790
899
  }
791
900
  });
792
901
  });
902
+ } else if (cmd.type === 'auto-load-disk') {
903
+ const loadEpoch = mediaCommandEpoch;
904
+ if (logEvents) console.error('[event] disk-autoload command-start');
905
+ await autoLoadDiskWithRun(exports, { isCancelled: () => loadEpoch !== mediaCommandEpoch });
906
+ if (logEvents) console.error('[event] disk-autoload command-done');
793
907
  } else if (cmd.type === 'save-snapshot') {
794
908
  const ptr = exports.c64_getSnapshot();
795
909
  const byteLen = exports.c64_getSnapshotSize();
@@ -807,6 +921,7 @@ export async function runHeadless(options = {}) {
807
921
  exports.c64_reset(); // return to clean BASIC prompt
808
922
  const gapMs = Date.now() - gapStart;
809
923
  resetSidRing();
924
+ diskSessionActive = false;
810
925
  if (webrtcEncoder) {
811
926
  webrtcEncoder.pushSilenceForGap(gapMs);
812
927
  if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after detach`);
@@ -836,6 +951,7 @@ export async function runHeadless(options = {}) {
836
951
  c64wasm = next;
837
952
  exports = c64wasm.exports;
838
953
  heap = c64wasm.heap;
954
+ diskSessionActive = false;
839
955
  exports.c64_init();
840
956
  exports.sid_setSampleRate(44100);
841
957
  exports.debugger_set_speed(100);
@@ -880,6 +996,7 @@ export async function runHeadless(options = {}) {
880
996
 
881
997
  webrtcEncoder = new WebRTCEncoder();
882
998
  webrtcEncoder.init({ width: 384, height: 272, sampleRate: 44100 });
999
+ webrtcEncoder.primeAudio();
883
1000
 
884
1001
  const { videoTrack, audioTrack } = webrtcEncoder;
885
1002
 
@@ -900,6 +1017,7 @@ export async function runHeadless(options = {}) {
900
1017
  },
901
1018
  onPeerConnected(pc) {
902
1019
  if (verbose) console.error('[webrtc] peer ICE connected');
1020
+ webrtcEncoder?.primeAudio?.();
903
1021
  if (webrtcServer) {
904
1022
  // New peers can attach mid-GOP and sit on a black frame until the
905
1023
  // next natural keyframe arrives. Force one on join so the decoder
@@ -5,7 +5,7 @@ declare module './headless-cli.mjs' {
5
5
  export interface RunHeadlessOptions {
6
6
  argv?: string[];
7
7
  instantiateFn?: (
8
- wasmBinary: ArrayBuffer | Uint8Array,
8
+ wasmBinary: ArrayBuffer | Uint8Array<ArrayBuffer>,
9
9
  importObject: unknown,
10
10
  ) => Promise<{ instance: { exports: unknown } }>;
11
11
  repoRoot?: string;