c64-ready 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +70 -62
  2. package/bin/headless.mjs +1 -1
  3. package/dist/assets/{CHANGELOG-CPlXKLCV.js → CHANGELOG-0a7A8Ekq.js} +113 -1
  4. package/dist/assets/index-BESofQoh.js +627 -0
  5. package/dist/games/cartridges/goat-beat.crt +0 -0
  6. package/dist/index.html +1 -1
  7. package/dist-ts/emulator/c64-emulator.d.ts +3 -0
  8. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  9. package/dist-ts/emulator/c64-emulator.js +36 -4
  10. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  11. package/dist-ts/emulator/crt-info.d.ts +61 -0
  12. package/dist-ts/emulator/crt-info.d.ts.map +1 -0
  13. package/dist-ts/emulator/crt-info.js +190 -0
  14. package/dist-ts/emulator/crt-info.js.map +1 -0
  15. package/dist-ts/emulator/input.d.ts +96 -0
  16. package/dist-ts/emulator/input.d.ts.map +1 -1
  17. package/dist-ts/emulator/input.js +549 -4
  18. package/dist-ts/emulator/input.js.map +1 -1
  19. package/dist-ts/headless/c64-headless.d.ts +1 -0
  20. package/dist-ts/headless/c64-headless.d.ts.map +1 -1
  21. package/dist-ts/headless/c64-headless.js +5 -0
  22. package/dist-ts/headless/c64-headless.js.map +1 -1
  23. package/dist-ts/types/emulator.d.ts +2 -1
  24. package/dist-ts/types/emulator.d.ts.map +1 -1
  25. package/package.json +1 -1
  26. package/public/games/cartridges/goat-beat.crt +0 -0
  27. package/src/emulator/c64-emulator.ts +37 -7
  28. package/src/emulator/crt-info.ts +35 -23
  29. package/src/emulator/input.ts +239 -19
  30. package/src/headless/c64-headless.ts +5 -0
  31. package/src/headless/headless-cli.mjs +462 -249
  32. package/src/headless/input-server.mjs +649 -278
  33. package/src/headless/webrtc-server.mjs +218 -71
  34. package/src/main.ts +30 -4
  35. package/src/player/c64-player.ts +121 -40
  36. package/src/player/input-handler.ts +8 -0
  37. package/src/player/styles/ui-controller.css +103 -21
  38. package/src/player/ui-controller.ts +186 -23
  39. package/src/types/emulator.ts +1 -1
  40. package/dist/assets/index-Ckbi7gQo.js +0 -535
@@ -1,13 +1,16 @@
1
1
  import fs from 'fs/promises';
2
2
  import { readFileSync, mkdirSync, createWriteStream, readdirSync, statSync, unlinkSync } from 'fs';
3
3
  import path from 'path';
4
- import {fileURLToPath} from 'url';
4
+ import { fileURLToPath } from 'url';
5
5
  import { execSync } from 'child_process';
6
6
  import FFmpegRunner from './ffmpeg-runner.mjs';
7
7
  import { domKeyToC64Actions } from './c64-key-map.mjs';
8
8
 
9
9
  const nowMonoMs = () => {
10
- if (typeof globalThis.performance !== 'undefined' && typeof globalThis.performance.now === 'function') {
10
+ if (
11
+ typeof globalThis.performance !== 'undefined' &&
12
+ typeof globalThis.performance.now === 'function'
13
+ ) {
11
14
  return globalThis.performance.now();
12
15
  }
13
16
  return Date.now();
@@ -19,29 +22,85 @@ const nowMonoMs = () => {
19
22
  //
20
23
  // Reference: https://vice-emu.sourceforge.io/vice_17.html#SEC380
21
24
  const _CRT_HW_TYPES = {
22
- 0:'Normal cartridge', 1:'Action Replay', 2:'KCS Power Cartridge',
23
- 3:'Final Cartridge III', 4:'Simons BASIC', 5:'Ocean type 1',
24
- 6:'Expert Cartridge', 7:'Fun Play, Power Play', 8:'Super Games',
25
- 9:'Atomic Power', 10:'Epyx Fastload', 11:'Westermann Learning',
26
- 12:'Rex Utility', 13:'Final Cartridge I', 14:'Magic Formel',
27
- 15:'C64 Game System (SYSTEM 3)', 16:'Warp Speed', 17:'Dinamic',
28
- 18:'Zaxxon / Super Zaxxon (SEGA)', 19:'Magic Desk / Domark / HES Australia',
29
- 20:'Super Snapshot V5', 21:'Comal-80', 22:'Structured BASIC', 23:'Ross',
30
- 24:'Dela EP64', 25:'Dela EP7x8', 26:'Dela EP256', 27:'Rex EP256',
31
- 28:'Mikro Assembler', 29:'Final Cartridge Plus', 30:'Action Replay 4',
32
- 31:'Stardos', 32:'EasyFlash', 33:'EasyFlash Xbank', 34:'Capture',
33
- 35:'Action Replay 3', 36:'Retro Replay', 37:'MMC64', 38:'MMC Replay',
34
- 39:'IDE64', 40:'Super Snapshot V4', 41:'IEEE-488', 42:'Game Killer',
35
- 43:'Prophet64', 44:'EXOS', 45:'Freeze Frame', 46:'Freeze Machine',
36
- 47:'Snapshot64', 48:'Super Explode V5.0', 49:'Magic Voice',
37
- 50:'Action Replay 2', 51:'MACH 5', 52:'Diashow-Maker', 53:'Pagefox',
38
- 54:'Kingsoft', 55:'Silverrock 128K Longshot', 56:'Formel 64', 57:'RGCD',
39
- 58:'RR-Net MK3', 59:'Easy Calc', 60:'GMod2', 61:'MAX Basic', 62:'GMod3',
40
- 63:'ZIPP-CODE 48', 64:'Blackbox V8', 65:'Blackbox V3', 66:'Blackbox V4',
41
- 67:'REX RAM-Floppy', 68:'BIS-Plus', 69:'SD-BOX', 70:'MultiMAX',
42
- 71:'Blackbox V9', 72:'Lt. Kernal Host Adaptor', 73:'RAMLink', 74:'H.E.R.O.',
43
- 75:'IEEE Flash! 64', 76:'Turtle Graphics II', 77:'Freeze Frame MK2',
44
- 78:'Partner 64',
25
+ 0: 'Normal cartridge',
26
+ 1: 'Action Replay',
27
+ 2: 'KCS Power Cartridge',
28
+ 3: 'Final Cartridge III',
29
+ 4: 'Simons BASIC',
30
+ 5: 'Ocean type 1',
31
+ 6: 'Expert Cartridge',
32
+ 7: 'Fun Play, Power Play',
33
+ 8: 'Super Games',
34
+ 9: 'Atomic Power',
35
+ 10: 'Epyx Fastload',
36
+ 11: 'Westermann Learning',
37
+ 12: 'Rex Utility',
38
+ 13: 'Final Cartridge I',
39
+ 14: 'Magic Formel',
40
+ 15: 'C64 Game System (SYSTEM 3)',
41
+ 16: 'Warp Speed',
42
+ 17: 'Dinamic',
43
+ 18: 'Zaxxon / Super Zaxxon (SEGA)',
44
+ 19: 'Magic Desk / Domark / HES Australia',
45
+ 20: 'Super Snapshot V5',
46
+ 21: 'Comal-80',
47
+ 22: 'Structured BASIC',
48
+ 23: 'Ross',
49
+ 24: 'Dela EP64',
50
+ 25: 'Dela EP7x8',
51
+ 26: 'Dela EP256',
52
+ 27: 'Rex EP256',
53
+ 28: 'Mikro Assembler',
54
+ 29: 'Final Cartridge Plus',
55
+ 30: 'Action Replay 4',
56
+ 31: 'Stardos',
57
+ 32: 'EasyFlash',
58
+ 33: 'EasyFlash Xbank',
59
+ 34: 'Capture',
60
+ 35: 'Action Replay 3',
61
+ 36: 'Retro Replay',
62
+ 37: 'MMC64',
63
+ 38: 'MMC Replay',
64
+ 39: 'IDE64',
65
+ 40: 'Super Snapshot V4',
66
+ 41: 'IEEE-488',
67
+ 42: 'Game Killer',
68
+ 43: 'Prophet64',
69
+ 44: 'EXOS',
70
+ 45: 'Freeze Frame',
71
+ 46: 'Freeze Machine',
72
+ 47: 'Snapshot64',
73
+ 48: 'Super Explode V5.0',
74
+ 49: 'Magic Voice',
75
+ 50: 'Action Replay 2',
76
+ 51: 'MACH 5',
77
+ 52: 'Diashow-Maker',
78
+ 53: 'Pagefox',
79
+ 54: 'Kingsoft',
80
+ 55: 'Silverrock 128K Longshot',
81
+ 56: 'Formel 64',
82
+ 57: 'RGCD',
83
+ 58: 'RR-Net MK3',
84
+ 59: 'Easy Calc',
85
+ 60: 'GMod2',
86
+ 61: 'MAX Basic',
87
+ 62: 'GMod3',
88
+ 63: 'ZIPP-CODE 48',
89
+ 64: 'Blackbox V8',
90
+ 65: 'Blackbox V3',
91
+ 66: 'Blackbox V4',
92
+ 67: 'REX RAM-Floppy',
93
+ 68: 'BIS-Plus',
94
+ 69: 'SD-BOX',
95
+ 70: 'MultiMAX',
96
+ 71: 'Blackbox V9',
97
+ 72: 'Lt. Kernal Host Adaptor',
98
+ 73: 'RAMLink',
99
+ 74: 'H.E.R.O.',
100
+ 75: 'IEEE Flash! 64',
101
+ 76: 'Turtle Graphics II',
102
+ 77: 'Freeze Frame MK2',
103
+ 78: 'Partner 64',
45
104
  };
46
105
  /**
47
106
  * Parse a CRT file and return a human-readable summary line plus metadata.
@@ -56,39 +115,46 @@ function parseCrtInfo(data, filename) {
56
115
  for (let i = 0; i < 16; i++) magic += String.fromCharCode(data[i]);
57
116
  if (!magic.startsWith('C64 CARTRIDGE')) return null;
58
117
 
59
- const headerLen = ((data[0x10]<<24)|(data[0x11]<<16)|(data[0x12]<<8)|data[0x13])>>>0;
60
- const hwType = ((data[0x16]<<8)|data[0x17])>>>0;
61
- const exrom = data[0x18];
62
- const game = data[0x19];
118
+ const headerLen =
119
+ ((data[0x10] << 24) | (data[0x11] << 16) | (data[0x12] << 8) | data[0x13]) >>> 0;
120
+ const hwType = ((data[0x16] << 8) | data[0x17]) >>> 0;
121
+ const exrom = data[0x18];
122
+ const game = data[0x19];
63
123
 
64
124
  let cartName = '';
65
125
  for (let i = 0x20; i < 0x40 && data[i] !== 0; i++) cartName += String.fromCharCode(data[i]);
66
126
  cartName = cartName.trim();
67
127
 
68
128
  let bankConfig;
69
- if (exrom === 0 && game === 0) bankConfig = '16K (ROML+ROMH)';
129
+ if (exrom === 0 && game === 0) bankConfig = '16K (ROML+ROMH)';
70
130
  else if (exrom === 0 && game === 1) bankConfig = '8K (ROML only)';
71
131
  else if (exrom === 1 && game === 0) bankConfig = 'Ultimax';
72
- else bankConfig = 'inactive (pass-through)';
132
+ else bankConfig = 'inactive (pass-through)';
73
133
 
74
- let chipCount = 0, totalRomBytes = 0;
134
+ let chipCount = 0,
135
+ totalRomBytes = 0;
75
136
  let offset = Math.max(headerLen, 0x40);
76
137
  while (offset + 16 <= data.length) {
77
138
  let cm = '';
78
139
  for (let i = 0; i < 4; i++) cm += String.fromCharCode(data[offset + i]);
79
140
  if (cm !== 'CHIP') break;
80
- const pktLen = ((data[offset+4]<<24)|(data[offset+5]<<16)|(data[offset+6]<<8)|data[offset+7])>>>0;
141
+ const pktLen =
142
+ ((data[offset + 4] << 24) |
143
+ (data[offset + 5] << 16) |
144
+ (data[offset + 6] << 8) |
145
+ data[offset + 7]) >>>
146
+ 0;
81
147
  if (pktLen < 16) break;
82
- const dataSize = ((data[offset+0x0E]<<8)|data[offset+0x0F])>>>0;
148
+ const dataSize = ((data[offset + 0x0e] << 8) | data[offset + 0x0f]) >>> 0;
83
149
  chipCount++;
84
150
  totalRomBytes += dataSize;
85
151
  offset += pktLen;
86
152
  }
87
153
 
88
- const hwName = _CRT_HW_TYPES[hwType] ?? `Unknown(${hwType})`;
154
+ const hwName = _CRT_HW_TYPES[hwType] ?? `Unknown(${hwType})`;
89
155
  const fileLabel = filename ? ` "${filename}"` : '';
90
- const namePart = cartName ? ` name="${cartName}"` : '';
91
- const kbActual = (totalRomBytes / 1024).toFixed(0);
156
+ const namePart = cartName ? ` name="${cartName}"` : '';
157
+ const kbActual = (totalRomBytes / 1024).toFixed(0);
92
158
  const line =
93
159
  `[C64 cart]${fileLabel} loading: hwType=${hwType}(${hwName})` +
94
160
  ` | ${bankConfig} flags, ${kbActual}K actual` +
@@ -96,15 +162,28 @@ function parseCrtInfo(data, filename) {
96
162
  return { line, hwType, hwName, exrom, game, bankConfig, cartName, chipCount, totalRomBytes };
97
163
  }
98
164
 
165
+ function getUnsupportedCrtReason(info) {
166
+ if (info && info.exrom === 1 && info.game === 0 && info.hwType === 0) {
167
+ return 'Unsupported CRT: Ultimax/MAX cartridges are not supported by this emulator.';
168
+ }
169
+ return null;
170
+ }
171
+
99
172
  function inferLoadType(filename = '') {
100
173
  const lower = String(filename).toLowerCase();
101
174
  if (lower.endsWith('.crt')) return 'crt';
102
175
  if (lower.endsWith('.prg')) return 'prg';
103
176
  if (lower.endsWith('.d64')) return 'd64';
104
- if (lower.endsWith('.snapshot') || lower.endsWith('.c64') || lower.endsWith('.s64')) return 'snapshot';
177
+ if (lower.endsWith('.snapshot') || lower.endsWith('.c64') || lower.endsWith('.s64'))
178
+ return 'snapshot';
105
179
  return 'crt';
106
180
  }
107
181
 
182
+ function formatSnapshotFilename(now = new Date()) {
183
+ const pad = (value) => String(value).padStart(2, '0');
184
+ return `snapshot-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.c64`;
185
+ }
186
+
108
187
  function sleepMs(ms) {
109
188
  return new Promise((resolve) => setTimeout(resolve, ms));
110
189
  }
@@ -144,7 +223,9 @@ let _serverGitHash = null;
144
223
  try {
145
224
  const pkg = JSON.parse(readFileSync(path.join(_repoRootForBuildInfo, 'package.json'), 'utf8'));
146
225
  _serverVersion = pkg.version ?? null;
147
- } catch { /* non-fatal */ }
226
+ } catch {
227
+ /* non-fatal */
228
+ }
148
229
  try {
149
230
  // Prefer the baked-in build-arg written by the Dockerfile (works in Docker
150
231
  // where git is not installed and .git is not present).
@@ -156,11 +237,17 @@ try {
156
237
  try {
157
238
  _serverGitHash = readFileSync(hashFile, 'utf8').trim() || null;
158
239
  } catch {
159
- _serverGitHash = execSync('git rev-parse --short HEAD', { cwd: _repoRootForBuildInfo, stdio: ['ignore', 'pipe', 'ignore'] })
160
- .toString().trim();
240
+ _serverGitHash = execSync('git rev-parse --short HEAD', {
241
+ cwd: _repoRootForBuildInfo,
242
+ stdio: ['ignore', 'pipe', 'ignore'],
243
+ })
244
+ .toString()
245
+ .trim();
161
246
  }
162
247
  }
163
- } catch { /* non-fatal — git may not be available in some deploy environments */ }
248
+ } catch {
249
+ /* non-fatal — git may not be available in some deploy environments */
250
+ }
164
251
 
165
252
  /**
166
253
  * Run headless emulator. Exported so tests can inject a fake WebAssembly.instantiate.
@@ -188,7 +275,7 @@ export async function runHeadless(options = {}) {
188
275
  let webrtc = false;
189
276
  let webrtcPort = 9002;
190
277
  let logEvents = false;
191
- let maxSpectators = 3;
278
+ let maxSpectators = 10;
192
279
  let webrtcMinBitrateKbps = 200;
193
280
  let webrtcMaxBitrateKbps = 600;
194
281
  let webrtcOutputFps = 40;
@@ -222,20 +309,21 @@ export async function runHeadless(options = {}) {
222
309
  else if (a === '--webrtc-output-fps') webrtcOutputFps = Number(argv[++i]);
223
310
  else if (a === '--admin-token') adminToken = argv[++i] ?? '';
224
311
  else if (a === '--help' || a === '-h') {
225
- return {ok: false, output: 'help'};
312
+ return { ok: false, output: 'help' };
226
313
  }
227
314
  }
228
315
  const adminTokenSafe = String(adminToken ?? '').trim();
229
316
 
230
- const webrtcMinBitrateKbpsSafe = Number.isFinite(webrtcMinBitrateKbps) && webrtcMinBitrateKbps > 0
231
- ? Math.round(webrtcMinBitrateKbps)
232
- : 200;
233
- const webrtcMaxBitrateKbpsSafe = Number.isFinite(webrtcMaxBitrateKbps) && webrtcMaxBitrateKbps > 0
234
- ? Math.max(webrtcMinBitrateKbpsSafe, Math.round(webrtcMaxBitrateKbps))
235
- : Math.max(webrtcMinBitrateKbpsSafe, 600);
236
- const webrtcOutputFpsSafe = Number.isFinite(webrtcOutputFps) && webrtcOutputFps > 0
237
- ? Math.round(webrtcOutputFps)
238
- : 0;
317
+ const webrtcMinBitrateKbpsSafe =
318
+ Number.isFinite(webrtcMinBitrateKbps) && webrtcMinBitrateKbps > 0
319
+ ? Math.round(webrtcMinBitrateKbps)
320
+ : 200;
321
+ const webrtcMaxBitrateKbpsSafe =
322
+ Number.isFinite(webrtcMaxBitrateKbps) && webrtcMaxBitrateKbps > 0
323
+ ? Math.max(webrtcMinBitrateKbpsSafe, Math.round(webrtcMaxBitrateKbps))
324
+ : Math.max(webrtcMinBitrateKbpsSafe, 600);
325
+ const webrtcOutputFpsSafe =
326
+ Number.isFinite(webrtcOutputFps) && webrtcOutputFps > 0 ? Math.round(webrtcOutputFps) : 0;
239
327
 
240
328
  const runtimeStats = {
241
329
  webrtcSendFps: null,
@@ -307,7 +395,8 @@ export async function runHeadless(options = {}) {
307
395
  const _writeLog = (origFn, ...args) => {
308
396
  origFn.apply(console, args);
309
397
  if (logStream && logStream.writable) {
310
- const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ') + '\n';
398
+ const line =
399
+ args.map((a) => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ') + '\n';
311
400
  logStream.write(line);
312
401
  }
313
402
  };
@@ -318,7 +407,9 @@ export async function runHeadless(options = {}) {
318
407
 
319
408
  function _teardownLogFile() {
320
409
  if (logStream) {
321
- try { logStream.end(); } catch (_) {}
410
+ try {
411
+ logStream.end();
412
+ } catch (_) {}
322
413
  logStream = null;
323
414
  }
324
415
  if (_origConsoleLog) {
@@ -344,8 +435,7 @@ export async function runHeadless(options = {}) {
344
435
  try {
345
436
  await fs.access(p);
346
437
  return p;
347
- } catch (_) {
348
- }
438
+ } catch (_) {}
349
439
  }
350
440
  return null;
351
441
  }
@@ -355,7 +445,7 @@ export async function runHeadless(options = {}) {
355
445
  const found = await findFirstExisting(defaultWasmPaths);
356
446
  if (found) wasmPath = found;
357
447
  }
358
- if (!wasmPath) return {ok: false, err: 'no-wasm'};
448
+ if (!wasmPath) return { ok: false, err: 'no-wasm' };
359
449
 
360
450
  let gamePath = gameArg ?? null;
361
451
  // If the user requested no game, ensure we do not load any default cartridge
@@ -368,13 +458,16 @@ export async function runHeadless(options = {}) {
368
458
  }
369
459
 
370
460
  const out = [];
371
- out.push(`Starting headless C64 using WASM: ${wasmPath}` + (gamePath ? ` game: ${gamePath}` : ''));
461
+ out.push(
462
+ `Starting headless C64 using WASM: ${wasmPath}` + (gamePath ? ` game: ${gamePath}` : ''),
463
+ );
372
464
 
373
465
  const wasmBinary = await fs.readFile(wasmPath);
374
466
  // runtime state placeholders — hoisted so onCommand handler can access c64wasm
375
- let exports = null;
376
- let heap = null;
377
- let c64wasm = null; // ← hoisted: needed by onCommand for allocAndWrite
467
+ let exports = null;
468
+ let heap = null;
469
+ let c64wasm = null; // ← hoisted: needed by onCommand for allocAndWrite
470
+ let C64WASMClass = null;
378
471
  let wrapperUsed = false;
379
472
  // SID audio constants — hoisted so the SID-cache block and the frame loop
380
473
  // both see them regardless of declaration order.
@@ -390,8 +483,8 @@ export async function runHeadless(options = {}) {
390
483
  );
391
484
  if (typeof instantiateFn === 'function') {
392
485
  try {
393
- const mem = new WebAssembly.Memory({initial: 256});
394
- const importObject = {env: {memory: mem}, wasi_snapshot_preview1: {}};
486
+ const mem = new WebAssembly.Memory({ initial: 256 });
487
+ const importObject = { env: { memory: mem }, wasi_snapshot_preview1: {} };
395
488
  const res = await instantiateFn(wasmAb, importObject);
396
489
  const inst = res && (res.instance ?? res);
397
490
  exports = inst.exports ?? inst;
@@ -399,11 +492,17 @@ export async function runHeadless(options = {}) {
399
492
  if (exports && !exports.memory) exports.memory = mem;
400
493
  if (exports && exports.memory) {
401
494
  const buf = exports.memory.buffer;
402
- heap = {heapU8: new Uint8Array(buf), heapF32: new Float32Array(buf), heapU32: new Uint32Array(buf)};
495
+ heap = {
496
+ heapU8: new Uint8Array(buf),
497
+ heapF32: new Float32Array(buf),
498
+ heapU32: new Uint32Array(buf),
499
+ };
403
500
  }
404
501
  if (exports && typeof exports.c64_init === 'function') exports.c64_init();
405
- if (exports && typeof exports.sid_setSampleRate === 'function') exports.sid_setSampleRate(44100);
406
- if (exports && typeof exports.debugger_set_speed === 'function') exports.debugger_set_speed(100);
502
+ if (exports && typeof exports.sid_setSampleRate === 'function')
503
+ exports.sid_setSampleRate(44100);
504
+ if (exports && typeof exports.debugger_set_speed === 'function')
505
+ exports.debugger_set_speed(100);
407
506
  if (exports && typeof exports.debugger_play === 'function') exports.debugger_play();
408
507
  wrapperUsed = true;
409
508
  } catch (e) {
@@ -437,12 +536,13 @@ export async function runHeadless(options = {}) {
437
536
  }
438
537
 
439
538
  if (!C64WASM) throw new Error('C64WASM wrapper not found (src/headless or dist-ts)');
539
+ C64WASMClass = C64WASM;
440
540
 
441
541
  const wasmAb = wasmBinary.buffer.slice(
442
542
  wasmBinary.byteOffset,
443
543
  wasmBinary.byteOffset + wasmBinary.byteLength,
444
544
  );
445
- c64wasm = new C64WASM(); // assigns to outer let
545
+ c64wasm = new C64WASM(); // assigns to outer let
446
546
  await c64wasm.instantiate(wasmAb);
447
547
 
448
548
  exports = c64wasm.exports;
@@ -457,9 +557,15 @@ export async function runHeadless(options = {}) {
457
557
  if (gamePath) {
458
558
  try {
459
559
  const gameData = await fs.readFile(gamePath);
460
- const gameArr = new Uint8Array(gameData);
560
+ const gameArr = new Uint8Array(gameData);
461
561
  const cartInfo = parseCrtInfo(gameArr, path.basename(gamePath));
462
- if (cartInfo) console.error(cartInfo.line);
562
+ if (cartInfo) {
563
+ console.error(cartInfo.line);
564
+ const unsupportedReason = getUnsupportedCrtReason(cartInfo);
565
+ if (unsupportedReason) {
566
+ throw new Error(unsupportedReason);
567
+ }
568
+ }
463
569
  const ptr = c64wasm.allocAndWrite(gameArr);
464
570
  c64wasm.updateHeapViews();
465
571
  heap = c64wasm.heap;
@@ -479,11 +585,12 @@ export async function runHeadless(options = {}) {
479
585
  }
480
586
  if (!wrapperUsed) {
481
587
  out.push('ERROR: dist-ts wrapper failed to load — cannot run headless');
482
- console.error('[headless] FATAL: dist-ts wrapper unavailable. Run: npx tsc -p tsconfig.build2.json');
483
- return {ok: false, output: out};
588
+ console.error(
589
+ '[headless] FATAL: dist-ts wrapper unavailable. Run: npx tsc -p tsconfig.build2.json',
590
+ );
591
+ return { ok: false, output: out };
484
592
  }
485
593
 
486
-
487
594
  // ── Input server (WebSocket) ──────────────────────────────────────────────
488
595
  // Start the embedded WebSocket input server when --input is passed.
489
596
  // Remote clients connect and send JSON InputEvent messages which are
@@ -503,11 +610,12 @@ export async function runHeadless(options = {}) {
503
610
  const kickTokenUrl = new URL(kickTokenRelPath, import.meta.url).href;
504
611
  const kickTokens = await import(kickTokenUrl);
505
612
  validateKickToken = kickTokens.validateKickToken;
506
- } catch { /* standalone mode — admin kick not available */ }
613
+ } catch {
614
+ /* standalone mode — admin kick not available */
615
+ }
507
616
 
508
617
  const dirMap = { up: 0x1, down: 0x2, left: 0x4, right: 0x8 };
509
618
 
510
-
511
619
  /** Flush all SID ring state after any emulator reset/cart-change.
512
620
  * The WASM SID resets its internal write cursor on c64_reset(), so any
513
621
  * samples still in the JS ring are from the old game and must be discarded.
@@ -520,13 +628,50 @@ export async function runHeadless(options = {}) {
520
628
  * game's own startup sound sequence. */
521
629
  function resetSidRing() {
522
630
  sidSampleAccum = 0;
523
- sidRingWrite = 0;
524
- sidRingRead = 0;
525
- sidRingCount = 0;
631
+ sidRingWrite = 0;
632
+ sidRingRead = 0;
633
+ sidRingCount = 0;
526
634
  sidFrameBufMax.fill(0);
527
635
  sidFrameView = sidFrameBufMax.subarray(0, 1);
528
636
  }
529
637
 
638
+ function handleInputEvent(event) {
639
+ if (!exports) return;
640
+ if (event.type === 'joystick') {
641
+ const port = (event.joystickPort ?? 2) - 1; // 1-based → 0-based
642
+ const dir = event.direction ? (dirMap[event.direction] ?? 0) : 0;
643
+ const fire = event.fire || event.fire1 ? 0x10 : 0;
644
+ if (event.action === 'release') {
645
+ if (dir) exports.c64_joystick_release(port, dir);
646
+ if (fire) exports.c64_joystick_release(port, fire);
647
+ } else {
648
+ if (dir) exports.c64_joystick_push(port, dir);
649
+ if (fire) exports.c64_joystick_push(port, fire);
650
+ }
651
+ if (verbose) {
652
+ const role = event._role ?? 'unknown';
653
+ console.error(
654
+ `[event] input joystick role=${role} port=${event.joystickPort ?? 2} action=${event.action ?? 'press'} dir=${event.direction ?? '-'} fire=${!!(event.fire || event.fire1)}`,
655
+ );
656
+ }
657
+ } else if (event.type === 'key') {
658
+ const domKey = String(event.key ?? '');
659
+ const shiftKey = !!event.shiftKey;
660
+ const evType = event.action === 'up' ? 'keyup' : 'keydown';
661
+ const c64acts = domKeyToC64Actions(domKey, shiftKey, evType);
662
+ for (const act of c64acts) {
663
+ if (act.action === 'press') exports.keyboard_keyPressed(act.key);
664
+ else exports.keyboard_keyReleased(act.key);
665
+ }
666
+ if (verbose && c64acts.length > 0) {
667
+ const role = event._role ?? 'unknown';
668
+ console.error(
669
+ `[input] input key role=${role} ${evType} "${domKey}" → ${JSON.stringify(c64acts)}`,
670
+ );
671
+ }
672
+ }
673
+ }
674
+
530
675
  inputServer = createInputServer({
531
676
  port: wsPort,
532
677
  verbose,
@@ -543,149 +688,170 @@ export async function runHeadless(options = {}) {
543
688
  getWebrtcPeerSnapshot: () => getWebrtcPeerSnapshot(),
544
689
  disconnectWebrtcPeersByAddr: (addr, reason) => disconnectWebrtcPeersByAddr(addr, reason),
545
690
  disconnectAllWebrtcPeers: (reason) => disconnectAllWebrtcPeers(reason),
546
- onCommand: (cmd) => {
691
+ onCommand: async (cmd) => {
547
692
  if (!exports) return;
548
693
  if (cmd.type === 'load-file' || cmd.type === 'load-crt') {
549
- const requestedType = cmd.type === 'load-crt' ? 'crt' : (cmd.fileType ?? inferLoadType(cmd.filename));
550
- // Decode base64 → Uint8Array immediately and release the large
551
- // base64 string from the cmd object as soon as possible so GC
552
- // can reclaim it during the subsequent async gap.
553
- const buf = Buffer.from(cmd.data, 'base64');
554
- // Slice to own ArrayBuffer — avoids aliasing Node's pooled Buffer
555
- // which could span a much larger backing store than the data alone.
556
- const arr = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength).slice();
557
- cmd.data = null; // release base64 string early
558
- const byteLen = arr.length;
559
- const filename = cmd.filename;
560
- // Defer the blocking WASM work (malloc + copy + cartridge parse)
561
- // via setImmediate so the event loop can drain any pending frame
562
- // writes / setTimeout callbacks before the synchronous WASM work
563
- // begins. This prevents the frame loop from stalling mid-write.
564
- // Return a Promise so input-server waits before broadcasting
565
- // cart-loaded — ensuring clients are told only after load succeeds.
566
- return new Promise((resolve, reject) => {
567
- setImmediate(async () => {
694
+ const requestedType =
695
+ cmd.type === 'load-crt' ? 'crt' : (cmd.fileType ?? inferLoadType(cmd.filename));
696
+ // Decode base64 → Uint8Array immediately and release the large
697
+ // base64 string from the cmd object as soon as possible so GC
698
+ // can reclaim it during the subsequent async gap.
699
+ const buf = Buffer.from(cmd.data, 'base64');
700
+ // Slice to own ArrayBuffer — avoids aliasing Node's pooled Buffer
701
+ // which could span a much larger backing store than the data alone.
702
+ const arr = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength).slice();
703
+ cmd.data = null; // release base64 string early
704
+ const byteLen = arr.length;
705
+ const filename = cmd.filename;
706
+ // Defer the blocking WASM work (malloc + copy + cartridge parse)
707
+ // via setImmediate so the event loop can drain any pending frame
708
+ // writes / setTimeout callbacks before the synchronous WASM work
709
+ // begins. This prevents the frame loop from stalling mid-write.
710
+ // Return a Promise so input-server waits before broadcasting
711
+ // cart-loaded — ensuring clients are told only after load succeeds.
712
+ return new Promise((resolve, reject) => {
713
+ setImmediate(async () => {
714
+ try {
715
+ const gapStart = Date.now();
716
+ const loadType = requestedType;
717
+ // For cartridge loads, reset first so bank state does not leak.
718
+ if (loadType === 'crt') {
719
+ exports.c64_removeCartridge();
720
+ exports.c64_reset();
721
+ }
722
+ const ptr = c64wasm.allocAndWrite(arr);
723
+ c64wasm.updateHeapViews();
724
+ heap = c64wasm.heap;
568
725
  try {
569
- const gapStart = Date.now();
570
- const loadType = requestedType;
571
- // For cartridge loads, reset first so bank state does not leak.
572
726
  if (loadType === 'crt') {
573
- exports.c64_removeCartridge();
574
- exports.c64_reset();
575
- }
576
- const ptr = c64wasm.allocAndWrite(arr);
577
- c64wasm.updateHeapViews();
578
- heap = c64wasm.heap;
579
- try {
580
- if (loadType === 'crt') {
581
- const cartInfo = parseCrtInfo(arr, filename);
582
- if (cartInfo) console.error(cartInfo.line);
583
- exports.c64_loadCartridge(ptr, byteLen);
584
- } else if (loadType === 'prg') {
585
- exports.c64_loadPRG(ptr, byteLen, 1);
586
- await typeCommandText(exports, 'run\n');
587
- } else if (loadType === 'd64') {
588
- exports.c64_setDriveEnabled(1);
589
- exports.c64_insertDisk(ptr, byteLen);
590
- } else if (loadType === 'snapshot') {
591
- exports.c64_loadSnapshot(ptr, byteLen);
592
- } else {
593
- throw new Error(`Unsupported load-file type: ${loadType}`);
727
+ const cartInfo = parseCrtInfo(arr, filename);
728
+ if (cartInfo) {
729
+ console.error(cartInfo.line);
730
+ const unsupportedReason = getUnsupportedCrtReason(cartInfo);
731
+ if (unsupportedReason) {
732
+ throw new Error(unsupportedReason);
733
+ }
594
734
  }
595
- } finally {
596
- c64wasm.free(ptr);
597
- }
598
- const gapMs = Date.now() - gapStart;
599
- //
600
- // ── Audio RTP re-sync after blocking gap ─────────────────────
601
- // c64_loadCartridge blocks the event loop for ~1300ms. During
602
- // this time the frame loop is frozen so no audio is pushed to
603
- // RTCAudioSource. The video RTP clock (driven by @roamhq/wrtc
604
- // internally via wall-clock) keeps ticking, but the audio RTP
605
- // clock only advances when onData() is called — so audio falls
606
- // ~1300ms behind video. The browser's AV sync logic then holds
607
- // video playback until audio catches up, manifesting as input lag.
608
- //
609
- // Fix: push silence frames totalling the measured gap duration so
610
- // the audio RTP clock jumps forward by the same amount the video
611
- // RTP clock advanced during the blockage.
612
- resetSidRing();
613
- if (webrtcEncoder) {
614
- webrtcEncoder.pushSilenceForGap(gapMs);
615
- if (verbose) console.error(`[headless] pushed ${gapMs}ms silence to re-align audio RTP after cart load`);
735
+ exports.c64_loadCartridge(ptr, byteLen);
736
+ } else if (loadType === 'prg') {
737
+ exports.c64_loadPRG(ptr, byteLen, 1);
738
+ await typeCommandText(exports, 'run\n');
739
+ } else if (loadType === 'd64') {
740
+ exports.c64_setDriveEnabled(1);
741
+ exports.c64_insertDisk(ptr, byteLen);
742
+ } else if (loadType === 'snapshot') {
743
+ exports.c64_reset();
744
+ exports.c64_loadSnapshot(ptr, byteLen);
745
+ } else {
746
+ throw new Error(`Unsupported load-file type: ${loadType}`);
616
747
  }
617
- if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
618
- if (verbose) console.error(`[headless] file loaded: ${filename} (${loadType}, ${byteLen} bytes, gap=${gapMs}ms)`);
619
- else if (logEvents) console.error(`[event] cart-loaded filename=${filename} type=${loadType} bytes=${byteLen} gap=${gapMs}ms`);
620
- resolve();
621
- } catch (err) {
622
- if (verbose) console.error('[headless] cart load (deferred) error:', err);
623
- else if (logEvents) console.error(`[event] error cart-load-failed filename=${filename} err=${err && err.message ? err.message : err}`);
624
- reject(err);
748
+ } finally {
749
+ c64wasm.free(ptr);
750
+ }
751
+ const gapMs = Date.now() - gapStart;
752
+ //
753
+ // ── Audio RTP re-sync after blocking gap ─────────────────────
754
+ // c64_loadCartridge blocks the event loop for ~1300ms. During
755
+ // this time the frame loop is frozen so no audio is pushed to
756
+ // RTCAudioSource. The video RTP clock (driven by @roamhq/wrtc
757
+ // internally via wall-clock) keeps ticking, but the audio RTP
758
+ // clock only advances when onData() is called — so audio falls
759
+ // ~1300ms behind video. The browser's AV sync logic then holds
760
+ // video playback until audio catches up, manifesting as input lag.
761
+ //
762
+ // Fix: push silence frames totalling the measured gap duration so
763
+ // the audio RTP clock jumps forward by the same amount the video
764
+ // RTP clock advanced during the blockage.
765
+ 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
+ );
625
772
  }
626
- });
773
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
774
+ if (verbose)
775
+ console.error(
776
+ `[headless] file loaded: ${filename} (${loadType}, ${byteLen} bytes, gap=${gapMs}ms)`,
777
+ );
778
+ else if (logEvents)
779
+ console.error(
780
+ `[event] cart-loaded filename=${filename} type=${loadType} bytes=${byteLen} gap=${gapMs}ms`,
781
+ );
782
+ resolve();
783
+ } catch (err) {
784
+ if (verbose) console.error('[headless] cart load (deferred) error:', err);
785
+ else if (logEvents)
786
+ console.error(
787
+ `[event] error cart-load-failed filename=${filename} err=${err && err.message ? err.message : err}`,
788
+ );
789
+ reject(err);
790
+ }
627
791
  });
628
- } else if (cmd.type === 'detach-crt') {
629
- const gapStart = Date.now();
630
- exports.c64_removeCartridge();
631
- exports.c64_reset(); // return to clean BASIC prompt
632
- const gapMs = Date.now() - gapStart;
633
- resetSidRing();
634
- if (webrtcEncoder) {
635
- webrtcEncoder.pushSilenceForGap(gapMs);
636
- if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after detach`);
637
- }
638
- if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
639
- if (verbose) console.error('[headless] cart detached');
640
- else if (logEvents) console.error(`[event] cart-detached gap=${gapMs}ms`);
641
- } else if (cmd.type === 'hard-reset') {
642
- // Instant hard reset: reset machine state but keep current media
643
- // attached (cartridge/disk), matching offline player behavior.
644
- const gapStart = Date.now();
645
- exports.c64_reset();
646
- const gapMs = Date.now() - gapStart;
647
- resetSidRing();
648
- if (webrtcEncoder) {
649
- webrtcEncoder.pushSilenceForGap(gapMs);
650
- if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after hard reset`);
651
- }
652
- if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
653
- if (verbose) console.error('[headless] hard reset');
654
- else if (logEvents) console.error(`[event] hard-reset gap=${gapMs}ms`);
792
+ });
793
+ } else if (cmd.type === 'save-snapshot') {
794
+ const ptr = exports.c64_getSnapshot();
795
+ const byteLen = exports.c64_getSnapshotSize();
796
+ c64wasm.updateHeapViews();
797
+ heap = c64wasm.heap;
798
+ if (!heap) throw new Error('WASM heap unavailable');
799
+ const snapshot = heap.heapU8.slice(ptr, ptr + byteLen);
800
+ return {
801
+ filename: formatSnapshotFilename(),
802
+ data: Buffer.from(snapshot).toString('base64'),
803
+ };
804
+ } else if (cmd.type === 'detach-crt') {
805
+ const gapStart = Date.now();
806
+ exports.c64_removeCartridge();
807
+ exports.c64_reset(); // return to clean BASIC prompt
808
+ const gapMs = Date.now() - gapStart;
809
+ resetSidRing();
810
+ if (webrtcEncoder) {
811
+ webrtcEncoder.pushSilenceForGap(gapMs);
812
+ if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after detach`);
655
813
  }
656
- },
657
- onInput: (event) => {
658
- if (!exports) return;
659
- if (event.type === 'joystick') {
660
- const port = ((event.joystickPort ?? 2) - 1); // 1-based → 0-based
661
- const dir = event.direction ? (dirMap[event.direction] ?? 0) : 0;
662
- const fire = (event.fire || event.fire1) ? 0x10 : 0;
663
- if (event.action === 'release') {
664
- if (dir) exports.c64_joystick_release(port, dir);
665
- if (fire) exports.c64_joystick_release(port, fire);
666
- } else {
667
- if (dir) exports.c64_joystick_push(port, dir);
668
- if (fire) exports.c64_joystick_push(port, fire);
669
- }
670
- if (verbose) {
671
- const role = event._role ?? 'unknown';
672
- console.error(`[event] input joystick role=${role} port=${event.joystickPort ?? 2} action=${event.action ?? 'press'} dir=${event.direction ?? '-'} fire=${!!(event.fire || event.fire1)}`);
814
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
815
+ if (verbose) console.error('[headless] cart detached');
816
+ else if (logEvents) console.error(`[event] cart-detached gap=${gapMs}ms`);
817
+ } else if (cmd.type === 'hard-reset') {
818
+ // Instant hard reset: reset machine state but keep current media
819
+ // attached (cartridge/disk), matching offline player behavior.
820
+ const gapStart = Date.now();
821
+ exports.c64_reset();
822
+ const gapMs = Date.now() - gapStart;
823
+ resetSidRing();
824
+ if (webrtcEncoder) {
825
+ webrtcEncoder.pushSilenceForGap(gapMs);
826
+ if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after hard reset`);
673
827
  }
674
- } else if (event.type === 'key') {
675
- const domKey = String(event.key ?? '');
676
- const shiftKey = !!event.shiftKey;
677
- const evType = event.action === 'up' ? 'keyup' : 'keydown';
678
- const c64acts = domKeyToC64Actions(domKey, shiftKey, evType);
679
- for (const act of c64acts) {
680
- if (act.action === 'press') exports.keyboard_keyPressed(act.key);
681
- else exports.keyboard_keyReleased(act.key);
682
- }
683
- if (verbose && c64acts.length > 0) {
684
- const role = event._role ?? 'unknown';
685
- console.error(`[input] input key role=${role} ${evType} "${domKey}" → ${JSON.stringify(c64acts)}`);
828
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
829
+ if (verbose) console.error('[headless] hard reset');
830
+ else if (logEvents) console.error(`[event] hard-reset gap=${gapMs}ms`);
831
+ } else if (cmd.type === 'reboot') {
832
+ if (!C64WASMClass) throw new Error('C64WASM wrapper unavailable for reboot');
833
+ const gapStart = Date.now();
834
+ const next = new C64WASMClass();
835
+ await next.instantiate(wasmAb);
836
+ c64wasm = next;
837
+ exports = c64wasm.exports;
838
+ heap = c64wasm.heap;
839
+ exports.c64_init();
840
+ exports.sid_setSampleRate(44100);
841
+ exports.debugger_set_speed(100);
842
+ exports.debugger_play();
843
+ const gapMs = Date.now() - gapStart;
844
+ resetSidRing();
845
+ if (webrtcEncoder) {
846
+ webrtcEncoder.pushSilenceForGap(gapMs);
847
+ if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after reboot`);
686
848
  }
849
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
850
+ if (verbose) console.error('[headless] emulator rebooted (fresh WASM instance)');
851
+ else if (logEvents) console.error(`[event] machine-rebooted gap=${gapMs}ms`);
687
852
  }
688
853
  },
854
+ onInput: handleInputEvent,
689
855
  });
690
856
  out.push(`Input server listening on ws://0.0.0.0:${wsPort}`);
691
857
  } catch (e) {
@@ -699,7 +865,7 @@ export async function runHeadless(options = {}) {
699
865
  // webrtcPort (default 9002). Each connecting browser gets its own
700
866
  // RTCPeerConnection fed by the shared encoder tracks.
701
867
  let webrtcEncoder = null;
702
- let webrtcServer = null;
868
+ let webrtcServer = null;
703
869
  let getWebrtcTelemetry = () => null;
704
870
  let getWebrtcPeerSnapshot = () => null;
705
871
  let disconnectWebrtcPeersByAddr = () => 0;
@@ -707,7 +873,7 @@ export async function runHeadless(options = {}) {
707
873
 
708
874
  if (webrtc) {
709
875
  try {
710
- const { WebRTCEncoder } = await import('./webrtc-encoder.mjs');
876
+ const { WebRTCEncoder } = await import('./webrtc-encoder.mjs');
711
877
  const { createWebRTCServer } = await import('./webrtc-server.mjs');
712
878
  const wrtcLib = (await import('@roamhq/wrtc')).default;
713
879
  const { MediaStream } = wrtcLib;
@@ -734,6 +900,15 @@ export async function runHeadless(options = {}) {
734
900
  },
735
901
  onPeerConnected(pc) {
736
902
  if (verbose) console.error('[webrtc] peer ICE connected');
903
+ if (webrtcServer) {
904
+ // New peers can attach mid-GOP and sit on a black frame until the
905
+ // next natural keyframe arrives. Force one on join so the decoder
906
+ // gets a decodable frame immediately.
907
+ webrtcServer.forceKeyframe(videoTrack);
908
+ setTimeout(() => {
909
+ webrtcServer?.forceKeyframe(videoTrack);
910
+ }, 300);
911
+ }
737
912
  // Reduce video sender bitrate after connection to minimise encode
738
913
  // latency. A tight ceiling keeps frame sizes small and predictable,
739
914
  // reducing the encoder's internal queue and decode buffer on the
@@ -743,7 +918,10 @@ export async function runHeadless(options = {}) {
743
918
  for (const sender of senders) {
744
919
  if (sender.track && sender.track.kind === 'video') {
745
920
  const params = sender.getParameters();
746
- const maxBitrateBps = Math.max(100_000, Math.round(webrtcMaxBitrateKbpsSafe * 1000));
921
+ const maxBitrateBps = Math.max(
922
+ 100_000,
923
+ Math.round(webrtcMaxBitrateKbpsSafe * 1000),
924
+ );
747
925
  if (params.encodings && params.encodings.length > 0) {
748
926
  params.encodings[0].maxBitrate = maxBitrateBps;
749
927
  } else {
@@ -755,6 +933,14 @@ export async function runHeadless(options = {}) {
755
933
  }
756
934
  } catch (_) {}
757
935
  },
936
+ onDataChannelInput: ({ msg, remoteAddr, sessionId, send }) => {
937
+ inputServer?.handlePeerDataMessage?.({
938
+ addr: remoteAddr,
939
+ sessionId,
940
+ msg,
941
+ send,
942
+ });
943
+ },
758
944
  });
759
945
  if (typeof webrtcServer.getTelemetrySnapshot === 'function') {
760
946
  getWebrtcTelemetry = () => webrtcServer.getTelemetrySnapshot();
@@ -763,13 +949,16 @@ export async function runHeadless(options = {}) {
763
949
  getWebrtcPeerSnapshot = () => webrtcServer.getPeerSnapshot();
764
950
  }
765
951
  if (typeof webrtcServer.disconnectPeersByAddr === 'function') {
766
- disconnectWebrtcPeersByAddr = (addr, reason) => webrtcServer.disconnectPeersByAddr(addr, reason);
952
+ disconnectWebrtcPeersByAddr = (addr, reason) =>
953
+ webrtcServer.disconnectPeersByAddr(addr, reason);
767
954
  }
768
955
  if (typeof webrtcServer.disconnectAllPeers === 'function') {
769
956
  disconnectAllWebrtcPeers = (reason) => webrtcServer.disconnectAllPeers(reason);
770
957
  }
771
958
 
772
- out.push(`WebRTC player at http://0.0.0.0:${webrtcPort}/ (send cap: ${webrtcOutputFpsSafe > 0 ? `${webrtcOutputFpsSafe}fps` : 'off'})`);
959
+ out.push(
960
+ `WebRTC player at http://0.0.0.0:${webrtcPort}/ (send cap: ${webrtcOutputFpsSafe > 0 ? `${webrtcOutputFpsSafe}fps` : 'off'})`,
961
+ );
773
962
  } catch (e) {
774
963
  console.error('[headless] Failed to start WebRTC server:', e && e.message ? e.message : e);
775
964
  out.push(`webrtc-server-failed: ${String(e)}`);
@@ -780,9 +969,10 @@ export async function runHeadless(options = {}) {
780
969
  // Run state and timing
781
970
  let frameCount = 0;
782
971
  let ffmpegDied = false; // set to true if ffmpeg exits unexpectedly and we give up
783
- const targetFps = (typeof fps === 'number' && !Number.isNaN(fps) && fps > 0) ? fps : 60;
972
+ const targetFps = typeof fps === 'number' && !Number.isNaN(fps) && fps > 0 ? fps : 60;
784
973
  const frameMs = Math.round(1000 / targetFps);
785
- const webrtcSendFps = webrtcOutputFpsSafe > 0 ? Math.max(1, Math.min(targetFps, webrtcOutputFpsSafe)) : targetFps;
974
+ const webrtcSendFps =
975
+ webrtcOutputFpsSafe > 0 ? Math.max(1, Math.min(targetFps, webrtcOutputFpsSafe)) : targetFps;
786
976
  const webrtcSendIntervalMs = 1000 / webrtcSendFps;
787
977
  let nextVideoDueAtMs = nowMonoMs();
788
978
  let videoFramesSent = 0;
@@ -808,7 +998,8 @@ export async function runHeadless(options = {}) {
808
998
  const lag = eventLoopMonitor ? eventLoopMonitor.min / 1e6 : 0; // ms
809
999
  // Keep event-loop lag diagnostics behind --verbose only. These can be
810
1000
  // noisy in steady-state and are intended for performance debugging.
811
- if (lag > 5 && verbose) { // only log if >5ms lag
1001
+ if (lag > 5 && verbose) {
1002
+ // only log if >5ms lag
812
1003
  console.error(`[event] event-loop-lag min=${lag.toFixed(2)}ms`);
813
1004
  }
814
1005
  if (eventLoopMonitor) eventLoopMonitor.reset();
@@ -842,24 +1033,24 @@ export async function runHeadless(options = {}) {
842
1033
  //
843
1034
  // Ring sizing: hold at least 2× SID_BUFFER_SIZE so one full WASM pull
844
1035
  // never overflows while the consumer hasn't caught up yet.
845
- const SID_RING_SIZE = SID_BUFFER_SIZE * 4; // 16384 samples of headroom
846
- const sidRing = new Float32Array(SID_RING_SIZE);
847
- let sidRingWrite = 0; // next write position in sidRing
848
- let sidRingRead = 0; // next read position in sidRing
849
- let sidRingCount = 0; // samples currently in the ring
1036
+ const SID_RING_SIZE = SID_BUFFER_SIZE * 4; // 16384 samples of headroom
1037
+ const sidRing = new Float32Array(SID_RING_SIZE);
1038
+ let sidRingWrite = 0; // next write position in sidRing
1039
+ let sidRingRead = 0; // next read position in sidRing
1040
+ let sidRingCount = 0; // samples currently in the ring
850
1041
  // Accumulator: how many emulated samples have passed since last WASM pull.
851
- let sidSampleAccum = 0;
1042
+ let sidSampleAccum = 0;
852
1043
  // Single staging buffer for per-frame audio delivered to ffmpeg/WebRTC.
853
1044
  const sidFrameBufMax = new Float32Array(MAX_AUDIO_SAMPLES_PER_ITER);
854
- let sidFrameView = sidFrameBufMax.subarray(0, 1);
1045
+ let sidFrameView = sidFrameBufMax.subarray(0, 1);
855
1046
 
856
1047
  /** Pull one 4096-sample chunk from the WASM SID buffer into the JS ring. */
857
1048
  function pullSidBuffer() {
858
1049
  if (!exports || !heap || typeof exports.sid_getAudioBuffer !== 'function') return;
859
1050
  try {
860
- const ptr = exports.sid_getAudioBuffer();
861
- const base = ptr >> 2;
862
- const src = heap.heapF32;
1051
+ const ptr = exports.sid_getAudioBuffer();
1052
+ const base = ptr >> 2;
1053
+ const src = heap.heapF32;
863
1054
  for (let i = 0; i < SID_BUFFER_SIZE; i++) {
864
1055
  sidRing[(sidRingWrite + i) % SID_RING_SIZE] = src[base + i];
865
1056
  }
@@ -897,18 +1088,19 @@ export async function runHeadless(options = {}) {
897
1088
  for (let i = 0; i < samplesNeeded; i++) {
898
1089
  sidFrameBufMax[i] = sidRing[(sidRingRead + i) % SID_RING_SIZE];
899
1090
  }
900
- sidRingRead = (sidRingRead + samplesNeeded) % SID_RING_SIZE;
1091
+ sidRingRead = (sidRingRead + samplesNeeded) % SID_RING_SIZE;
901
1092
  sidRingCount -= samplesNeeded;
902
1093
  return true;
903
1094
  }
904
1095
 
905
-
906
1096
  // Resolve output path once — treat remote URLs verbatim, local file paths
907
1097
  // should be resolved relative to the current working directory (process.cwd()).
908
1098
  // If no output provided, fall back to repoRoot/temp as before.
909
1099
  const isRemoteUrl = (s) => /^[a-zA-Z]+:\/\//.test(s);
910
1100
  const outPathResolved = output
911
- ? (isRemoteUrl(output) ? output : path.resolve(process.cwd(), output))
1101
+ ? isRemoteUrl(output)
1102
+ ? output
1103
+ : path.resolve(process.cwd(), output)
912
1104
  : path.join(repoRoot, 'temp', `c64-record-${Date.now()}.mp4`);
913
1105
  const isRtmpOutput = isRemoteUrl(outPathResolved);
914
1106
 
@@ -928,7 +1120,7 @@ export async function runHeadless(options = {}) {
928
1120
  raw,
929
1121
  verbose,
930
1122
  audio,
931
- sampleRate: audioSampleRate
1123
+ sampleRate: audioSampleRate,
932
1124
  });
933
1125
  return started;
934
1126
  }
@@ -940,7 +1132,7 @@ export async function runHeadless(options = {}) {
940
1132
  const msg = 'ffmpeg-record-failed:start-failed';
941
1133
  out.push(msg);
942
1134
  console.error('[headless] ' + msg);
943
- return {ok: false, output: out};
1135
+ return { ok: false, output: out };
944
1136
  } else {
945
1137
  const msg = `Recording to ${outPathResolved} (${durationSec ? durationSec + 's' : 'endless'} @ ${fps}fps${audio ? ' +audio' : ''})`;
946
1138
  out.push(msg);
@@ -975,7 +1167,9 @@ export async function runHeadless(options = {}) {
975
1167
  const runStartTime = Date.now();
976
1168
  const isStreamingMode = record || webrtc;
977
1169
  const endTime = isStreamingMode
978
- ? (durationSec ? runStartTime + durationSec * 1000 : Infinity)
1170
+ ? durationSec
1171
+ ? runStartTime + durationSec * 1000
1172
+ : Infinity
979
1173
  : null;
980
1174
 
981
1175
  let windowStart = nowMonoMs();
@@ -984,7 +1178,8 @@ export async function runHeadless(options = {}) {
984
1178
 
985
1179
  while (isStreamingMode ? Date.now() < endTime : frameCount < frames) {
986
1180
  try {
987
- if (verbose && frameCount % 50 === 0) console.error(`[headless] loop frameCount=${frameCount}`);
1181
+ if (verbose && frameCount % 50 === 0)
1182
+ console.error(`[headless] loop frameCount=${frameCount}`);
988
1183
 
989
1184
  // Capture frame start time BEFORE emulation so sleepMs accounts for
990
1185
  // ALL work in this iteration (emulation + audio + video push + ffmpeg).
@@ -1002,7 +1197,7 @@ export async function runHeadless(options = {}) {
1002
1197
  // AND debugger_isRunning() — we mirror that here so we never push a stale
1003
1198
  // or repeated pixel buffer into WebRTC during boot/reset sequences.
1004
1199
  const frameReady = !!exports.debugger_update(emuDeltaMs);
1005
- const isRunning = !!exports.debugger_isRunning();
1200
+ const isRunning = !!exports.debugger_isRunning();
1006
1201
 
1007
1202
  // ── Audio: pull from WASM SID → JS ring → per-frame slice ───────────
1008
1203
  // Audio runs every frame regardless of frameReady/isRunning so the WebRTC
@@ -1034,7 +1229,7 @@ export async function runHeadless(options = {}) {
1034
1229
  videoFramesDroppedLateWindow += lateDrops;
1035
1230
  nextVideoDueAtMs += lateDrops * webrtcSendIntervalMs;
1036
1231
  }
1037
- const ptr = exports.c64_getPixelBuffer();
1232
+ const ptr = exports.c64_getPixelBuffer();
1038
1233
  const rgba = heap.heapU8.subarray(ptr, ptr + 384 * 272 * 4);
1039
1234
  webrtcEncoder.pushVideoFrame(rgba);
1040
1235
  videoFramesSent++;
@@ -1111,8 +1306,7 @@ export async function runHeadless(options = {}) {
1111
1306
  const sleepMs = Math.max(0, frameMs - workMs);
1112
1307
  if (sleepMs > 0) await new Promise((r) => setTimeout(r, sleepMs));
1113
1308
  await new Promise((r) => setImmediate(r)); // drain any remaining I/O callbacks
1114
- } catch (_) {
1115
- }
1309
+ } catch (_) {}
1116
1310
  frameCount++;
1117
1311
  // diagnostics
1118
1312
  windowCount++;
@@ -1128,11 +1322,15 @@ export async function runHeadless(options = {}) {
1128
1322
  const drift = actualFps - targetFps;
1129
1323
  const driftPct = Math.abs(drift / targetFps) * 100;
1130
1324
  if (driftPct > 10) {
1131
- console.error(`[event] drift fps-actual=${actualFps.toFixed(1)} fps-target=${targetFps} drift=${drift > 0 ? '+' : ''}${drift.toFixed(1)} (${driftPct.toFixed(0)}%)`);
1325
+ console.error(
1326
+ `[event] drift fps-actual=${actualFps.toFixed(1)} fps-target=${targetFps} drift=${drift > 0 ? '+' : ''}${drift.toFixed(1)} (${driftPct.toFixed(0)}%)`,
1327
+ );
1132
1328
  }
1133
1329
  // Keep per-window drop telemetry behind --verbose only.
1134
1330
  if (verbose && (videoFramesDroppedLateWindow > 0 || videoFramesDroppedCapWindow > 0)) {
1135
- console.error(`[event] webrtc-video-drop sent=${videoFramesSent} late=${videoFramesDroppedLateWindow} cap=${videoFramesDroppedCapWindow} totalLate=${videoFramesDroppedLate} totalCap=${videoFramesDroppedCap} fpsCap=${webrtcSendFps}`);
1331
+ console.error(
1332
+ `[event] webrtc-video-drop sent=${videoFramesSent} late=${videoFramesDroppedLateWindow} cap=${videoFramesDroppedCapWindow} totalLate=${videoFramesDroppedLate} totalCap=${videoFramesDroppedCap} fpsCap=${webrtcSendFps}`,
1333
+ );
1136
1334
  }
1137
1335
  }
1138
1336
  runtimeStats.videoFramesSent = videoFramesSent;
@@ -1141,12 +1339,28 @@ export async function runHeadless(options = {}) {
1141
1339
  const webrtcTelemetry = getWebrtcTelemetry();
1142
1340
  if (webrtcTelemetry) {
1143
1341
  runtimeStats.webrtcPeerCount = webrtcTelemetry.peerCount ?? null;
1144
- runtimeStats.webrtcAvgRttMs = Number.isFinite(webrtcTelemetry.avgRttMs) ? webrtcTelemetry.avgRttMs : null;
1145
- runtimeStats.webrtcSendDelayMsPerPacket = Number.isFinite(webrtcTelemetry.sendDelayMsPerPacket) ? webrtcTelemetry.sendDelayMsPerPacket : null;
1146
- runtimeStats.webrtcEncodeMsPerFrame = Number.isFinite(webrtcTelemetry.encodeMsPerFrame) ? webrtcTelemetry.encodeMsPerFrame : null;
1147
- runtimeStats.webrtcFramesSentPerSec = Number.isFinite(webrtcTelemetry.framesSentPerSec) ? webrtcTelemetry.framesSentPerSec : null;
1148
- runtimeStats.webrtcFramesEncodedPerSec = Number.isFinite(webrtcTelemetry.framesEncodedPerSec) ? webrtcTelemetry.framesEncodedPerSec : null;
1149
- runtimeStats.webrtcBytesSentPerSec = Number.isFinite(webrtcTelemetry.bytesSentPerSec) ? webrtcTelemetry.bytesSentPerSec : null;
1342
+ runtimeStats.webrtcAvgRttMs = Number.isFinite(webrtcTelemetry.avgRttMs)
1343
+ ? webrtcTelemetry.avgRttMs
1344
+ : null;
1345
+ runtimeStats.webrtcSendDelayMsPerPacket = Number.isFinite(
1346
+ webrtcTelemetry.sendDelayMsPerPacket,
1347
+ )
1348
+ ? webrtcTelemetry.sendDelayMsPerPacket
1349
+ : null;
1350
+ runtimeStats.webrtcEncodeMsPerFrame = Number.isFinite(webrtcTelemetry.encodeMsPerFrame)
1351
+ ? webrtcTelemetry.encodeMsPerFrame
1352
+ : null;
1353
+ runtimeStats.webrtcFramesSentPerSec = Number.isFinite(webrtcTelemetry.framesSentPerSec)
1354
+ ? webrtcTelemetry.framesSentPerSec
1355
+ : null;
1356
+ runtimeStats.webrtcFramesEncodedPerSec = Number.isFinite(
1357
+ webrtcTelemetry.framesEncodedPerSec,
1358
+ )
1359
+ ? webrtcTelemetry.framesEncodedPerSec
1360
+ : null;
1361
+ runtimeStats.webrtcBytesSentPerSec = Number.isFinite(webrtcTelemetry.bytesSentPerSec)
1362
+ ? webrtcTelemetry.bytesSentPerSec
1363
+ : null;
1150
1364
  runtimeStats.webrtcQualityLimitation = webrtcTelemetry.qualityLimitation ?? null;
1151
1365
  }
1152
1366
  runtimeStats.sampledAt = Date.now();
@@ -1157,12 +1371,11 @@ export async function runHeadless(options = {}) {
1157
1371
  }
1158
1372
  if (verify && frameCount % 60 === 0) {
1159
1373
  const cycleCount = exports.c64_getCycleCount ? exports.c64_getCycleCount() : null;
1160
- out.push(JSON.stringify({pid: process.pid, frame: frameCount, cycles: cycleCount}));
1374
+ out.push(JSON.stringify({ pid: process.pid, frame: frameCount, cycles: cycleCount }));
1161
1375
  try {
1162
1376
  const pc = exports.c64_getPC ? exports.c64_getPC() : null;
1163
1377
  console.error(`[headless] verify: frame=${frameCount} pc=${pc} cycles=${cycleCount}`);
1164
- } catch (_) {
1165
- }
1378
+ } catch (_) {}
1166
1379
  }
1167
1380
  }
1168
1381
 
@@ -1219,7 +1432,7 @@ export async function runHeadless(options = {}) {
1219
1432
  out.push(`ffmpeg-stop-failed: ${String(e)}`);
1220
1433
  }
1221
1434
  }
1222
- return {ok: !ffmpegDied, output: out};
1435
+ return { ok: !ffmpegDied, output: out };
1223
1436
  }
1224
1437
 
1225
1438
  export default runHeadless;