c64-ready 0.6.2 → 0.11.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 (41) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +94 -22
  3. package/bin/admin.mjs +196 -0
  4. package/bin/headless.mjs +26 -3
  5. package/bin/serve.mjs +3 -0
  6. package/dist/assets/CHANGELOG-CPMeNyjb.js +261 -0
  7. package/dist/assets/index-CeQto0sd.js +499 -0
  8. package/dist/c64-ready/c64-ready.gif +0 -0
  9. package/dist/fonts/Commodore Angled v1.2.ttf +0 -0
  10. package/dist/fonts/Commodore Rounded v1.2.ttf +0 -0
  11. package/dist/fonts/Commodore-64-v6.3.TTF +0 -0
  12. package/dist/fonts/READ ME!.txt +127 -0
  13. package/dist/fonts/button-commodore-64-font.gif +0 -0
  14. package/dist/games/cartridges/bubble-bobble.crt +0 -0
  15. package/dist/games/cartridges/ghosts-n-goblins.crt +0 -0
  16. package/dist/games/snapshots/LVLLVL%BAAL.c64 +0 -0
  17. package/dist/games/snapshots/VICE2-4%APOLLO18.vsf +0 -0
  18. package/dist/games/snapshots/VICE3.10%ELEVATOR.vsf +0 -0
  19. package/dist/index.html +1 -1
  20. package/dist/tools/Keyboard-Test.prg +0 -0
  21. package/package.json +6 -2
  22. package/public/games/cartridges/bubble-bobble.crt +0 -0
  23. package/public/games/cartridges/ghosts-n-goblins.crt +0 -0
  24. package/src/emulator/c64-emulator.ts +10 -2
  25. package/src/emulator/crt-info.ts +210 -0
  26. package/src/emulator/input.ts +542 -7
  27. package/src/headless/c64-key-map.mjs +254 -0
  28. package/src/headless/c64-wasm.mjs +4 -1
  29. package/src/headless/headless-cli.mjs +832 -123
  30. package/src/headless/input-server.mjs +947 -14
  31. package/src/headless/webrtc-encoder.mjs +251 -0
  32. package/src/headless/webrtc-server.mjs +1327 -0
  33. package/src/main.ts +39 -7
  34. package/src/player/c64-player.ts +131 -14
  35. package/src/player/input-handler.ts +22 -6
  36. package/src/player/load-formats.ts +58 -0
  37. package/src/player/styles/ui-controller.css +69 -2
  38. package/src/player/ui-controller.ts +167 -36
  39. package/src/types/emulator.ts +2 -1
  40. package/dist/assets/CHANGELOG-C1nvP1iO.js +0 -96
  41. package/dist/assets/index-Cioamf6E.js +0 -394
@@ -1,7 +1,166 @@
1
1
  import fs from 'fs/promises';
2
+ import { readFileSync, mkdirSync, createWriteStream, readdirSync, statSync, unlinkSync } from 'fs';
2
3
  import path from 'path';
3
4
  import {fileURLToPath} from 'url';
5
+ import { execSync } from 'child_process';
4
6
  import FFmpegRunner from './ffmpeg-runner.mjs';
7
+ import { domKeyToC64Actions } from './c64-key-map.mjs';
8
+
9
+ const nowMonoMs = () => {
10
+ if (typeof globalThis.performance !== 'undefined' && typeof globalThis.performance.now === 'function') {
11
+ return globalThis.performance.now();
12
+ }
13
+ return Date.now();
14
+ };
15
+
16
+ // ── CRT info parser ───────────────────────────────────────────────────────────
17
+ // Inline JS port of src/emulator/crt-info.ts — kept here so headless-cli.mjs
18
+ // runs without a TypeScript build step.
19
+ //
20
+ // Reference: https://vice-emu.sourceforge.io/vice_17.html#SEC380
21
+ 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',
45
+ };
46
+ /**
47
+ * Parse a CRT file and return a human-readable summary line plus metadata.
48
+ * Returns null if the data is too short or the magic bytes are absent.
49
+ * @param {Uint8Array} data
50
+ * @param {string} [filename]
51
+ */
52
+ function parseCrtInfo(data, filename) {
53
+ if (!data || data.length < 0x40) return null;
54
+ // Validate "C64 CARTRIDGE" magic
55
+ let magic = '';
56
+ for (let i = 0; i < 16; i++) magic += String.fromCharCode(data[i]);
57
+ if (!magic.startsWith('C64 CARTRIDGE')) return null;
58
+
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];
63
+
64
+ let cartName = '';
65
+ for (let i = 0x20; i < 0x40 && data[i] !== 0; i++) cartName += String.fromCharCode(data[i]);
66
+ cartName = cartName.trim();
67
+
68
+ let bankConfig;
69
+ if (exrom === 0 && game === 0) bankConfig = '16K (ROML+ROMH)';
70
+ else if (exrom === 0 && game === 1) bankConfig = '8K (ROML only)';
71
+ else if (exrom === 1 && game === 0) bankConfig = 'Ultimax';
72
+ else bankConfig = 'inactive (pass-through)';
73
+
74
+ let chipCount = 0, totalRomBytes = 0;
75
+ let offset = Math.max(headerLen, 0x40);
76
+ while (offset + 16 <= data.length) {
77
+ let cm = '';
78
+ for (let i = 0; i < 4; i++) cm += String.fromCharCode(data[offset + i]);
79
+ if (cm !== 'CHIP') break;
80
+ const pktLen = ((data[offset+4]<<24)|(data[offset+5]<<16)|(data[offset+6]<<8)|data[offset+7])>>>0;
81
+ if (pktLen < 16) break;
82
+ const dataSize = ((data[offset+0x0E]<<8)|data[offset+0x0F])>>>0;
83
+ chipCount++;
84
+ totalRomBytes += dataSize;
85
+ offset += pktLen;
86
+ }
87
+
88
+ const hwName = _CRT_HW_TYPES[hwType] ?? `Unknown(${hwType})`;
89
+ const fileLabel = filename ? ` "${filename}"` : '';
90
+ const namePart = cartName ? ` name="${cartName}"` : '';
91
+ const kbActual = (totalRomBytes / 1024).toFixed(0);
92
+ const line =
93
+ `[C64 cart]${fileLabel} loading: hwType=${hwType}(${hwName})` +
94
+ ` | ${bankConfig} flags, ${kbActual}K actual` +
95
+ ` | ${chipCount} CHIP(s) | ${data.length} bytes${namePart}`;
96
+ return { line, hwType, hwName, exrom, game, bankConfig, cartName, chipCount, totalRomBytes };
97
+ }
98
+
99
+ function inferLoadType(filename = '') {
100
+ const lower = String(filename).toLowerCase();
101
+ if (lower.endsWith('.crt')) return 'crt';
102
+ if (lower.endsWith('.prg')) return 'prg';
103
+ if (lower.endsWith('.d64')) return 'd64';
104
+ if (lower.endsWith('.snapshot') || lower.endsWith('.c64') || lower.endsWith('.s64')) return 'snapshot';
105
+ return 'crt';
106
+ }
107
+
108
+ function sleepMs(ms) {
109
+ return new Promise((resolve) => setTimeout(resolve, ms));
110
+ }
111
+
112
+ async function typeCommandText(exports, text, opts = {}) {
113
+ if (!exports) return;
114
+ const settleMs = Number.isFinite(opts.settleMs) ? opts.settleMs : 120;
115
+ const keyDelayMs = Number.isFinite(opts.keyDelayMs) ? opts.keyDelayMs : 22;
116
+
117
+ if (settleMs > 0) await sleepMs(settleMs);
118
+
119
+ for (const ch of text) {
120
+ const key = ch === '\n' ? 'Enter' : ch;
121
+ const down = domKeyToC64Actions(key, false, 'keydown');
122
+ for (const act of down) {
123
+ if (act.action === 'press') exports.keyboard_keyPressed(act.key);
124
+ else exports.keyboard_keyReleased(act.key);
125
+ }
126
+ if (typeof exports.debugger_update === 'function') exports.debugger_update(12);
127
+ if (keyDelayMs > 0) await sleepMs(keyDelayMs);
128
+
129
+ const up = domKeyToC64Actions(key, false, 'keyup');
130
+ for (const act of up) {
131
+ if (act.action === 'press') exports.keyboard_keyPressed(act.key);
132
+ else exports.keyboard_keyReleased(act.key);
133
+ }
134
+ if (typeof exports.debugger_update === 'function') exports.debugger_update(12);
135
+ if (keyDelayMs > 0) await sleepMs(keyDelayMs);
136
+ }
137
+ }
138
+
139
+ // ── Build info ────────────────────────────────────────────────────────────────
140
+ // Read once at module load so every createInputServer call gets the same values.
141
+ const _repoRootForBuildInfo = path.resolve(new URL('../../', import.meta.url).pathname);
142
+ let _serverVersion = null;
143
+ let _serverGitHash = null;
144
+ try {
145
+ const pkg = JSON.parse(readFileSync(path.join(_repoRootForBuildInfo, 'package.json'), 'utf8'));
146
+ _serverVersion = pkg.version ?? null;
147
+ } catch { /* non-fatal */ }
148
+ try {
149
+ // Prefer the baked-in build-arg written by the Dockerfile (works in Docker
150
+ // where git is not installed and .git is not present).
151
+ // Fall back to execSync for local dev where the repo is available.
152
+ const hashFile = path.join(_repoRootForBuildInfo, '.git-hash');
153
+ if (process.env.GIT_HASH) {
154
+ _serverGitHash = process.env.GIT_HASH.trim() || null;
155
+ } else {
156
+ try {
157
+ _serverGitHash = readFileSync(hashFile, 'utf8').trim() || null;
158
+ } catch {
159
+ _serverGitHash = execSync('git rev-parse --short HEAD', { cwd: _repoRootForBuildInfo, stdio: ['ignore', 'pipe', 'ignore'] })
160
+ .toString().trim();
161
+ }
162
+ }
163
+ } catch { /* non-fatal — git may not be available in some deploy environments */ }
5
164
 
6
165
  /**
7
166
  * Run headless emulator. Exported so tests can inject a fake WebAssembly.instantiate.
@@ -21,13 +180,21 @@ export async function runHeadless(options = {}) {
21
180
  let verify = false;
22
181
  let record = false;
23
182
  let audio = false;
24
- // Use fixed timestep by default to keep emulation timing stable.
25
- let useFixedDt = true;
26
183
  let raw = false;
27
184
  let output = null;
28
185
  let durationSec = 0; // 0 means no --duration was passed → stream forever when recording
29
186
  let enableInput = false;
30
187
  let wsPort = 9001;
188
+ let webrtc = false;
189
+ let webrtcPort = 9002;
190
+ let logEvents = false;
191
+ let maxSpectators = 3;
192
+ let webrtcMinBitrateKbps = 200;
193
+ let webrtcMaxBitrateKbps = 600;
194
+ let webrtcOutputFps = 40;
195
+ let adminToken = process.env.C64_ADMIN_TOKEN ?? '';
196
+ let logFile = false;
197
+ let logRetainDays = 7;
31
198
  for (let i = 0; i < argv.length; i++) {
32
199
  const a = argv[i];
33
200
  if (a === '--wasm' || a === '-w') wasmArg = argv[++i];
@@ -41,15 +208,128 @@ export async function runHeadless(options = {}) {
41
208
  else if (a === '--duration' || a === '-d') durationSec = Number(argv[++i]);
42
209
  else if (a === '--no-game') noGame = true;
43
210
  else if (a === '--verbose') verbose = true;
211
+ else if (a === '--log-events') logEvents = true;
212
+ else if (a === '--log-file') logFile = true;
213
+ else if (a === '--log-retain-days') logRetainDays = Number(argv[++i]);
44
214
  else if (a === '--fps') fps = Number(argv[++i]);
45
- else if (a === '--use-fixed-dt') useFixedDt = true;
46
- else if (a === '--use-wall-clock') useFixedDt = false;
47
215
  else if (a === '--input') enableInput = true;
48
216
  else if (a === '--ws-port') wsPort = Number(argv[++i]);
217
+ else if (a === '--webrtc') webrtc = true;
218
+ else if (a === '--webrtc-port') webrtcPort = Number(argv[++i]);
219
+ else if (a === '--max-spectators') maxSpectators = Number(argv[++i]);
220
+ else if (a === '--webrtc-min-bitrate-kbps') webrtcMinBitrateKbps = Number(argv[++i]);
221
+ else if (a === '--webrtc-max-bitrate-kbps') webrtcMaxBitrateKbps = Number(argv[++i]);
222
+ else if (a === '--webrtc-output-fps') webrtcOutputFps = Number(argv[++i]);
223
+ else if (a === '--admin-token') adminToken = argv[++i] ?? '';
49
224
  else if (a === '--help' || a === '-h') {
50
225
  return {ok: false, output: 'help'};
51
226
  }
52
227
  }
228
+ const adminTokenSafe = String(adminToken ?? '').trim();
229
+
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;
239
+
240
+ const runtimeStats = {
241
+ webrtcSendFps: null,
242
+ videoFramesSent: 0,
243
+ videoFramesDroppedLate: 0,
244
+ videoFramesDroppedCap: 0,
245
+ webrtcPeerCount: null,
246
+ webrtcAvgRttMs: null,
247
+ webrtcSendDelayMsPerPacket: null,
248
+ webrtcEncodeMsPerFrame: null,
249
+ webrtcFramesSentPerSec: null,
250
+ webrtcFramesEncodedPerSec: null,
251
+ webrtcBytesSentPerSec: null,
252
+ webrtcQualityLimitation: null,
253
+ sampledAt: Date.now(),
254
+ };
255
+
256
+ // ── Log file setup ────────────────────────────────────────────────────────────
257
+ let logStream = null;
258
+ let _origConsoleLog = null;
259
+ let _origConsoleError = null;
260
+
261
+ function _setupLogFile() {
262
+ if (!logFile) return;
263
+
264
+ const logsDir = path.join(repoRoot, 'logs');
265
+ try {
266
+ mkdirSync(logsDir, { recursive: true });
267
+ } catch (e) {
268
+ console.error('[headless] could not create logs directory:', e.message);
269
+ return;
270
+ }
271
+
272
+ // Clean up old logs
273
+ if (logRetainDays > 0) {
274
+ try {
275
+ const files = readdirSync(logsDir);
276
+ const now = Date.now();
277
+ for (const f of files) {
278
+ if (!f.startsWith('headless-') || !f.endsWith('.log')) continue;
279
+ const fpath = path.join(logsDir, f);
280
+ const stat = statSync(fpath);
281
+ const ageDays = (now - stat.mtimeMs) / (1000 * 60 * 60 * 24);
282
+ if (ageDays > logRetainDays) {
283
+ unlinkSync(fpath);
284
+ console.error(`[headless] purged old log: ${f} (${ageDays.toFixed(1)} days old)`);
285
+ }
286
+ }
287
+ } catch (e) {
288
+ console.error('[headless] log cleanup error:', e.message);
289
+ }
290
+ }
291
+
292
+ // Generate filename
293
+ const timestamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
294
+ const logPath = path.join(logsDir, `headless-${timestamp}.log`);
295
+ try {
296
+ logStream = createWriteStream(logPath, { flags: 'a' });
297
+ console.error(`[headless] logging to: ${logPath}`);
298
+ } catch (e) {
299
+ console.error('[headless] could not open log file:', e.message);
300
+ return;
301
+ }
302
+
303
+ // Tee console methods
304
+ _origConsoleLog = console.log;
305
+ _origConsoleError = console.error;
306
+
307
+ const _writeLog = (origFn, ...args) => {
308
+ origFn.apply(console, args);
309
+ if (logStream && logStream.writable) {
310
+ const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ') + '\n';
311
+ logStream.write(line);
312
+ }
313
+ };
314
+
315
+ console.log = (...args) => _writeLog(_origConsoleLog, ...args);
316
+ console.error = (...args) => _writeLog(_origConsoleError, ...args);
317
+ }
318
+
319
+ function _teardownLogFile() {
320
+ if (logStream) {
321
+ try { logStream.end(); } catch (_) {}
322
+ logStream = null;
323
+ }
324
+ if (_origConsoleLog) {
325
+ console.log = _origConsoleLog;
326
+ console.error = _origConsoleError;
327
+ _origConsoleLog = null;
328
+ _origConsoleError = null;
329
+ }
330
+ }
331
+
332
+ _setupLogFile();
53
333
 
54
334
  const defaultWasmPaths = [
55
335
  path.join(repoRoot, 'public', 'c64.wasm'),
@@ -91,10 +371,14 @@ export async function runHeadless(options = {}) {
91
371
  out.push(`Starting headless C64 using WASM: ${wasmPath}` + (gamePath ? ` game: ${gamePath}` : ''));
92
372
 
93
373
  const wasmBinary = await fs.readFile(wasmPath);
94
- // runtime state placeholders
95
- let exports = null;
96
- let heap = null;
374
+ // 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
97
378
  let wrapperUsed = false;
379
+ // SID audio constants — hoisted so the SID-cache block and the frame loop
380
+ // both see them regardless of declaration order.
381
+ const SID_BUFFER_SIZE = 4096;
98
382
 
99
383
  // If a test injected a fake instantiate function, prefer that path so
100
384
  // tests can run without the compiled wrapper. Provide a minimal import
@@ -158,7 +442,7 @@ export async function runHeadless(options = {}) {
158
442
  wasmBinary.byteOffset,
159
443
  wasmBinary.byteOffset + wasmBinary.byteLength,
160
444
  );
161
- const c64wasm = new C64WASM();
445
+ c64wasm = new C64WASM(); // assigns to outer let
162
446
  await c64wasm.instantiate(wasmAb);
163
447
 
164
448
  exports = c64wasm.exports;
@@ -173,13 +457,17 @@ export async function runHeadless(options = {}) {
173
457
  if (gamePath) {
174
458
  try {
175
459
  const gameData = await fs.readFile(gamePath);
176
- const ptr = c64wasm.allocAndWrite(new Uint8Array(gameData));
460
+ const gameArr = new Uint8Array(gameData);
461
+ const cartInfo = parseCrtInfo(gameArr, path.basename(gamePath));
462
+ if (cartInfo) console.error(cartInfo.line);
463
+ const ptr = c64wasm.allocAndWrite(gameArr);
177
464
  c64wasm.updateHeapViews();
178
465
  heap = c64wasm.heap;
179
466
  exports.c64_loadCartridge(ptr, gameData.length);
180
- exports.free(ptr);
181
- exports.c64_reset();
182
- exports.debugger_play();
467
+ // free(ptr), c64_reset, debugger_set_speed, debugger_play intentionally
468
+ // omitted: c64_loadCartridge already resets and resumes the machine
469
+ // internally. Calling them re-triggers the ROM boot sequence — the same
470
+ // root cause of post-load input lag fixed for the load-crt command path.
183
471
  } catch (e) {
184
472
  out.push(`Failed to load game: ${String(e)}`);
185
473
  }
@@ -195,6 +483,7 @@ export async function runHeadless(options = {}) {
195
483
  return {ok: false, output: out};
196
484
  }
197
485
 
486
+
198
487
  // ── Input server (WebSocket) ──────────────────────────────────────────────
199
488
  // Start the embedded WebSocket input server when --input is passed.
200
489
  // Remote clients connect and send JSON InputEvent messages which are
@@ -203,39 +492,200 @@ export async function runHeadless(options = {}) {
203
492
  if (enableInput) {
204
493
  try {
205
494
  const { createInputServer } = await import('./input-server.mjs');
495
+ // Try to import the kick-token validator from the co-located c64cade server.
496
+ // If it's not present (standalone c64-ready usage) fall back to no-op.
497
+ // NOTE: The import path is computed at runtime (not a string literal) so
498
+ // Vite/Vitest does NOT attempt to resolve/bundle it at transform time —
499
+ // dynamic import of a non-literal string is left to the JS engine.
500
+ let validateKickToken = () => null;
501
+ try {
502
+ const kickTokenRelPath = '../../c64cade/packages/server/utils/kick-tokens.js';
503
+ const kickTokenUrl = new URL(kickTokenRelPath, import.meta.url).href;
504
+ const kickTokens = await import(kickTokenUrl);
505
+ validateKickToken = kickTokens.validateKickToken;
506
+ } catch { /* standalone mode — admin kick not available */ }
507
+
206
508
  const dirMap = { up: 0x1, down: 0x2, left: 0x4, right: 0x8 };
509
+
510
+
511
+ /** Flush all SID ring state after any emulator reset/cart-change.
512
+ * The WASM SID resets its internal write cursor on c64_reset(), so any
513
+ * samples still in the JS ring are from the old game and must be discarded.
514
+ * sidSampleAccum is also zeroed so the next pull aligns with the freshly
515
+ * restarted SID write cursor rather than inheriting stale offset.
516
+ * Note: we do NOT call primeSidRing() here — that would run 186ms of
517
+ * synchronous debugger_update inside the load-crt setImmediate callback
518
+ * and add unwanted post-load blockage. The ring re-fills naturally within
519
+ * ~5 frames; those frames output silence which is inaudible during the
520
+ * game's own startup sound sequence. */
521
+ function resetSidRing() {
522
+ sidSampleAccum = 0;
523
+ sidRingWrite = 0;
524
+ sidRingRead = 0;
525
+ sidRingCount = 0;
526
+ sidFrameBufMax.fill(0);
527
+ sidFrameView = sidFrameBufMax.subarray(0, 1);
528
+ }
529
+
207
530
  inputServer = createInputServer({
208
531
  port: wsPort,
209
532
  verbose,
210
- onInput: (event) => {
533
+ logEvents,
534
+ validateKickToken,
535
+ validateAdminToken: (token) => {
536
+ if (!adminTokenSafe) return false;
537
+ return token === adminTokenSafe;
538
+ },
539
+ initialCartFilename: gamePath ? path.basename(gamePath) : null,
540
+ serverVersion: _serverVersion,
541
+ serverGitHash: _serverGitHash,
542
+ getRuntimeStats: () => ({ ...runtimeStats }),
543
+ getWebrtcPeerSnapshot: () => getWebrtcPeerSnapshot(),
544
+ disconnectWebrtcPeersByAddr: (addr, reason) => disconnectWebrtcPeersByAddr(addr, reason),
545
+ disconnectAllWebrtcPeers: (reason) => disconnectAllWebrtcPeers(reason),
546
+ onCommand: (cmd) => {
211
547
  if (!exports) return;
212
- try {
213
- if (event.type === 'joystick') {
214
- const port = ((event.joystickPort ?? 2) - 1); // 1-based → 0-based
215
- const dir = event.direction ? (dirMap[event.direction] ?? 0) : 0;
216
- const fire = (event.fire || event.fire1) ? 0x10 : 0;
217
-
218
- if (event.action === 'release') {
219
- if (dir) exports.c64_joystick_release(port, dir);
220
- if (fire) exports.c64_joystick_release(port, fire);
221
- } else {
222
- // Default to push for backwards compat (action missing)
223
- if (dir) exports.c64_joystick_push(port, dir);
224
- if (fire) exports.c64_joystick_push(port, fire);
548
+ 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 () => {
568
+ try {
569
+ const gapStart = Date.now();
570
+ const loadType = requestedType;
571
+ // For cartridge loads, reset first so bank state does not leak.
572
+ 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}`);
596
+ }
597
+ } finally {
598
+ c64wasm.free(ptr);
599
+ }
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);
627
+ }
628
+ });
629
+ });
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`);
225
639
  }
226
- } else if (event.type === 'key') {
227
- const keyCode = Number(event.key);
228
- if (!Number.isNaN(keyCode)) {
229
- if (event.action === 'up') {
230
- exports.keyboard_keyReleased(keyCode);
231
- } else {
232
- // Default to keyPressed for backwards compat (action missing)
233
- exports.keyboard_keyPressed(keyCode);
234
- }
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`);
235
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`);
657
+ }
658
+ },
659
+ onInput: (event) => {
660
+ if (!exports) return;
661
+ if (event.type === 'joystick') {
662
+ const port = ((event.joystickPort ?? 2) - 1); // 1-based → 0-based
663
+ const dir = event.direction ? (dirMap[event.direction] ?? 0) : 0;
664
+ const fire = (event.fire || event.fire1) ? 0x10 : 0;
665
+ if (event.action === 'release') {
666
+ if (dir) exports.c64_joystick_release(port, dir);
667
+ if (fire) exports.c64_joystick_release(port, fire);
668
+ } else {
669
+ if (dir) exports.c64_joystick_push(port, dir);
670
+ if (fire) exports.c64_joystick_push(port, fire);
671
+ }
672
+ if (verbose) {
673
+ 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)}`);
675
+ }
676
+ } else if (event.type === 'key') {
677
+ const domKey = String(event.key ?? '');
678
+ const shiftKey = !!event.shiftKey;
679
+ const evType = event.action === 'up' ? 'keyup' : 'keydown';
680
+ const c64acts = domKeyToC64Actions(domKey, shiftKey, evType);
681
+ for (const act of c64acts) {
682
+ if (act.action === 'press') exports.keyboard_keyPressed(act.key);
683
+ else exports.keyboard_keyReleased(act.key);
684
+ }
685
+ if (verbose && c64acts.length > 0) {
686
+ const role = event._role ?? 'unknown';
687
+ console.error(`[input] input key role=${role} ${evType} "${domKey}" → ${JSON.stringify(c64acts)}`);
236
688
  }
237
- } catch (err) {
238
- if (verbose) console.error('[headless] input dispatch error:', err);
239
689
  }
240
690
  },
241
691
  });
@@ -246,27 +696,212 @@ export async function runHeadless(options = {}) {
246
696
  }
247
697
  }
248
698
 
699
+ // ── WebRTC server (low-latency streaming, replaces RTMP+flv.js) ─────────
700
+ // Started when --webrtc is passed. Opens an HTTP+WS signalling server on
701
+ // webrtcPort (default 9002). Each connecting browser gets its own
702
+ // RTCPeerConnection fed by the shared encoder tracks.
703
+ let webrtcEncoder = null;
704
+ let webrtcServer = null;
705
+ let getWebrtcTelemetry = () => null;
706
+ let getWebrtcPeerSnapshot = () => null;
707
+ let disconnectWebrtcPeersByAddr = () => 0;
708
+ let disconnectAllWebrtcPeers = () => 0;
709
+
710
+ if (webrtc) {
711
+ try {
712
+ const { WebRTCEncoder } = await import('./webrtc-encoder.mjs');
713
+ const { createWebRTCServer } = await import('./webrtc-server.mjs');
714
+ const wrtcLib = (await import('@roamhq/wrtc')).default;
715
+ const { MediaStream } = wrtcLib;
716
+
717
+ webrtcEncoder = new WebRTCEncoder();
718
+ webrtcEncoder.init({ width: 384, height: 272, sampleRate: 44100 });
719
+
720
+ const { videoTrack, audioTrack } = webrtcEncoder;
721
+
722
+ webrtcServer = createWebRTCServer({
723
+ port: webrtcPort,
724
+ verbose,
725
+ logEvents,
726
+ inputPort: wsPort,
727
+ maxSpectators,
728
+ minBitrateKbps: webrtcMinBitrateKbpsSafe,
729
+ maxBitrateKbps: webrtcMaxBitrateKbpsSafe,
730
+ // onOffer fires BEFORE createAnswer() — the right place to addTrack()
731
+ onOffer(pc) {
732
+ const stream = new MediaStream([videoTrack, audioTrack]);
733
+ pc.addTrack(videoTrack, stream);
734
+ pc.addTrack(audioTrack, stream);
735
+ if (verbose) console.error('[webrtc] tracks attached to peer');
736
+ },
737
+ onPeerConnected(pc) {
738
+ if (verbose) console.error('[webrtc] peer ICE connected');
739
+ // Reduce video sender bitrate after connection to minimise encode
740
+ // latency. A tight ceiling keeps frame sizes small and predictable,
741
+ // reducing the encoder's internal queue and decode buffer on the
742
+ // receiving end.
743
+ try {
744
+ const senders = pc.getSenders();
745
+ for (const sender of senders) {
746
+ if (sender.track && sender.track.kind === 'video') {
747
+ const params = sender.getParameters();
748
+ const maxBitrateBps = Math.max(100_000, Math.round(webrtcMaxBitrateKbpsSafe * 1000));
749
+ if (params.encodings && params.encodings.length > 0) {
750
+ params.encodings[0].maxBitrate = maxBitrateBps;
751
+ } else {
752
+ params.encodings = [{ maxBitrate: maxBitrateBps }];
753
+ }
754
+ sender.setParameters(params).catch(() => {});
755
+ break;
756
+ }
757
+ }
758
+ } catch (_) {}
759
+ },
760
+ });
761
+ if (typeof webrtcServer.getTelemetrySnapshot === 'function') {
762
+ getWebrtcTelemetry = () => webrtcServer.getTelemetrySnapshot();
763
+ }
764
+ if (typeof webrtcServer.getPeerSnapshot === 'function') {
765
+ getWebrtcPeerSnapshot = () => webrtcServer.getPeerSnapshot();
766
+ }
767
+ if (typeof webrtcServer.disconnectPeersByAddr === 'function') {
768
+ disconnectWebrtcPeersByAddr = (addr, reason) => webrtcServer.disconnectPeersByAddr(addr, reason);
769
+ }
770
+ if (typeof webrtcServer.disconnectAllPeers === 'function') {
771
+ disconnectAllWebrtcPeers = (reason) => webrtcServer.disconnectAllPeers(reason);
772
+ }
773
+
774
+ out.push(`WebRTC player at http://0.0.0.0:${webrtcPort}/ (send cap: ${webrtcOutputFpsSafe > 0 ? `${webrtcOutputFpsSafe}fps` : 'off'})`);
775
+ } catch (e) {
776
+ console.error('[headless] Failed to start WebRTC server:', e && e.message ? e.message : e);
777
+ out.push(`webrtc-server-failed: ${String(e)}`);
778
+ webrtc = false;
779
+ }
780
+ }
781
+
249
782
  // Run state and timing
250
783
  let frameCount = 0;
251
784
  let ffmpegDied = false; // set to true if ffmpeg exits unexpectedly and we give up
252
785
  const targetFps = (typeof fps === 'number' && !Number.isNaN(fps) && fps > 0) ? fps : 60;
786
+ const frameMs = Math.round(1000 / targetFps);
787
+ const webrtcSendFps = webrtcOutputFpsSafe > 0 ? Math.max(1, Math.min(targetFps, webrtcOutputFpsSafe)) : targetFps;
788
+ const webrtcSendIntervalMs = 1000 / webrtcSendFps;
789
+ let nextVideoDueAtMs = nowMonoMs();
790
+ let videoFramesSent = 0;
791
+ let videoFramesDroppedLate = 0;
792
+ let videoFramesDroppedCap = 0;
793
+ let videoFramesDroppedLateWindow = 0;
794
+ let videoFramesDroppedCapWindow = 0;
795
+ runtimeStats.webrtcSendFps = webrtcSendFps;
796
+ // Now that targetFps is known, configure the WebRTC encoder's frame duration
797
+ // so video timestamps are driven by frame count × frame duration (µs) rather
798
+ // than wall clock — making loadCartridge blockages invisible to the receiver.
799
+ if (webrtcEncoder) webrtcEncoder.setFps(targetFps);
800
+
801
+ // ── Event loop lag monitoring (for input flood investigation) ─────────────
802
+ let eventLoopMonitor = null;
803
+ let eventLoopLogTimer = null;
804
+ try {
805
+ const perfHooks = await import('perf_hooks');
806
+ eventLoopMonitor = perfHooks.monitorEventLoopDelay();
807
+ eventLoopMonitor.enable();
808
+ const EVENT_LOOP_LOG_MS = 5000;
809
+ eventLoopLogTimer = setInterval(() => {
810
+ const lag = eventLoopMonitor ? eventLoopMonitor.min / 1e6 : 0; // ms
811
+ if (lag > 5 && (logEvents || verbose)) { // only log if >5ms lag
812
+ console.error(`[event] event-loop-lag min=${lag.toFixed(2)}ms`);
813
+ }
814
+ if (eventLoopMonitor) eventLoopMonitor.reset();
815
+ }, EVENT_LOOP_LOG_MS);
816
+ } catch (e) {
817
+ // perf_hooks not available (e.g., old Node) — skip monitoring
818
+ }
253
819
 
254
820
  // ── Audio timing ──────────────────────────────────────────────────────────
255
821
  const audioSampleRate = 44100;
256
- const samplesPerFrame = Math.floor(audioSampleRate / targetFps); // 882 @ 50fps
822
+ const FALLBACK_DELTA_MS = 1000 / 60;
823
+ const MAX_DELTA_MS = 100;
824
+ const MAX_AUDIO_SAMPLES_PER_ITER = Math.ceil((audioSampleRate * MAX_DELTA_MS) / 1000);
257
825
  let audioInterval = null;
258
826
 
259
- // SID audio buffer is 4096 Float32 samples. debugger_update accumulates
260
- // samples into it across multiple calls. sid_getAudioBuffer() must be
261
- // called once per full 4096-sample fill — NOT once per video frame —
262
- // to read the complete buffer and reset it for the next fill cycle.
827
+ // SID audio design — two-stage pipeline:
263
828
  //
264
- // At 50fps: 882 samples/frame × ~4.65 frames = 4096 samples per SID buffer.
265
- // We track accumulated samples and call sid_getAudioBuffer() each time
266
- // the total crosses a 4096-sample boundary, sending the full 4096-sample
267
- // chunk to ffmpeg at that point.
268
- const SID_BUFFER_SIZE = 4096;
269
- let sidSampleAccum = 0; // samples accumulated since last sid_getAudioBuffer call
829
+ // Stage 1 (WASM → JS ring):
830
+ // Call sid_getAudioBuffer() exactly once per SID_BUFFER_SIZE samples of
831
+ // emulated audio (every ~4.65 video frames at 50fps). This is the ONLY
832
+ // safe call rate — calling it more often resets the SID's internal write
833
+ // counter and causes runaway emulation speed (per AGENTS.md).
834
+ // Each pull copies the full 4096-sample WASM buffer into a JS-side ring.
835
+ //
836
+ // Stage 2 (JS ring → ffmpeg/WebRTC):
837
+ // Every loop iteration, dequeue samples based on REAL elapsed wall-clock
838
+ // time, not target fps. This keeps audio throughput anchored to 44100 Hz
839
+ // even if the loop temporarily runs at 42fps, preventing A/V clock drift.
840
+ // The ring provides the decoupling: WASM pushes in 4096-sample chunks,
841
+ // consumers pull in 882-sample chunks.
842
+ //
843
+ // Ring sizing: hold at least 2× SID_BUFFER_SIZE so one full WASM pull
844
+ // 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
850
+ // Accumulator: how many emulated samples have passed since last WASM pull.
851
+ let sidSampleAccum = 0;
852
+ // Single staging buffer for per-frame audio delivered to ffmpeg/WebRTC.
853
+ const sidFrameBufMax = new Float32Array(MAX_AUDIO_SAMPLES_PER_ITER);
854
+ let sidFrameView = sidFrameBufMax.subarray(0, 1);
855
+
856
+ /** Pull one 4096-sample chunk from the WASM SID buffer into the JS ring. */
857
+ function pullSidBuffer() {
858
+ if (!exports || !heap || typeof exports.sid_getAudioBuffer !== 'function') return;
859
+ try {
860
+ const ptr = exports.sid_getAudioBuffer();
861
+ const base = ptr >> 2;
862
+ const src = heap.heapF32;
863
+ for (let i = 0; i < SID_BUFFER_SIZE; i++) {
864
+ sidRing[(sidRingWrite + i) % SID_RING_SIZE] = src[base + i];
865
+ }
866
+ sidRingWrite = (sidRingWrite + SID_BUFFER_SIZE) % SID_RING_SIZE;
867
+ sidRingCount = Math.min(sidRingCount + SID_BUFFER_SIZE, SID_RING_SIZE);
868
+ } catch (_) {}
869
+ }
870
+
871
+ /**
872
+ * Re-prime the JS SID ring with 2 full WASM buffer pulls (~8192 samples).
873
+ * Must be called after any emulator reset/cart-change once the WASM SID's
874
+ * own write cursor has been restarted — i.e. AFTER resetSidRing() zeros
875
+ * the JS ring state. Runs ~186ms of emulated pre-roll (not captured).
876
+ */
877
+ function primeSidRing() {
878
+ if (!exports || typeof exports.debugger_update !== 'function') return;
879
+ const primeMs = Math.ceil(SID_BUFFER_SIZE / (audioSampleRate / 1000)); // ~93ms
880
+ for (let p = 0; p < 2; p++) {
881
+ exports.debugger_update(primeMs);
882
+ pullSidBuffer();
883
+ }
884
+ }
885
+
886
+ /** Dequeue n samples from JS ring into sidFrameBufMax and expose sidFrameView. */
887
+ function dequeueSidFrame(n) {
888
+ const samplesNeeded = Math.max(1, Math.min(n, MAX_AUDIO_SAMPLES_PER_ITER));
889
+ sidFrameView = sidFrameBufMax.subarray(0, samplesNeeded);
890
+ // If the ring doesn't have a full frame yet, pad with silence rather than
891
+ // stalling — this can happen on the very first frames before the SID has
892
+ // had time to fill a full 4096-sample chunk.
893
+ if (sidRingCount < samplesNeeded) {
894
+ sidFrameBufMax.fill(0, 0, samplesNeeded);
895
+ return false;
896
+ }
897
+ for (let i = 0; i < samplesNeeded; i++) {
898
+ sidFrameBufMax[i] = sidRing[(sidRingRead + i) % SID_RING_SIZE];
899
+ }
900
+ sidRingRead = (sidRingRead + samplesNeeded) % SID_RING_SIZE;
901
+ sidRingCount -= samplesNeeded;
902
+ return true;
903
+ }
904
+
270
905
 
271
906
  // Resolve output path once — treat remote URLs verbatim, local file paths
272
907
  // should be resolved relative to the current working directory (process.cwd()).
@@ -317,49 +952,97 @@ export async function runHeadless(options = {}) {
317
952
  }
318
953
  }
319
954
 
955
+ // ── SID ring pre-prime ───────────────────────────────────────────────────
956
+ // Without pre-priming, the ring starts empty and the first ~4 frames are
957
+ // silent (sidSampleAccum hasn't crossed SID_BUFFER_SIZE yet). Worse, the
958
+ // ring drains to zero every ~4.65 frames (882 × 4 = 3528 < 4096) so the
959
+ // 5th frame after each pull would also be silent in steady state.
960
+ //
961
+ // Fix: run 2× SID_BUFFER_SIZE worth of emulation (~186ms) before the frame
962
+ // loop and pull both 4096-sample chunks into the JS ring. The ring then
963
+ // starts at 8192 samples — a comfortable ~9.3 frames of headroom — and
964
+ // never runs dry because subsequent pulls always arrive before it reaches 0.
965
+ //
966
+ // This emulation is "throwaway" pre-roll: the pixel buffer is not captured
967
+ // and the CPU state matches what a real C64 would be doing at startup.
968
+ if (audio || (webrtc && webrtcEncoder)) {
969
+ primeSidRing();
970
+ if (verbose) console.error(`[headless] SID ring primed: ${sidRingCount} samples ready`);
971
+ }
972
+
320
973
  // runStartTime is set AFTER ffmpeg starts so --duration counts from when
321
974
  // recording actually begins (after any RTMP probe/stabilisation delay).
322
975
  const runStartTime = Date.now();
323
- // When recording without an explicit --duration, run forever (endTime = Infinity).
324
- const endTime = record
976
+ const isStreamingMode = record || webrtc;
977
+ const endTime = isStreamingMode
325
978
  ? (durationSec ? runStartTime + durationSec * 1000 : Infinity)
326
979
  : null;
327
- let lastTick = Date.now();
328
- let windowStart = Date.now();
980
+
981
+ let windowStart = nowMonoMs();
329
982
  let windowCount = 0;
983
+ let lastStepAt = nowMonoMs();
330
984
 
331
- while (record ? Date.now() < endTime : frameCount < frames) {
332
- // iteration start timestamp (declare in outer scope so it's available
333
- // to the throttle logic even if the try block throws)
334
- let iterStart = Date.now();
985
+ while (isStreamingMode ? Date.now() < endTime : frameCount < frames) {
335
986
  try {
336
987
  if (verbose && frameCount % 50 === 0) console.error(`[headless] loop frameCount=${frameCount}`);
337
- // Record iteration start time and compute deltaMs. Always update
338
- // lastTick so the throttle calculation below works correctly for
339
- // both fixed-dt and wall-clock modes.
340
- iterStart = Date.now();
341
- let deltaMs;
342
- if (useFixedDt) {
343
- deltaMs = Math.round(1000 / targetFps);
344
- } else {
345
- // wall-clock delta in milliseconds since last tick
346
- deltaMs = iterStart - lastTick;
347
- if (deltaMs <= 0) deltaMs = Math.round(1000 / targetFps);
348
- // clamp to a single frame interval to avoid huge jumps
349
- if (deltaMs > 1000) deltaMs = Math.round(1000 / targetFps);
988
+
989
+ // Capture frame start time BEFORE emulation so sleepMs accounts for
990
+ // ALL work in this iteration (emulation + audio + video push + ffmpeg).
991
+ const iterStart = nowMonoMs();
992
+ // Drive emulation with real wall-clock delta to avoid long-term A/V drift
993
+ // when actual loop FPS differs from target FPS.
994
+ const nowMs = nowMonoMs();
995
+ let emuDeltaMs = nowMs - lastStepAt;
996
+ lastStepAt = nowMs;
997
+ if (!emuDeltaMs || emuDeltaMs > MAX_DELTA_MS) emuDeltaMs = FALLBACK_DELTA_MS;
998
+
999
+ // Run a single full-frame emulation step.
1000
+ // debugger_update() returns truthy when the emulator has completed a full
1001
+ // video frame (VSync). c64.js gates its redraw on both this return value
1002
+ // AND debugger_isRunning() — we mirror that here so we never push a stale
1003
+ // or repeated pixel buffer into WebRTC during boot/reset sequences.
1004
+ const frameReady = !!exports.debugger_update(emuDeltaMs);
1005
+ const isRunning = !!exports.debugger_isRunning();
1006
+
1007
+ // ── Audio: pull from WASM SID → JS ring → per-frame slice ───────────
1008
+ // Audio runs every frame regardless of frameReady/isRunning so the WebRTC
1009
+ // audio clock stays continuous — gaps cause desync, not silence.
1010
+ if (audio || (webrtc && webrtcEncoder)) {
1011
+ const samplesThisIter = Math.max(1, Math.round((audioSampleRate * emuDeltaMs) / 1000));
1012
+ sidSampleAccum += samplesThisIter;
1013
+ while (sidSampleAccum >= SID_BUFFER_SIZE) {
1014
+ sidSampleAccum -= SID_BUFFER_SIZE;
1015
+ pullSidBuffer();
1016
+ }
1017
+ dequeueSidFrame(samplesThisIter); // fills sidFrameView (or silence)
350
1018
  }
351
- lastTick = iterStart;
352
- // Drive the emulator for one frame interval. One call to debugger_update
353
- // with the target frame duration (20ms at 50fps) advances exactly one
354
- // PAL frame worth of C64 cycles. Do NOT call it multiple times per loop
355
- // iteration — that runs the emulator faster than real-time.
356
- const stepMs = Math.round(1000 / targetFps); // 20ms at 50fps
357
- try {
358
- // Advance emulator one frame. Previously we logged dt/ret here for
359
- // debugging; remove the per-frame diagnostic to avoid noisy output.
360
- exports.debugger_update(stepMs);
361
- } catch (e) {
362
- if (verbose) console.error('[headless] debugger_update threw', e);
1019
+
1020
+ // ── WebRTC: push video + audio into the live track ─────────────────
1021
+ if (webrtc && webrtcEncoder) {
1022
+ // Only push a video frame when the emulator confirms one is ready and
1023
+ // is actively running — mirrors c64.js: if (update && !!debugger_isRunning())
1024
+ if (frameReady && isRunning) {
1025
+ const nowVideoMs = nowMonoMs();
1026
+ if (nowVideoMs + 1 < nextVideoDueAtMs) {
1027
+ videoFramesDroppedCap++;
1028
+ videoFramesDroppedCapWindow++;
1029
+ } else {
1030
+ const overdueMs = Math.max(0, nowVideoMs - nextVideoDueAtMs);
1031
+ if (overdueMs >= webrtcSendIntervalMs) {
1032
+ const lateDrops = Math.floor(overdueMs / webrtcSendIntervalMs);
1033
+ videoFramesDroppedLate += lateDrops;
1034
+ videoFramesDroppedLateWindow += lateDrops;
1035
+ nextVideoDueAtMs += lateDrops * webrtcSendIntervalMs;
1036
+ }
1037
+ const ptr = exports.c64_getPixelBuffer();
1038
+ const rgba = heap.heapU8.subarray(ptr, ptr + 384 * 272 * 4);
1039
+ webrtcEncoder.pushVideoFrame(rgba);
1040
+ videoFramesSent++;
1041
+ nextVideoDueAtMs = Math.max(nextVideoDueAtMs + webrtcSendIntervalMs, nowVideoMs + 1);
1042
+ }
1043
+ }
1044
+
1045
+ webrtcEncoder.pushAudioFrame(sidFrameView);
363
1046
  }
364
1047
 
365
1048
  // Capture video frame and audio chunk, then write both atomically.
@@ -401,71 +1084,85 @@ export async function runHeadless(options = {}) {
401
1084
  break;
402
1085
  }
403
1086
  }
404
- try {
1087
+ if (frameReady && isRunning) {
405
1088
  const ptr = exports.c64_getPixelBuffer();
406
1089
  const videoFrame = heap.heapU8.subarray(ptr, ptr + frameSize);
407
- let audioChunk = null;
408
- if (audio && exports.sid_getAudioBuffer) {
409
- // Accumulate samples. sid_getAudioBuffer() fills 4096 samples per
410
- // cycle — call it exactly when the accumulator crosses that boundary,
411
- // then send the full 4096-sample buffer. This matches the original
412
- // ScriptProcessorNode pattern in c64.js (audioBufferLength = 4096).
413
- sidSampleAccum += samplesPerFrame;
414
- if (sidSampleAccum >= SID_BUFFER_SIZE) {
415
- sidSampleAccum -= SID_BUFFER_SIZE;
416
- try {
417
- const sidPtr = exports.sid_getAudioBuffer();
418
- const sidBase = sidPtr >> 2;
419
- // Copy the full 4096-sample buffer so ffmpeg gets a consistent chunk
420
- audioChunk = heap.heapF32.slice(sidBase, sidBase + SID_BUFFER_SIZE);
421
- } catch (_) {
422
- }
423
- }
424
- }
1090
+ const audioChunk = audio ? sidFrameView : null;
425
1091
  await ffmpegRunner.writeFrame(videoFrame, audioChunk);
426
- } catch (e) {
427
- const errMsg = `ffmpeg write error after ${frameCount} frames: ${e && e.message ? e.message : String(e)}`;
428
- out.push(errMsg);
429
- console.error(`[headless] ${errMsg}`);
430
- // For URL outputs, don't give up immediately — ffmpeg may have just died,
431
- // the isAlive() check at the top of next iteration will handle the retry.
432
- if (!isRtmpOutput) {
433
- ffmpegDied = true;
434
- record = false;
435
- break;
436
- }
437
1092
  }
438
1093
  }
1094
+ // Throttle to target FPS, then yield so input events are committed
1095
+ // to WASM before the next debugger_update.
1096
+ //
1097
+ // Ordering matters for input latency:
1098
+ // 1. setTimeout(sleepMs) — event loop sleeps; WebSocket 'message'
1099
+ // I/O callbacks fire during this window and call onInput() which
1100
+ // writes directly to WASM exports (keyboard_keyPressed, etc.)
1101
+ // 2. setImmediate yield — runs after all pending I/O callbacks,
1102
+ // guaranteeing any message that arrived right at the end of the
1103
+ // sleep is also committed before we continue.
1104
+ // 3. top of next iteration: debugger_update() reads the now-current
1105
+ // WASM input state.
1106
+ //
1107
+ // Worst-case input latency = one full frame (20ms @ 50fps): a keydown
1108
+ // that lands just AFTER step 2 waits until the following frame.
1109
+ // Average latency = half a frame (~10ms).
1110
+ const workMs = nowMonoMs() - iterStart;
1111
+ const sleepMs = Math.max(0, frameMs - workMs);
1112
+ if (sleepMs > 0) await new Promise((r) => setTimeout(r, sleepMs));
1113
+ await new Promise((r) => setImmediate(r)); // drain any remaining I/O callbacks
439
1114
  } catch (_) {
440
1115
  }
441
1116
  frameCount++;
442
1117
  // diagnostics
443
1118
  windowCount++;
444
1119
  if (windowCount >= 50) {
445
- const now = Date.now();
1120
+ const now = nowMonoMs();
446
1121
  const secs = (now - windowStart) / 1000;
447
- const obsFps = windowCount / (secs || 1);
448
- //console.error(`[headless] observed fps=${obsFps.toFixed(2)} over ${secs.toFixed(2)}s (frames ${frameCount - windowCount}..${frameCount})`);
1122
+ const actualFps = windowCount / secs;
449
1123
  windowStart = now;
450
1124
  windowCount = 0;
1125
+ // Drift reporting: if actual FPS deviates more than 10% from target, warn.
1126
+ // Only emit when --log-events is set; never emit per-frame.
1127
+ if (logEvents || verbose) {
1128
+ const drift = actualFps - targetFps;
1129
+ const driftPct = Math.abs(drift / targetFps) * 100;
1130
+ 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)}%)`);
1132
+ }
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}`);
1135
+ }
1136
+ }
1137
+ runtimeStats.videoFramesSent = videoFramesSent;
1138
+ runtimeStats.videoFramesDroppedLate = videoFramesDroppedLate;
1139
+ runtimeStats.videoFramesDroppedCap = videoFramesDroppedCap;
1140
+ const webrtcTelemetry = getWebrtcTelemetry();
1141
+ if (webrtcTelemetry) {
1142
+ 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;
1149
+ runtimeStats.webrtcQualityLimitation = webrtcTelemetry.qualityLimitation ?? null;
1150
+ }
1151
+ runtimeStats.sampledAt = Date.now();
1152
+ if (videoFramesDroppedLateWindow > 0 || videoFramesDroppedCapWindow > 0) {
1153
+ videoFramesDroppedLateWindow = 0;
1154
+ videoFramesDroppedCapWindow = 0;
1155
+ }
451
1156
  }
452
1157
  if (verify && frameCount % 60 === 0) {
453
1158
  const cycleCount = exports.c64_getCycleCount ? exports.c64_getCycleCount() : null;
454
1159
  out.push(JSON.stringify({pid: process.pid, frame: frameCount, cycles: cycleCount}));
455
- // Also emit a stderr heartbeat so interactive runs show progress.
456
1160
  try {
457
1161
  const pc = exports.c64_getPC ? exports.c64_getPC() : null;
458
1162
  console.error(`[headless] verify: frame=${frameCount} pc=${pc} cycles=${cycleCount}`);
459
1163
  } catch (_) {
460
1164
  }
461
- } else if (frameCount % 120 === 0) {
462
- //out.push(`HEADLESS: frame=${frameCount}`);
463
1165
  }
464
- // Throttle to target FPS: sleep for the remainder of the frame interval
465
- const frameMs = Math.round(1000 / targetFps);
466
- const iterElapsed = Date.now() - iterStart;
467
- const sleepMs = Math.max(0, frameMs - iterElapsed);
468
- await new Promise((r) => setTimeout(r, sleepMs));
469
1166
  }
470
1167
 
471
1168
  const elapsed = (Date.now() - runStartTime) / 1000;
@@ -481,6 +1178,19 @@ export async function runHeadless(options = {}) {
481
1178
  }
482
1179
  }
483
1180
 
1181
+ // ── Shut down WebRTC server ───────────────────────────────────────────────
1182
+ if (webrtcServer) {
1183
+ try {
1184
+ await webrtcServer.close();
1185
+ if (verbose) console.error('[headless] webrtc server closed');
1186
+ } catch (e) {
1187
+ console.error('[headless] webrtc server close error:', e && e.message ? e.message : e);
1188
+ }
1189
+ }
1190
+
1191
+ // ── Log file teardown ──────────────────────────────────────────────────────
1192
+ _teardownLogFile();
1193
+
484
1194
  if (record && ffmpegRunner) {
485
1195
  // Clear audio interval if it was used (currently null/no-op)
486
1196
  if (audioInterval) {
@@ -539,4 +1249,3 @@ try {
539
1249
  } catch (e) {
540
1250
  // ignore errors in CLI wrapper detection
541
1251
  }
542
-