c64-ready 0.11.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +10 -2
  2. package/dist/assets/CHANGELOG-B12WeYEc.js +116 -0
  3. package/dist/assets/index-fUdEY2R7.js +610 -0
  4. package/dist/index.html +1 -1
  5. package/dist/tools/anykey-c64.prg +0 -0
  6. package/dist/tools/tools.json +6 -0
  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/src/emulator/c64-emulator.ts +34 -2
  27. package/src/emulator/crt-info.ts +35 -23
  28. package/src/emulator/input.ts +5 -2
  29. package/src/headless/c64-headless.ts +5 -0
  30. package/src/headless/c64-key-map.mjs +1 -1
  31. package/src/headless/headless-cli.mjs +410 -232
  32. package/src/headless/input-server.mjs +463 -198
  33. package/src/headless/webrtc-server.mjs +235 -70
  34. package/src/main.ts +37 -3
  35. package/src/player/c64-player.ts +121 -37
  36. package/src/player/styles/ui-controller.css +114 -21
  37. package/src/player/ui-controller.ts +176 -8
  38. package/dist/assets/CHANGELOG-CPMeNyjb.js +0 -261
  39. package/dist/assets/index-CeQto0sd.js +0 -499
@@ -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,12 +162,20 @@ 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
 
@@ -144,7 +218,9 @@ let _serverGitHash = null;
144
218
  try {
145
219
  const pkg = JSON.parse(readFileSync(path.join(_repoRootForBuildInfo, 'package.json'), 'utf8'));
146
220
  _serverVersion = pkg.version ?? null;
147
- } catch { /* non-fatal */ }
221
+ } catch {
222
+ /* non-fatal */
223
+ }
148
224
  try {
149
225
  // Prefer the baked-in build-arg written by the Dockerfile (works in Docker
150
226
  // where git is not installed and .git is not present).
@@ -156,11 +232,17 @@ try {
156
232
  try {
157
233
  _serverGitHash = readFileSync(hashFile, 'utf8').trim() || null;
158
234
  } catch {
159
- _serverGitHash = execSync('git rev-parse --short HEAD', { cwd: _repoRootForBuildInfo, stdio: ['ignore', 'pipe', 'ignore'] })
160
- .toString().trim();
235
+ _serverGitHash = execSync('git rev-parse --short HEAD', {
236
+ cwd: _repoRootForBuildInfo,
237
+ stdio: ['ignore', 'pipe', 'ignore'],
238
+ })
239
+ .toString()
240
+ .trim();
161
241
  }
162
242
  }
163
- } catch { /* non-fatal — git may not be available in some deploy environments */ }
243
+ } catch {
244
+ /* non-fatal — git may not be available in some deploy environments */
245
+ }
164
246
 
165
247
  /**
166
248
  * Run headless emulator. Exported so tests can inject a fake WebAssembly.instantiate.
@@ -222,20 +304,21 @@ export async function runHeadless(options = {}) {
222
304
  else if (a === '--webrtc-output-fps') webrtcOutputFps = Number(argv[++i]);
223
305
  else if (a === '--admin-token') adminToken = argv[++i] ?? '';
224
306
  else if (a === '--help' || a === '-h') {
225
- return {ok: false, output: 'help'};
307
+ return { ok: false, output: 'help' };
226
308
  }
227
309
  }
228
310
  const adminTokenSafe = String(adminToken ?? '').trim();
229
311
 
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;
312
+ const webrtcMinBitrateKbpsSafe =
313
+ Number.isFinite(webrtcMinBitrateKbps) && webrtcMinBitrateKbps > 0
314
+ ? Math.round(webrtcMinBitrateKbps)
315
+ : 200;
316
+ const webrtcMaxBitrateKbpsSafe =
317
+ Number.isFinite(webrtcMaxBitrateKbps) && webrtcMaxBitrateKbps > 0
318
+ ? Math.max(webrtcMinBitrateKbpsSafe, Math.round(webrtcMaxBitrateKbps))
319
+ : Math.max(webrtcMinBitrateKbpsSafe, 600);
320
+ const webrtcOutputFpsSafe =
321
+ Number.isFinite(webrtcOutputFps) && webrtcOutputFps > 0 ? Math.round(webrtcOutputFps) : 0;
239
322
 
240
323
  const runtimeStats = {
241
324
  webrtcSendFps: null,
@@ -307,7 +390,8 @@ export async function runHeadless(options = {}) {
307
390
  const _writeLog = (origFn, ...args) => {
308
391
  origFn.apply(console, args);
309
392
  if (logStream && logStream.writable) {
310
- const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ') + '\n';
393
+ const line =
394
+ args.map((a) => (typeof a === 'object' ? JSON.stringify(a) : String(a))).join(' ') + '\n';
311
395
  logStream.write(line);
312
396
  }
313
397
  };
@@ -318,7 +402,9 @@ export async function runHeadless(options = {}) {
318
402
 
319
403
  function _teardownLogFile() {
320
404
  if (logStream) {
321
- try { logStream.end(); } catch (_) {}
405
+ try {
406
+ logStream.end();
407
+ } catch (_) {}
322
408
  logStream = null;
323
409
  }
324
410
  if (_origConsoleLog) {
@@ -344,8 +430,7 @@ export async function runHeadless(options = {}) {
344
430
  try {
345
431
  await fs.access(p);
346
432
  return p;
347
- } catch (_) {
348
- }
433
+ } catch (_) {}
349
434
  }
350
435
  return null;
351
436
  }
@@ -355,7 +440,7 @@ export async function runHeadless(options = {}) {
355
440
  const found = await findFirstExisting(defaultWasmPaths);
356
441
  if (found) wasmPath = found;
357
442
  }
358
- if (!wasmPath) return {ok: false, err: 'no-wasm'};
443
+ if (!wasmPath) return { ok: false, err: 'no-wasm' };
359
444
 
360
445
  let gamePath = gameArg ?? null;
361
446
  // If the user requested no game, ensure we do not load any default cartridge
@@ -368,13 +453,16 @@ export async function runHeadless(options = {}) {
368
453
  }
369
454
 
370
455
  const out = [];
371
- out.push(`Starting headless C64 using WASM: ${wasmPath}` + (gamePath ? ` game: ${gamePath}` : ''));
456
+ out.push(
457
+ `Starting headless C64 using WASM: ${wasmPath}` + (gamePath ? ` game: ${gamePath}` : ''),
458
+ );
372
459
 
373
460
  const wasmBinary = await fs.readFile(wasmPath);
374
461
  // 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
462
+ let exports = null;
463
+ let heap = null;
464
+ let c64wasm = null; // ← hoisted: needed by onCommand for allocAndWrite
465
+ let C64WASMClass = null;
378
466
  let wrapperUsed = false;
379
467
  // SID audio constants — hoisted so the SID-cache block and the frame loop
380
468
  // both see them regardless of declaration order.
@@ -390,8 +478,8 @@ export async function runHeadless(options = {}) {
390
478
  );
391
479
  if (typeof instantiateFn === 'function') {
392
480
  try {
393
- const mem = new WebAssembly.Memory({initial: 256});
394
- const importObject = {env: {memory: mem}, wasi_snapshot_preview1: {}};
481
+ const mem = new WebAssembly.Memory({ initial: 256 });
482
+ const importObject = { env: { memory: mem }, wasi_snapshot_preview1: {} };
395
483
  const res = await instantiateFn(wasmAb, importObject);
396
484
  const inst = res && (res.instance ?? res);
397
485
  exports = inst.exports ?? inst;
@@ -399,11 +487,17 @@ export async function runHeadless(options = {}) {
399
487
  if (exports && !exports.memory) exports.memory = mem;
400
488
  if (exports && exports.memory) {
401
489
  const buf = exports.memory.buffer;
402
- heap = {heapU8: new Uint8Array(buf), heapF32: new Float32Array(buf), heapU32: new Uint32Array(buf)};
490
+ heap = {
491
+ heapU8: new Uint8Array(buf),
492
+ heapF32: new Float32Array(buf),
493
+ heapU32: new Uint32Array(buf),
494
+ };
403
495
  }
404
496
  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);
497
+ if (exports && typeof exports.sid_setSampleRate === 'function')
498
+ exports.sid_setSampleRate(44100);
499
+ if (exports && typeof exports.debugger_set_speed === 'function')
500
+ exports.debugger_set_speed(100);
407
501
  if (exports && typeof exports.debugger_play === 'function') exports.debugger_play();
408
502
  wrapperUsed = true;
409
503
  } catch (e) {
@@ -437,12 +531,13 @@ export async function runHeadless(options = {}) {
437
531
  }
438
532
 
439
533
  if (!C64WASM) throw new Error('C64WASM wrapper not found (src/headless or dist-ts)');
534
+ C64WASMClass = C64WASM;
440
535
 
441
536
  const wasmAb = wasmBinary.buffer.slice(
442
537
  wasmBinary.byteOffset,
443
538
  wasmBinary.byteOffset + wasmBinary.byteLength,
444
539
  );
445
- c64wasm = new C64WASM(); // assigns to outer let
540
+ c64wasm = new C64WASM(); // assigns to outer let
446
541
  await c64wasm.instantiate(wasmAb);
447
542
 
448
543
  exports = c64wasm.exports;
@@ -457,9 +552,15 @@ export async function runHeadless(options = {}) {
457
552
  if (gamePath) {
458
553
  try {
459
554
  const gameData = await fs.readFile(gamePath);
460
- const gameArr = new Uint8Array(gameData);
555
+ const gameArr = new Uint8Array(gameData);
461
556
  const cartInfo = parseCrtInfo(gameArr, path.basename(gamePath));
462
- if (cartInfo) console.error(cartInfo.line);
557
+ if (cartInfo) {
558
+ console.error(cartInfo.line);
559
+ const unsupportedReason = getUnsupportedCrtReason(cartInfo);
560
+ if (unsupportedReason) {
561
+ throw new Error(unsupportedReason);
562
+ }
563
+ }
463
564
  const ptr = c64wasm.allocAndWrite(gameArr);
464
565
  c64wasm.updateHeapViews();
465
566
  heap = c64wasm.heap;
@@ -479,11 +580,12 @@ export async function runHeadless(options = {}) {
479
580
  }
480
581
  if (!wrapperUsed) {
481
582
  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};
583
+ console.error(
584
+ '[headless] FATAL: dist-ts wrapper unavailable. Run: npx tsc -p tsconfig.build2.json',
585
+ );
586
+ return { ok: false, output: out };
484
587
  }
485
588
 
486
-
487
589
  // ── Input server (WebSocket) ──────────────────────────────────────────────
488
590
  // Start the embedded WebSocket input server when --input is passed.
489
591
  // Remote clients connect and send JSON InputEvent messages which are
@@ -503,11 +605,12 @@ export async function runHeadless(options = {}) {
503
605
  const kickTokenUrl = new URL(kickTokenRelPath, import.meta.url).href;
504
606
  const kickTokens = await import(kickTokenUrl);
505
607
  validateKickToken = kickTokens.validateKickToken;
506
- } catch { /* standalone mode — admin kick not available */ }
608
+ } catch {
609
+ /* standalone mode — admin kick not available */
610
+ }
507
611
 
508
612
  const dirMap = { up: 0x1, down: 0x2, left: 0x4, right: 0x8 };
509
613
 
510
-
511
614
  /** Flush all SID ring state after any emulator reset/cart-change.
512
615
  * The WASM SID resets its internal write cursor on c64_reset(), so any
513
616
  * samples still in the JS ring are from the old game and must be discarded.
@@ -520,9 +623,9 @@ export async function runHeadless(options = {}) {
520
623
  * game's own startup sound sequence. */
521
624
  function resetSidRing() {
522
625
  sidSampleAccum = 0;
523
- sidRingWrite = 0;
524
- sidRingRead = 0;
525
- sidRingCount = 0;
626
+ sidRingWrite = 0;
627
+ sidRingRead = 0;
628
+ sidRingCount = 0;
526
629
  sidFrameBufMax.fill(0);
527
630
  sidFrameView = sidFrameBufMax.subarray(0, 1);
528
631
  }
@@ -543,148 +646,190 @@ export async function runHeadless(options = {}) {
543
646
  getWebrtcPeerSnapshot: () => getWebrtcPeerSnapshot(),
544
647
  disconnectWebrtcPeersByAddr: (addr, reason) => disconnectWebrtcPeersByAddr(addr, reason),
545
648
  disconnectAllWebrtcPeers: (reason) => disconnectAllWebrtcPeers(reason),
546
- onCommand: (cmd) => {
649
+ onCommand: async (cmd) => {
547
650
  if (!exports) return;
548
651
  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 () => {
652
+ const requestedType =
653
+ cmd.type === 'load-crt' ? 'crt' : (cmd.fileType ?? inferLoadType(cmd.filename));
654
+ // Decode base64 → Uint8Array immediately and release the large
655
+ // base64 string from the cmd object as soon as possible so GC
656
+ // can reclaim it during the subsequent async gap.
657
+ const buf = Buffer.from(cmd.data, 'base64');
658
+ // Slice to own ArrayBuffer — avoids aliasing Node's pooled Buffer
659
+ // which could span a much larger backing store than the data alone.
660
+ const arr = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength).slice();
661
+ cmd.data = null; // release base64 string early
662
+ const byteLen = arr.length;
663
+ const filename = cmd.filename;
664
+ // Defer the blocking WASM work (malloc + copy + cartridge parse)
665
+ // via setImmediate so the event loop can drain any pending frame
666
+ // writes / setTimeout callbacks before the synchronous WASM work
667
+ // begins. This prevents the frame loop from stalling mid-write.
668
+ // Return a Promise so input-server waits before broadcasting
669
+ // cart-loaded — ensuring clients are told only after load succeeds.
670
+ return new Promise((resolve, reject) => {
671
+ setImmediate(async () => {
672
+ try {
673
+ const gapStart = Date.now();
674
+ const loadType = requestedType;
675
+ // For cartridge loads, reset first so bank state does not leak.
676
+ if (loadType === 'crt') {
677
+ exports.c64_removeCartridge();
678
+ exports.c64_reset();
679
+ }
680
+ const ptr = c64wasm.allocAndWrite(arr);
681
+ c64wasm.updateHeapViews();
682
+ heap = c64wasm.heap;
568
683
  try {
569
- const gapStart = Date.now();
570
- const loadType = requestedType;
571
- // For cartridge loads, reset first so bank state does not leak.
572
684
  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_removeCartridge();
589
- exports.c64_reset();
590
- exports.c64_setDriveEnabled(1);
591
- exports.c64_insertDisk(ptr, byteLen);
592
- } else if (loadType === 'snapshot') {
593
- exports.c64_loadSnapshot(ptr, byteLen);
594
- } else {
595
- throw new Error(`Unsupported load-file type: ${loadType}`);
685
+ const cartInfo = parseCrtInfo(arr, filename);
686
+ if (cartInfo) {
687
+ console.error(cartInfo.line);
688
+ const unsupportedReason = getUnsupportedCrtReason(cartInfo);
689
+ if (unsupportedReason) {
690
+ throw new Error(unsupportedReason);
691
+ }
596
692
  }
597
- } finally {
598
- c64wasm.free(ptr);
693
+ exports.c64_loadCartridge(ptr, byteLen);
694
+ } else if (loadType === 'prg') {
695
+ exports.c64_loadPRG(ptr, byteLen, 1);
696
+ await typeCommandText(exports, 'run\n');
697
+ } else if (loadType === 'd64') {
698
+ exports.c64_setDriveEnabled(1);
699
+ exports.c64_insertDisk(ptr, byteLen);
700
+ } else if (loadType === 'snapshot') {
701
+ exports.c64_loadSnapshot(ptr, byteLen);
702
+ } else {
703
+ throw new Error(`Unsupported load-file type: ${loadType}`);
599
704
  }
600
- const gapMs = Date.now() - gapStart;
601
- //
602
- // ── Audio RTP re-sync after blocking gap ─────────────────────
603
- // c64_loadCartridge blocks the event loop for ~1300ms. During
604
- // this time the frame loop is frozen so no audio is pushed to
605
- // RTCAudioSource. The video RTP clock (driven by @roamhq/wrtc
606
- // internally via wall-clock) keeps ticking, but the audio RTP
607
- // clock only advances when onData() is called — so audio falls
608
- // ~1300ms behind video. The browser's AV sync logic then holds
609
- // video playback until audio catches up, manifesting as input lag.
610
- //
611
- // Fix: push silence frames totalling the measured gap duration so
612
- // the audio RTP clock jumps forward by the same amount the video
613
- // RTP clock advanced during the blockage.
614
- resetSidRing();
615
- if (webrtcEncoder) {
616
- webrtcEncoder.pushSilenceForGap(gapMs);
617
- if (verbose) console.error(`[headless] pushed ${gapMs}ms silence to re-align audio RTP after cart load`);
618
- }
619
- if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
620
- if (verbose) console.error(`[headless] file loaded: ${filename} (${loadType}, ${byteLen} bytes, gap=${gapMs}ms)`);
621
- else if (logEvents) console.error(`[event] cart-loaded filename=${filename} type=${loadType} bytes=${byteLen} gap=${gapMs}ms`);
622
- resolve();
623
- } catch (err) {
624
- if (verbose) console.error('[headless] cart load (deferred) error:', err);
625
- else if (logEvents) console.error(`[event] error cart-load-failed filename=${filename} err=${err && err.message ? err.message : err}`);
626
- reject(err);
705
+ } finally {
706
+ c64wasm.free(ptr);
707
+ }
708
+ const gapMs = Date.now() - gapStart;
709
+ //
710
+ // ── Audio RTP re-sync after blocking gap ─────────────────────
711
+ // c64_loadCartridge blocks the event loop for ~1300ms. During
712
+ // this time the frame loop is frozen so no audio is pushed to
713
+ // RTCAudioSource. The video RTP clock (driven by @roamhq/wrtc
714
+ // internally via wall-clock) keeps ticking, but the audio RTP
715
+ // clock only advances when onData() is called — so audio falls
716
+ // ~1300ms behind video. The browser's AV sync logic then holds
717
+ // video playback until audio catches up, manifesting as input lag.
718
+ //
719
+ // Fix: push silence frames totalling the measured gap duration so
720
+ // the audio RTP clock jumps forward by the same amount the video
721
+ // RTP clock advanced during the blockage.
722
+ resetSidRing();
723
+ if (webrtcEncoder) {
724
+ webrtcEncoder.pushSilenceForGap(gapMs);
725
+ if (verbose)
726
+ console.error(
727
+ `[headless] pushed ${gapMs}ms silence to re-align audio RTP after cart load`,
728
+ );
627
729
  }
628
- });
730
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
731
+ if (verbose)
732
+ console.error(
733
+ `[headless] file loaded: ${filename} (${loadType}, ${byteLen} bytes, gap=${gapMs}ms)`,
734
+ );
735
+ else if (logEvents)
736
+ console.error(
737
+ `[event] cart-loaded filename=${filename} type=${loadType} bytes=${byteLen} gap=${gapMs}ms`,
738
+ );
739
+ resolve();
740
+ } catch (err) {
741
+ if (verbose) console.error('[headless] cart load (deferred) error:', err);
742
+ else if (logEvents)
743
+ console.error(
744
+ `[event] error cart-load-failed filename=${filename} err=${err && err.message ? err.message : err}`,
745
+ );
746
+ reject(err);
747
+ }
629
748
  });
630
- } else if (cmd.type === 'detach-crt') {
631
- const gapStart = Date.now();
632
- exports.c64_removeCartridge();
633
- exports.c64_reset(); // return to clean BASIC prompt
634
- const gapMs = Date.now() - gapStart;
635
- resetSidRing();
636
- if (webrtcEncoder) {
637
- webrtcEncoder.pushSilenceForGap(gapMs);
638
- if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after detach`);
639
- }
640
- if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
641
- if (verbose) console.error('[headless] cart detached');
642
- else if (logEvents) console.error(`[event] cart-detached gap=${gapMs}ms`);
643
- } else if (cmd.type === 'hard-reset') {
644
- // Instant hard reset: reset machine state but keep current media
645
- // attached (cartridge/disk), matching offline player behavior.
646
- const gapStart = Date.now();
647
- exports.c64_reset();
648
- const gapMs = Date.now() - gapStart;
649
- resetSidRing();
650
- if (webrtcEncoder) {
651
- webrtcEncoder.pushSilenceForGap(gapMs);
652
- if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after hard reset`);
653
- }
654
- if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
655
- if (verbose) console.error('[headless] hard reset');
656
- else if (logEvents) console.error(`[event] hard-reset gap=${gapMs}ms`);
749
+ });
750
+ } else if (cmd.type === 'detach-crt') {
751
+ const gapStart = Date.now();
752
+ exports.c64_removeCartridge();
753
+ exports.c64_reset(); // return to clean BASIC prompt
754
+ const gapMs = Date.now() - gapStart;
755
+ resetSidRing();
756
+ if (webrtcEncoder) {
757
+ webrtcEncoder.pushSilenceForGap(gapMs);
758
+ if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after detach`);
657
759
  }
760
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
761
+ if (verbose) console.error('[headless] cart detached');
762
+ else if (logEvents) console.error(`[event] cart-detached gap=${gapMs}ms`);
763
+ } else if (cmd.type === 'hard-reset') {
764
+ // Instant hard reset: reset machine state but keep current media
765
+ // attached (cartridge/disk), matching offline player behavior.
766
+ const gapStart = Date.now();
767
+ exports.c64_reset();
768
+ const gapMs = Date.now() - gapStart;
769
+ resetSidRing();
770
+ if (webrtcEncoder) {
771
+ webrtcEncoder.pushSilenceForGap(gapMs);
772
+ if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after hard reset`);
773
+ }
774
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
775
+ if (verbose) console.error('[headless] hard reset');
776
+ else if (logEvents) console.error(`[event] hard-reset gap=${gapMs}ms`);
777
+ } else if (cmd.type === 'reboot') {
778
+ if (!C64WASMClass) throw new Error('C64WASM wrapper unavailable for reboot');
779
+ const gapStart = Date.now();
780
+ const next = new C64WASMClass();
781
+ await next.instantiate(wasmAb);
782
+ c64wasm = next;
783
+ exports = c64wasm.exports;
784
+ heap = c64wasm.heap;
785
+ exports.c64_init();
786
+ exports.sid_setSampleRate(44100);
787
+ exports.debugger_set_speed(100);
788
+ exports.debugger_play();
789
+ const gapMs = Date.now() - gapStart;
790
+ resetSidRing();
791
+ if (webrtcEncoder) {
792
+ webrtcEncoder.pushSilenceForGap(gapMs);
793
+ if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after reboot`);
794
+ }
795
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
796
+ if (verbose) console.error('[headless] emulator rebooted (fresh WASM instance)');
797
+ else if (logEvents) console.error(`[event] machine-rebooted gap=${gapMs}ms`);
798
+ }
658
799
  },
659
800
  onInput: (event) => {
660
801
  if (!exports) return;
661
802
  if (event.type === 'joystick') {
662
- const port = ((event.joystickPort ?? 2) - 1); // 1-based → 0-based
803
+ const port = (event.joystickPort ?? 2) - 1; // 1-based → 0-based
663
804
  const dir = event.direction ? (dirMap[event.direction] ?? 0) : 0;
664
- const fire = (event.fire || event.fire1) ? 0x10 : 0;
805
+ const fire = event.fire || event.fire1 ? 0x10 : 0;
665
806
  if (event.action === 'release') {
666
- if (dir) exports.c64_joystick_release(port, dir);
807
+ if (dir) exports.c64_joystick_release(port, dir);
667
808
  if (fire) exports.c64_joystick_release(port, fire);
668
809
  } else {
669
- if (dir) exports.c64_joystick_push(port, dir);
810
+ if (dir) exports.c64_joystick_push(port, dir);
670
811
  if (fire) exports.c64_joystick_push(port, fire);
671
812
  }
672
813
  if (verbose) {
673
814
  const role = event._role ?? 'unknown';
674
- console.error(`[event] input joystick role=${role} port=${event.joystickPort ?? 2} action=${event.action ?? 'press'} dir=${event.direction ?? '-'} fire=${!!(event.fire || event.fire1)}`);
815
+ console.error(
816
+ `[event] input joystick role=${role} port=${event.joystickPort ?? 2} action=${event.action ?? 'press'} dir=${event.direction ?? '-'} fire=${!!(event.fire || event.fire1)}`,
817
+ );
675
818
  }
676
819
  } else if (event.type === 'key') {
677
- const domKey = String(event.key ?? '');
820
+ const domKey = String(event.key ?? '');
678
821
  const shiftKey = !!event.shiftKey;
679
- const evType = event.action === 'up' ? 'keyup' : 'keydown';
680
- const c64acts = domKeyToC64Actions(domKey, shiftKey, evType);
822
+ const evType = event.action === 'up' ? 'keyup' : 'keydown';
823
+ const c64acts = domKeyToC64Actions(domKey, shiftKey, evType);
681
824
  for (const act of c64acts) {
682
825
  if (act.action === 'press') exports.keyboard_keyPressed(act.key);
683
- else exports.keyboard_keyReleased(act.key);
826
+ else exports.keyboard_keyReleased(act.key);
684
827
  }
685
828
  if (verbose && c64acts.length > 0) {
686
829
  const role = event._role ?? 'unknown';
687
- console.error(`[input] input key role=${role} ${evType} "${domKey}" → ${JSON.stringify(c64acts)}`);
830
+ console.error(
831
+ `[input] input key role=${role} ${evType} "${domKey}" → ${JSON.stringify(c64acts)}`,
832
+ );
688
833
  }
689
834
  }
690
835
  },
@@ -701,7 +846,7 @@ export async function runHeadless(options = {}) {
701
846
  // webrtcPort (default 9002). Each connecting browser gets its own
702
847
  // RTCPeerConnection fed by the shared encoder tracks.
703
848
  let webrtcEncoder = null;
704
- let webrtcServer = null;
849
+ let webrtcServer = null;
705
850
  let getWebrtcTelemetry = () => null;
706
851
  let getWebrtcPeerSnapshot = () => null;
707
852
  let disconnectWebrtcPeersByAddr = () => 0;
@@ -709,7 +854,7 @@ export async function runHeadless(options = {}) {
709
854
 
710
855
  if (webrtc) {
711
856
  try {
712
- const { WebRTCEncoder } = await import('./webrtc-encoder.mjs');
857
+ const { WebRTCEncoder } = await import('./webrtc-encoder.mjs');
713
858
  const { createWebRTCServer } = await import('./webrtc-server.mjs');
714
859
  const wrtcLib = (await import('@roamhq/wrtc')).default;
715
860
  const { MediaStream } = wrtcLib;
@@ -745,7 +890,10 @@ export async function runHeadless(options = {}) {
745
890
  for (const sender of senders) {
746
891
  if (sender.track && sender.track.kind === 'video') {
747
892
  const params = sender.getParameters();
748
- const maxBitrateBps = Math.max(100_000, Math.round(webrtcMaxBitrateKbpsSafe * 1000));
893
+ const maxBitrateBps = Math.max(
894
+ 100_000,
895
+ Math.round(webrtcMaxBitrateKbpsSafe * 1000),
896
+ );
749
897
  if (params.encodings && params.encodings.length > 0) {
750
898
  params.encodings[0].maxBitrate = maxBitrateBps;
751
899
  } else {
@@ -765,13 +913,16 @@ export async function runHeadless(options = {}) {
765
913
  getWebrtcPeerSnapshot = () => webrtcServer.getPeerSnapshot();
766
914
  }
767
915
  if (typeof webrtcServer.disconnectPeersByAddr === 'function') {
768
- disconnectWebrtcPeersByAddr = (addr, reason) => webrtcServer.disconnectPeersByAddr(addr, reason);
916
+ disconnectWebrtcPeersByAddr = (addr, reason) =>
917
+ webrtcServer.disconnectPeersByAddr(addr, reason);
769
918
  }
770
919
  if (typeof webrtcServer.disconnectAllPeers === 'function') {
771
920
  disconnectAllWebrtcPeers = (reason) => webrtcServer.disconnectAllPeers(reason);
772
921
  }
773
922
 
774
- out.push(`WebRTC player at http://0.0.0.0:${webrtcPort}/ (send cap: ${webrtcOutputFpsSafe > 0 ? `${webrtcOutputFpsSafe}fps` : 'off'})`);
923
+ out.push(
924
+ `WebRTC player at http://0.0.0.0:${webrtcPort}/ (send cap: ${webrtcOutputFpsSafe > 0 ? `${webrtcOutputFpsSafe}fps` : 'off'})`,
925
+ );
775
926
  } catch (e) {
776
927
  console.error('[headless] Failed to start WebRTC server:', e && e.message ? e.message : e);
777
928
  out.push(`webrtc-server-failed: ${String(e)}`);
@@ -782,9 +933,10 @@ export async function runHeadless(options = {}) {
782
933
  // Run state and timing
783
934
  let frameCount = 0;
784
935
  let ffmpegDied = false; // set to true if ffmpeg exits unexpectedly and we give up
785
- const targetFps = (typeof fps === 'number' && !Number.isNaN(fps) && fps > 0) ? fps : 60;
936
+ const targetFps = typeof fps === 'number' && !Number.isNaN(fps) && fps > 0 ? fps : 60;
786
937
  const frameMs = Math.round(1000 / targetFps);
787
- const webrtcSendFps = webrtcOutputFpsSafe > 0 ? Math.max(1, Math.min(targetFps, webrtcOutputFpsSafe)) : targetFps;
938
+ const webrtcSendFps =
939
+ webrtcOutputFpsSafe > 0 ? Math.max(1, Math.min(targetFps, webrtcOutputFpsSafe)) : targetFps;
788
940
  const webrtcSendIntervalMs = 1000 / webrtcSendFps;
789
941
  let nextVideoDueAtMs = nowMonoMs();
790
942
  let videoFramesSent = 0;
@@ -808,7 +960,10 @@ export async function runHeadless(options = {}) {
808
960
  const EVENT_LOOP_LOG_MS = 5000;
809
961
  eventLoopLogTimer = setInterval(() => {
810
962
  const lag = eventLoopMonitor ? eventLoopMonitor.min / 1e6 : 0; // ms
811
- if (lag > 5 && (logEvents || verbose)) { // only log if >5ms lag
963
+ // Keep event-loop lag diagnostics behind --verbose only. These can be
964
+ // noisy in steady-state and are intended for performance debugging.
965
+ if (lag > 5 && verbose) {
966
+ // only log if >5ms lag
812
967
  console.error(`[event] event-loop-lag min=${lag.toFixed(2)}ms`);
813
968
  }
814
969
  if (eventLoopMonitor) eventLoopMonitor.reset();
@@ -842,24 +997,24 @@ export async function runHeadless(options = {}) {
842
997
  //
843
998
  // Ring sizing: hold at least 2× SID_BUFFER_SIZE so one full WASM pull
844
999
  // 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
1000
+ const SID_RING_SIZE = SID_BUFFER_SIZE * 4; // 16384 samples of headroom
1001
+ const sidRing = new Float32Array(SID_RING_SIZE);
1002
+ let sidRingWrite = 0; // next write position in sidRing
1003
+ let sidRingRead = 0; // next read position in sidRing
1004
+ let sidRingCount = 0; // samples currently in the ring
850
1005
  // Accumulator: how many emulated samples have passed since last WASM pull.
851
- let sidSampleAccum = 0;
1006
+ let sidSampleAccum = 0;
852
1007
  // Single staging buffer for per-frame audio delivered to ffmpeg/WebRTC.
853
1008
  const sidFrameBufMax = new Float32Array(MAX_AUDIO_SAMPLES_PER_ITER);
854
- let sidFrameView = sidFrameBufMax.subarray(0, 1);
1009
+ let sidFrameView = sidFrameBufMax.subarray(0, 1);
855
1010
 
856
1011
  /** Pull one 4096-sample chunk from the WASM SID buffer into the JS ring. */
857
1012
  function pullSidBuffer() {
858
1013
  if (!exports || !heap || typeof exports.sid_getAudioBuffer !== 'function') return;
859
1014
  try {
860
- const ptr = exports.sid_getAudioBuffer();
861
- const base = ptr >> 2;
862
- const src = heap.heapF32;
1015
+ const ptr = exports.sid_getAudioBuffer();
1016
+ const base = ptr >> 2;
1017
+ const src = heap.heapF32;
863
1018
  for (let i = 0; i < SID_BUFFER_SIZE; i++) {
864
1019
  sidRing[(sidRingWrite + i) % SID_RING_SIZE] = src[base + i];
865
1020
  }
@@ -897,18 +1052,19 @@ export async function runHeadless(options = {}) {
897
1052
  for (let i = 0; i < samplesNeeded; i++) {
898
1053
  sidFrameBufMax[i] = sidRing[(sidRingRead + i) % SID_RING_SIZE];
899
1054
  }
900
- sidRingRead = (sidRingRead + samplesNeeded) % SID_RING_SIZE;
1055
+ sidRingRead = (sidRingRead + samplesNeeded) % SID_RING_SIZE;
901
1056
  sidRingCount -= samplesNeeded;
902
1057
  return true;
903
1058
  }
904
1059
 
905
-
906
1060
  // Resolve output path once — treat remote URLs verbatim, local file paths
907
1061
  // should be resolved relative to the current working directory (process.cwd()).
908
1062
  // If no output provided, fall back to repoRoot/temp as before.
909
1063
  const isRemoteUrl = (s) => /^[a-zA-Z]+:\/\//.test(s);
910
1064
  const outPathResolved = output
911
- ? (isRemoteUrl(output) ? output : path.resolve(process.cwd(), output))
1065
+ ? isRemoteUrl(output)
1066
+ ? output
1067
+ : path.resolve(process.cwd(), output)
912
1068
  : path.join(repoRoot, 'temp', `c64-record-${Date.now()}.mp4`);
913
1069
  const isRtmpOutput = isRemoteUrl(outPathResolved);
914
1070
 
@@ -928,7 +1084,7 @@ export async function runHeadless(options = {}) {
928
1084
  raw,
929
1085
  verbose,
930
1086
  audio,
931
- sampleRate: audioSampleRate
1087
+ sampleRate: audioSampleRate,
932
1088
  });
933
1089
  return started;
934
1090
  }
@@ -940,7 +1096,7 @@ export async function runHeadless(options = {}) {
940
1096
  const msg = 'ffmpeg-record-failed:start-failed';
941
1097
  out.push(msg);
942
1098
  console.error('[headless] ' + msg);
943
- return {ok: false, output: out};
1099
+ return { ok: false, output: out };
944
1100
  } else {
945
1101
  const msg = `Recording to ${outPathResolved} (${durationSec ? durationSec + 's' : 'endless'} @ ${fps}fps${audio ? ' +audio' : ''})`;
946
1102
  out.push(msg);
@@ -975,7 +1131,9 @@ export async function runHeadless(options = {}) {
975
1131
  const runStartTime = Date.now();
976
1132
  const isStreamingMode = record || webrtc;
977
1133
  const endTime = isStreamingMode
978
- ? (durationSec ? runStartTime + durationSec * 1000 : Infinity)
1134
+ ? durationSec
1135
+ ? runStartTime + durationSec * 1000
1136
+ : Infinity
979
1137
  : null;
980
1138
 
981
1139
  let windowStart = nowMonoMs();
@@ -984,7 +1142,8 @@ export async function runHeadless(options = {}) {
984
1142
 
985
1143
  while (isStreamingMode ? Date.now() < endTime : frameCount < frames) {
986
1144
  try {
987
- if (verbose && frameCount % 50 === 0) console.error(`[headless] loop frameCount=${frameCount}`);
1145
+ if (verbose && frameCount % 50 === 0)
1146
+ console.error(`[headless] loop frameCount=${frameCount}`);
988
1147
 
989
1148
  // Capture frame start time BEFORE emulation so sleepMs accounts for
990
1149
  // ALL work in this iteration (emulation + audio + video push + ffmpeg).
@@ -1002,7 +1161,7 @@ export async function runHeadless(options = {}) {
1002
1161
  // AND debugger_isRunning() — we mirror that here so we never push a stale
1003
1162
  // or repeated pixel buffer into WebRTC during boot/reset sequences.
1004
1163
  const frameReady = !!exports.debugger_update(emuDeltaMs);
1005
- const isRunning = !!exports.debugger_isRunning();
1164
+ const isRunning = !!exports.debugger_isRunning();
1006
1165
 
1007
1166
  // ── Audio: pull from WASM SID → JS ring → per-frame slice ───────────
1008
1167
  // Audio runs every frame regardless of frameReady/isRunning so the WebRTC
@@ -1034,7 +1193,7 @@ export async function runHeadless(options = {}) {
1034
1193
  videoFramesDroppedLateWindow += lateDrops;
1035
1194
  nextVideoDueAtMs += lateDrops * webrtcSendIntervalMs;
1036
1195
  }
1037
- const ptr = exports.c64_getPixelBuffer();
1196
+ const ptr = exports.c64_getPixelBuffer();
1038
1197
  const rgba = heap.heapU8.subarray(ptr, ptr + 384 * 272 * 4);
1039
1198
  webrtcEncoder.pushVideoFrame(rgba);
1040
1199
  videoFramesSent++;
@@ -1111,8 +1270,7 @@ export async function runHeadless(options = {}) {
1111
1270
  const sleepMs = Math.max(0, frameMs - workMs);
1112
1271
  if (sleepMs > 0) await new Promise((r) => setTimeout(r, sleepMs));
1113
1272
  await new Promise((r) => setImmediate(r)); // drain any remaining I/O callbacks
1114
- } catch (_) {
1115
- }
1273
+ } catch (_) {}
1116
1274
  frameCount++;
1117
1275
  // diagnostics
1118
1276
  windowCount++;
@@ -1128,10 +1286,15 @@ export async function runHeadless(options = {}) {
1128
1286
  const drift = actualFps - targetFps;
1129
1287
  const driftPct = Math.abs(drift / targetFps) * 100;
1130
1288
  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)}%)`);
1289
+ console.error(
1290
+ `[event] drift fps-actual=${actualFps.toFixed(1)} fps-target=${targetFps} drift=${drift > 0 ? '+' : ''}${drift.toFixed(1)} (${driftPct.toFixed(0)}%)`,
1291
+ );
1132
1292
  }
1133
- if (videoFramesDroppedLateWindow > 0 || videoFramesDroppedCapWindow > 0) {
1134
- console.error(`[event] webrtc-video-drop sent=${videoFramesSent} late=${videoFramesDroppedLateWindow} cap=${videoFramesDroppedCapWindow} totalLate=${videoFramesDroppedLate} totalCap=${videoFramesDroppedCap} fpsCap=${webrtcSendFps}`);
1293
+ // Keep per-window drop telemetry behind --verbose only.
1294
+ if (verbose && (videoFramesDroppedLateWindow > 0 || videoFramesDroppedCapWindow > 0)) {
1295
+ console.error(
1296
+ `[event] webrtc-video-drop sent=${videoFramesSent} late=${videoFramesDroppedLateWindow} cap=${videoFramesDroppedCapWindow} totalLate=${videoFramesDroppedLate} totalCap=${videoFramesDroppedCap} fpsCap=${webrtcSendFps}`,
1297
+ );
1135
1298
  }
1136
1299
  }
1137
1300
  runtimeStats.videoFramesSent = videoFramesSent;
@@ -1140,12 +1303,28 @@ export async function runHeadless(options = {}) {
1140
1303
  const webrtcTelemetry = getWebrtcTelemetry();
1141
1304
  if (webrtcTelemetry) {
1142
1305
  runtimeStats.webrtcPeerCount = webrtcTelemetry.peerCount ?? null;
1143
- runtimeStats.webrtcAvgRttMs = Number.isFinite(webrtcTelemetry.avgRttMs) ? webrtcTelemetry.avgRttMs : null;
1144
- runtimeStats.webrtcSendDelayMsPerPacket = Number.isFinite(webrtcTelemetry.sendDelayMsPerPacket) ? webrtcTelemetry.sendDelayMsPerPacket : null;
1145
- runtimeStats.webrtcEncodeMsPerFrame = Number.isFinite(webrtcTelemetry.encodeMsPerFrame) ? webrtcTelemetry.encodeMsPerFrame : null;
1146
- runtimeStats.webrtcFramesSentPerSec = Number.isFinite(webrtcTelemetry.framesSentPerSec) ? webrtcTelemetry.framesSentPerSec : null;
1147
- runtimeStats.webrtcFramesEncodedPerSec = Number.isFinite(webrtcTelemetry.framesEncodedPerSec) ? webrtcTelemetry.framesEncodedPerSec : null;
1148
- runtimeStats.webrtcBytesSentPerSec = Number.isFinite(webrtcTelemetry.bytesSentPerSec) ? webrtcTelemetry.bytesSentPerSec : null;
1306
+ runtimeStats.webrtcAvgRttMs = Number.isFinite(webrtcTelemetry.avgRttMs)
1307
+ ? webrtcTelemetry.avgRttMs
1308
+ : null;
1309
+ runtimeStats.webrtcSendDelayMsPerPacket = Number.isFinite(
1310
+ webrtcTelemetry.sendDelayMsPerPacket,
1311
+ )
1312
+ ? webrtcTelemetry.sendDelayMsPerPacket
1313
+ : null;
1314
+ runtimeStats.webrtcEncodeMsPerFrame = Number.isFinite(webrtcTelemetry.encodeMsPerFrame)
1315
+ ? webrtcTelemetry.encodeMsPerFrame
1316
+ : null;
1317
+ runtimeStats.webrtcFramesSentPerSec = Number.isFinite(webrtcTelemetry.framesSentPerSec)
1318
+ ? webrtcTelemetry.framesSentPerSec
1319
+ : null;
1320
+ runtimeStats.webrtcFramesEncodedPerSec = Number.isFinite(
1321
+ webrtcTelemetry.framesEncodedPerSec,
1322
+ )
1323
+ ? webrtcTelemetry.framesEncodedPerSec
1324
+ : null;
1325
+ runtimeStats.webrtcBytesSentPerSec = Number.isFinite(webrtcTelemetry.bytesSentPerSec)
1326
+ ? webrtcTelemetry.bytesSentPerSec
1327
+ : null;
1149
1328
  runtimeStats.webrtcQualityLimitation = webrtcTelemetry.qualityLimitation ?? null;
1150
1329
  }
1151
1330
  runtimeStats.sampledAt = Date.now();
@@ -1156,12 +1335,11 @@ export async function runHeadless(options = {}) {
1156
1335
  }
1157
1336
  if (verify && frameCount % 60 === 0) {
1158
1337
  const cycleCount = exports.c64_getCycleCount ? exports.c64_getCycleCount() : null;
1159
- out.push(JSON.stringify({pid: process.pid, frame: frameCount, cycles: cycleCount}));
1338
+ out.push(JSON.stringify({ pid: process.pid, frame: frameCount, cycles: cycleCount }));
1160
1339
  try {
1161
1340
  const pc = exports.c64_getPC ? exports.c64_getPC() : null;
1162
1341
  console.error(`[headless] verify: frame=${frameCount} pc=${pc} cycles=${cycleCount}`);
1163
- } catch (_) {
1164
- }
1342
+ } catch (_) {}
1165
1343
  }
1166
1344
  }
1167
1345
 
@@ -1218,7 +1396,7 @@ export async function runHeadless(options = {}) {
1218
1396
  out.push(`ffmpeg-stop-failed: ${String(e)}`);
1219
1397
  }
1220
1398
  }
1221
- return {ok: !ffmpegDied, output: out};
1399
+ return { ok: !ffmpegDied, output: out };
1222
1400
  }
1223
1401
 
1224
1402
  export default runHeadless;