c64-ready 0.6.2 → 0.10.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.
@@ -1,7 +1,126 @@
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
+ // ── Build info ────────────────────────────────────────────────────────────────
100
+ // Read once at module load so every createInputServer call gets the same values.
101
+ const _repoRootForBuildInfo = path.resolve(new URL('../../', import.meta.url).pathname);
102
+ let _serverVersion = null;
103
+ let _serverGitHash = null;
104
+ try {
105
+ const pkg = JSON.parse(readFileSync(path.join(_repoRootForBuildInfo, 'package.json'), 'utf8'));
106
+ _serverVersion = pkg.version ?? null;
107
+ } catch { /* non-fatal */ }
108
+ try {
109
+ // Prefer the baked-in build-arg written by the Dockerfile (works in Docker
110
+ // where git is not installed and .git is not present).
111
+ // Fall back to execSync for local dev where the repo is available.
112
+ const hashFile = path.join(_repoRootForBuildInfo, '.git-hash');
113
+ if (process.env.GIT_HASH) {
114
+ _serverGitHash = process.env.GIT_HASH.trim() || null;
115
+ } else {
116
+ try {
117
+ _serverGitHash = readFileSync(hashFile, 'utf8').trim() || null;
118
+ } catch {
119
+ _serverGitHash = execSync('git rev-parse --short HEAD', { cwd: _repoRootForBuildInfo, stdio: ['ignore', 'pipe', 'ignore'] })
120
+ .toString().trim();
121
+ }
122
+ }
123
+ } catch { /* non-fatal — git may not be available in some deploy environments */ }
5
124
 
6
125
  /**
7
126
  * Run headless emulator. Exported so tests can inject a fake WebAssembly.instantiate.
@@ -21,13 +140,21 @@ export async function runHeadless(options = {}) {
21
140
  let verify = false;
22
141
  let record = false;
23
142
  let audio = false;
24
- // Use fixed timestep by default to keep emulation timing stable.
25
- let useFixedDt = true;
26
143
  let raw = false;
27
144
  let output = null;
28
145
  let durationSec = 0; // 0 means no --duration was passed → stream forever when recording
29
146
  let enableInput = false;
30
147
  let wsPort = 9001;
148
+ let webrtc = false;
149
+ let webrtcPort = 9002;
150
+ let logEvents = false;
151
+ let maxSpectators = 3;
152
+ let webrtcMinBitrateKbps = 200;
153
+ let webrtcMaxBitrateKbps = 600;
154
+ let webrtcOutputFps = 40;
155
+ let adminToken = process.env.C64_ADMIN_TOKEN ?? '';
156
+ let logFile = false;
157
+ let logRetainDays = 7;
31
158
  for (let i = 0; i < argv.length; i++) {
32
159
  const a = argv[i];
33
160
  if (a === '--wasm' || a === '-w') wasmArg = argv[++i];
@@ -41,15 +168,128 @@ export async function runHeadless(options = {}) {
41
168
  else if (a === '--duration' || a === '-d') durationSec = Number(argv[++i]);
42
169
  else if (a === '--no-game') noGame = true;
43
170
  else if (a === '--verbose') verbose = true;
171
+ else if (a === '--log-events') logEvents = true;
172
+ else if (a === '--log-file') logFile = true;
173
+ else if (a === '--log-retain-days') logRetainDays = Number(argv[++i]);
44
174
  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
175
  else if (a === '--input') enableInput = true;
48
176
  else if (a === '--ws-port') wsPort = Number(argv[++i]);
177
+ else if (a === '--webrtc') webrtc = true;
178
+ else if (a === '--webrtc-port') webrtcPort = Number(argv[++i]);
179
+ else if (a === '--max-spectators') maxSpectators = Number(argv[++i]);
180
+ else if (a === '--webrtc-min-bitrate-kbps') webrtcMinBitrateKbps = Number(argv[++i]);
181
+ else if (a === '--webrtc-max-bitrate-kbps') webrtcMaxBitrateKbps = Number(argv[++i]);
182
+ else if (a === '--webrtc-output-fps') webrtcOutputFps = Number(argv[++i]);
183
+ else if (a === '--admin-token') adminToken = argv[++i] ?? '';
49
184
  else if (a === '--help' || a === '-h') {
50
185
  return {ok: false, output: 'help'};
51
186
  }
52
187
  }
188
+ const adminTokenSafe = String(adminToken ?? '').trim();
189
+
190
+ const webrtcMinBitrateKbpsSafe = Number.isFinite(webrtcMinBitrateKbps) && webrtcMinBitrateKbps > 0
191
+ ? Math.round(webrtcMinBitrateKbps)
192
+ : 200;
193
+ const webrtcMaxBitrateKbpsSafe = Number.isFinite(webrtcMaxBitrateKbps) && webrtcMaxBitrateKbps > 0
194
+ ? Math.max(webrtcMinBitrateKbpsSafe, Math.round(webrtcMaxBitrateKbps))
195
+ : Math.max(webrtcMinBitrateKbpsSafe, 600);
196
+ const webrtcOutputFpsSafe = Number.isFinite(webrtcOutputFps) && webrtcOutputFps > 0
197
+ ? Math.round(webrtcOutputFps)
198
+ : 0;
199
+
200
+ const runtimeStats = {
201
+ webrtcSendFps: null,
202
+ videoFramesSent: 0,
203
+ videoFramesDroppedLate: 0,
204
+ videoFramesDroppedCap: 0,
205
+ webrtcPeerCount: null,
206
+ webrtcAvgRttMs: null,
207
+ webrtcSendDelayMsPerPacket: null,
208
+ webrtcEncodeMsPerFrame: null,
209
+ webrtcFramesSentPerSec: null,
210
+ webrtcFramesEncodedPerSec: null,
211
+ webrtcBytesSentPerSec: null,
212
+ webrtcQualityLimitation: null,
213
+ sampledAt: Date.now(),
214
+ };
215
+
216
+ // ── Log file setup ────────────────────────────────────────────────────────────
217
+ let logStream = null;
218
+ let _origConsoleLog = null;
219
+ let _origConsoleError = null;
220
+
221
+ function _setupLogFile() {
222
+ if (!logFile) return;
223
+
224
+ const logsDir = path.join(repoRoot, 'logs');
225
+ try {
226
+ mkdirSync(logsDir, { recursive: true });
227
+ } catch (e) {
228
+ console.error('[headless] could not create logs directory:', e.message);
229
+ return;
230
+ }
231
+
232
+ // Clean up old logs
233
+ if (logRetainDays > 0) {
234
+ try {
235
+ const files = readdirSync(logsDir);
236
+ const now = Date.now();
237
+ for (const f of files) {
238
+ if (!f.startsWith('headless-') || !f.endsWith('.log')) continue;
239
+ const fpath = path.join(logsDir, f);
240
+ const stat = statSync(fpath);
241
+ const ageDays = (now - stat.mtimeMs) / (1000 * 60 * 60 * 24);
242
+ if (ageDays > logRetainDays) {
243
+ unlinkSync(fpath);
244
+ console.error(`[headless] purged old log: ${f} (${ageDays.toFixed(1)} days old)`);
245
+ }
246
+ }
247
+ } catch (e) {
248
+ console.error('[headless] log cleanup error:', e.message);
249
+ }
250
+ }
251
+
252
+ // Generate filename
253
+ const timestamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
254
+ const logPath = path.join(logsDir, `headless-${timestamp}.log`);
255
+ try {
256
+ logStream = createWriteStream(logPath, { flags: 'a' });
257
+ console.error(`[headless] logging to: ${logPath}`);
258
+ } catch (e) {
259
+ console.error('[headless] could not open log file:', e.message);
260
+ return;
261
+ }
262
+
263
+ // Tee console methods
264
+ _origConsoleLog = console.log;
265
+ _origConsoleError = console.error;
266
+
267
+ const _writeLog = (origFn, ...args) => {
268
+ origFn.apply(console, args);
269
+ if (logStream && logStream.writable) {
270
+ const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ') + '\n';
271
+ logStream.write(line);
272
+ }
273
+ };
274
+
275
+ console.log = (...args) => _writeLog(_origConsoleLog, ...args);
276
+ console.error = (...args) => _writeLog(_origConsoleError, ...args);
277
+ }
278
+
279
+ function _teardownLogFile() {
280
+ if (logStream) {
281
+ try { logStream.end(); } catch (_) {}
282
+ logStream = null;
283
+ }
284
+ if (_origConsoleLog) {
285
+ console.log = _origConsoleLog;
286
+ console.error = _origConsoleError;
287
+ _origConsoleLog = null;
288
+ _origConsoleError = null;
289
+ }
290
+ }
291
+
292
+ _setupLogFile();
53
293
 
54
294
  const defaultWasmPaths = [
55
295
  path.join(repoRoot, 'public', 'c64.wasm'),
@@ -91,10 +331,14 @@ export async function runHeadless(options = {}) {
91
331
  out.push(`Starting headless C64 using WASM: ${wasmPath}` + (gamePath ? ` game: ${gamePath}` : ''));
92
332
 
93
333
  const wasmBinary = await fs.readFile(wasmPath);
94
- // runtime state placeholders
95
- let exports = null;
96
- let heap = null;
334
+ // runtime state placeholders — hoisted so onCommand handler can access c64wasm
335
+ let exports = null;
336
+ let heap = null;
337
+ let c64wasm = null; // ← hoisted: needed by onCommand for allocAndWrite
97
338
  let wrapperUsed = false;
339
+ // SID audio constants — hoisted so the SID-cache block and the frame loop
340
+ // both see them regardless of declaration order.
341
+ const SID_BUFFER_SIZE = 4096;
98
342
 
99
343
  // If a test injected a fake instantiate function, prefer that path so
100
344
  // tests can run without the compiled wrapper. Provide a minimal import
@@ -158,7 +402,7 @@ export async function runHeadless(options = {}) {
158
402
  wasmBinary.byteOffset,
159
403
  wasmBinary.byteOffset + wasmBinary.byteLength,
160
404
  );
161
- const c64wasm = new C64WASM();
405
+ c64wasm = new C64WASM(); // assigns to outer let
162
406
  await c64wasm.instantiate(wasmAb);
163
407
 
164
408
  exports = c64wasm.exports;
@@ -173,13 +417,17 @@ export async function runHeadless(options = {}) {
173
417
  if (gamePath) {
174
418
  try {
175
419
  const gameData = await fs.readFile(gamePath);
176
- const ptr = c64wasm.allocAndWrite(new Uint8Array(gameData));
420
+ const gameArr = new Uint8Array(gameData);
421
+ const cartInfo = parseCrtInfo(gameArr, path.basename(gamePath));
422
+ if (cartInfo) console.error(cartInfo.line);
423
+ const ptr = c64wasm.allocAndWrite(gameArr);
177
424
  c64wasm.updateHeapViews();
178
425
  heap = c64wasm.heap;
179
426
  exports.c64_loadCartridge(ptr, gameData.length);
180
- exports.free(ptr);
181
- exports.c64_reset();
182
- exports.debugger_play();
427
+ // free(ptr), c64_reset, debugger_set_speed, debugger_play intentionally
428
+ // omitted: c64_loadCartridge already resets and resumes the machine
429
+ // internally. Calling them re-triggers the ROM boot sequence — the same
430
+ // root cause of post-load input lag fixed for the load-crt command path.
183
431
  } catch (e) {
184
432
  out.push(`Failed to load game: ${String(e)}`);
185
433
  }
@@ -195,6 +443,7 @@ export async function runHeadless(options = {}) {
195
443
  return {ok: false, output: out};
196
444
  }
197
445
 
446
+
198
447
  // ── Input server (WebSocket) ──────────────────────────────────────────────
199
448
  // Start the embedded WebSocket input server when --input is passed.
200
449
  // Remote clients connect and send JSON InputEvent messages which are
@@ -203,39 +452,184 @@ export async function runHeadless(options = {}) {
203
452
  if (enableInput) {
204
453
  try {
205
454
  const { createInputServer } = await import('./input-server.mjs');
455
+ // Try to import the kick-token validator from the co-located c64cade server.
456
+ // If it's not present (standalone c64-ready usage) fall back to no-op.
457
+ // NOTE: The import path is computed at runtime (not a string literal) so
458
+ // Vite/Vitest does NOT attempt to resolve/bundle it at transform time —
459
+ // dynamic import of a non-literal string is left to the JS engine.
460
+ let validateKickToken = () => null;
461
+ try {
462
+ const kickTokenRelPath = '../../c64cade/packages/server/utils/kick-tokens.js';
463
+ const kickTokenUrl = new URL(kickTokenRelPath, import.meta.url).href;
464
+ const kickTokens = await import(kickTokenUrl);
465
+ validateKickToken = kickTokens.validateKickToken;
466
+ } catch { /* standalone mode — admin kick not available */ }
467
+
206
468
  const dirMap = { up: 0x1, down: 0x2, left: 0x4, right: 0x8 };
469
+
470
+
471
+ /** Flush all SID ring state after any emulator reset/cart-change.
472
+ * The WASM SID resets its internal write cursor on c64_reset(), so any
473
+ * samples still in the JS ring are from the old game and must be discarded.
474
+ * sidSampleAccum is also zeroed so the next pull aligns with the freshly
475
+ * restarted SID write cursor rather than inheriting stale offset.
476
+ * Note: we do NOT call primeSidRing() here — that would run 186ms of
477
+ * synchronous debugger_update inside the load-crt setImmediate callback
478
+ * and add unwanted post-load blockage. The ring re-fills naturally within
479
+ * ~5 frames; those frames output silence which is inaudible during the
480
+ * game's own startup sound sequence. */
481
+ function resetSidRing() {
482
+ sidSampleAccum = 0;
483
+ sidRingWrite = 0;
484
+ sidRingRead = 0;
485
+ sidRingCount = 0;
486
+ sidFrameBufMax.fill(0);
487
+ sidFrameView = sidFrameBufMax.subarray(0, 1);
488
+ }
489
+
207
490
  inputServer = createInputServer({
208
491
  port: wsPort,
209
492
  verbose,
210
- onInput: (event) => {
493
+ logEvents,
494
+ validateKickToken,
495
+ validateAdminToken: (token) => {
496
+ if (!adminTokenSafe) return false;
497
+ return token === adminTokenSafe;
498
+ },
499
+ initialCartFilename: gamePath ? path.basename(gamePath) : null,
500
+ serverVersion: _serverVersion,
501
+ serverGitHash: _serverGitHash,
502
+ getRuntimeStats: () => ({ ...runtimeStats }),
503
+ getWebrtcPeerSnapshot: () => getWebrtcPeerSnapshot(),
504
+ disconnectWebrtcPeersByAddr: (addr, reason) => disconnectWebrtcPeersByAddr(addr, reason),
505
+ disconnectAllWebrtcPeers: (reason) => disconnectAllWebrtcPeers(reason),
506
+ onCommand: (cmd) => {
211
507
  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);
508
+ if (cmd.type === 'load-crt') {
509
+ // Decode base64 → Uint8Array immediately and release the large
510
+ // base64 string from the cmd object as soon as possible so GC
511
+ // can reclaim it during the subsequent async gap.
512
+ const buf = Buffer.from(cmd.data, 'base64');
513
+ // Slice to own ArrayBuffer — avoids aliasing Node's pooled Buffer
514
+ // which could span a much larger backing store than the data alone.
515
+ const arr = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength).slice();
516
+ cmd.data = null; // release base64 string early
517
+ const byteLen = arr.length;
518
+ const filename = cmd.filename;
519
+ // Defer the blocking WASM work (malloc + copy + cartridge parse)
520
+ // via setImmediate so the event loop can drain any pending frame
521
+ // writes / setTimeout callbacks before the synchronous WASM work
522
+ // begins. This prevents the frame loop from stalling mid-write.
523
+ // Return a Promise so input-server waits before broadcasting
524
+ // cart-loaded — ensuring clients are told only after load succeeds.
525
+ return new Promise((resolve, reject) => {
526
+ setImmediate(() => {
527
+ try {
528
+ const gapStart = Date.now();
529
+ exports.c64_removeCartridge();
530
+ exports.c64_reset(); // clean slate before loading new cart
531
+ const cartInfo = parseCrtInfo(arr, filename);
532
+ if (cartInfo) console.error(cartInfo.line);
533
+ const ptr = c64wasm.allocAndWrite(arr);
534
+ c64wasm.updateHeapViews();
535
+ heap = c64wasm.heap;
536
+ exports.c64_loadCartridge(ptr, byteLen);
537
+ // free(ptr), debugger_set_speed and debugger_play intentionally
538
+ // omitted: c64_loadCartridge internally resets and resumes.
539
+ const gapMs = Date.now() - gapStart;
540
+ //
541
+ // ── Audio RTP re-sync after blocking gap ─────────────────────
542
+ // c64_loadCartridge blocks the event loop for ~1300ms. During
543
+ // this time the frame loop is frozen so no audio is pushed to
544
+ // RTCAudioSource. The video RTP clock (driven by @roamhq/wrtc
545
+ // internally via wall-clock) keeps ticking, but the audio RTP
546
+ // clock only advances when onData() is called — so audio falls
547
+ // ~1300ms behind video. The browser's AV sync logic then holds
548
+ // video playback until audio catches up, manifesting as input lag.
549
+ //
550
+ // Fix: push silence frames totalling the measured gap duration so
551
+ // the audio RTP clock jumps forward by the same amount the video
552
+ // RTP clock advanced during the blockage.
553
+ resetSidRing();
554
+ if (webrtcEncoder) {
555
+ webrtcEncoder.pushSilenceForGap(gapMs);
556
+ if (verbose) console.error(`[headless] pushed ${gapMs}ms silence to re-align audio RTP after cart load`);
557
+ }
558
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
559
+ if (verbose) console.error(`[headless] cart loaded: ${filename} (${byteLen} bytes, gap=${gapMs}ms)`);
560
+ else if (logEvents) console.error(`[event] cart-loaded filename=${filename} bytes=${byteLen} gap=${gapMs}ms`);
561
+ resolve();
562
+ } catch (err) {
563
+ if (verbose) console.error('[headless] cart load (deferred) error:', err);
564
+ else if (logEvents) console.error(`[event] error cart-load-failed filename=${filename} err=${err && err.message ? err.message : err}`);
565
+ reject(err);
566
+ }
567
+ });
568
+ });
569
+ } else if (cmd.type === 'detach-crt') {
570
+ const gapStart = Date.now();
571
+ exports.c64_removeCartridge();
572
+ exports.c64_reset(); // return to clean BASIC prompt
573
+ const gapMs = Date.now() - gapStart;
574
+ resetSidRing();
575
+ if (webrtcEncoder) {
576
+ webrtcEncoder.pushSilenceForGap(gapMs);
577
+ if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after detach`);
225
578
  }
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
- }
579
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
580
+ if (verbose) console.error('[headless] cart detached');
581
+ else if (logEvents) console.error(`[event] cart-detached gap=${gapMs}ms`);
582
+ } else if (cmd.type === 'hard-reset') {
583
+ // Instant hard reset: detach cart and soft-reset the machine.
584
+ // c64_removeCartridge() is ~0ms; c64_reset() with no cart is ~110ms
585
+ // and runs synchronously inline — no setImmediate deferral needed
586
+ // since there is no loadCartridge call to block the event loop.
587
+ // The game is intentionally NOT reloaded: hard reset returns to
588
+ // the BASIC prompt / blank screen, matching real C64 behaviour.
589
+ const gapStart = Date.now();
590
+ exports.c64_removeCartridge();
591
+ exports.c64_reset();
592
+ const gapMs = Date.now() - gapStart;
593
+ resetSidRing();
594
+ if (webrtcEncoder) {
595
+ webrtcEncoder.pushSilenceForGap(gapMs);
596
+ if (verbose) console.error(`[headless] pushed ${gapMs}ms silence after hard reset`);
235
597
  }
598
+ if (webrtcServer) webrtcServer.forceKeyframe(webrtcEncoder?.videoTrack);
599
+ if (verbose) console.error('[headless] hard reset');
600
+ else if (logEvents) console.error(`[event] hard-reset gap=${gapMs}ms`);
601
+ }
602
+ },
603
+ onInput: (event) => {
604
+ if (!exports) return;
605
+ if (event.type === 'joystick') {
606
+ const port = ((event.joystickPort ?? 2) - 1); // 1-based → 0-based
607
+ const dir = event.direction ? (dirMap[event.direction] ?? 0) : 0;
608
+ const fire = (event.fire || event.fire1) ? 0x10 : 0;
609
+ if (event.action === 'release') {
610
+ if (dir) exports.c64_joystick_release(port, dir);
611
+ if (fire) exports.c64_joystick_release(port, fire);
612
+ } else {
613
+ if (dir) exports.c64_joystick_push(port, dir);
614
+ if (fire) exports.c64_joystick_push(port, fire);
615
+ }
616
+ if (verbose) {
617
+ const role = event._role ?? 'unknown';
618
+ console.error(`[event] input joystick role=${role} port=${event.joystickPort ?? 2} action=${event.action ?? 'press'} dir=${event.direction ?? '-'} fire=${!!(event.fire || event.fire1)}`);
619
+ }
620
+ } else if (event.type === 'key') {
621
+ const domKey = String(event.key ?? '');
622
+ const shiftKey = !!event.shiftKey;
623
+ const evType = event.action === 'up' ? 'keyup' : 'keydown';
624
+ const c64acts = domKeyToC64Actions(domKey, shiftKey, evType);
625
+ for (const act of c64acts) {
626
+ if (act.action === 'press') exports.keyboard_keyPressed(act.key);
627
+ else exports.keyboard_keyReleased(act.key);
628
+ }
629
+ if (verbose && c64acts.length > 0) {
630
+ const role = event._role ?? 'unknown';
631
+ console.error(`[input] input key role=${role} ${evType} "${domKey}" → ${JSON.stringify(c64acts)}`);
236
632
  }
237
- } catch (err) {
238
- if (verbose) console.error('[headless] input dispatch error:', err);
239
633
  }
240
634
  },
241
635
  });
@@ -246,27 +640,212 @@ export async function runHeadless(options = {}) {
246
640
  }
247
641
  }
248
642
 
643
+ // ── WebRTC server (low-latency streaming, replaces RTMP+flv.js) ─────────
644
+ // Started when --webrtc is passed. Opens an HTTP+WS signalling server on
645
+ // webrtcPort (default 9002). Each connecting browser gets its own
646
+ // RTCPeerConnection fed by the shared encoder tracks.
647
+ let webrtcEncoder = null;
648
+ let webrtcServer = null;
649
+ let getWebrtcTelemetry = () => null;
650
+ let getWebrtcPeerSnapshot = () => null;
651
+ let disconnectWebrtcPeersByAddr = () => 0;
652
+ let disconnectAllWebrtcPeers = () => 0;
653
+
654
+ if (webrtc) {
655
+ try {
656
+ const { WebRTCEncoder } = await import('./webrtc-encoder.mjs');
657
+ const { createWebRTCServer } = await import('./webrtc-server.mjs');
658
+ const wrtcLib = (await import('@roamhq/wrtc')).default;
659
+ const { MediaStream } = wrtcLib;
660
+
661
+ webrtcEncoder = new WebRTCEncoder();
662
+ webrtcEncoder.init({ width: 384, height: 272, sampleRate: 44100 });
663
+
664
+ const { videoTrack, audioTrack } = webrtcEncoder;
665
+
666
+ webrtcServer = createWebRTCServer({
667
+ port: webrtcPort,
668
+ verbose,
669
+ logEvents,
670
+ inputPort: wsPort,
671
+ maxSpectators,
672
+ minBitrateKbps: webrtcMinBitrateKbpsSafe,
673
+ maxBitrateKbps: webrtcMaxBitrateKbpsSafe,
674
+ // onOffer fires BEFORE createAnswer() — the right place to addTrack()
675
+ onOffer(pc) {
676
+ const stream = new MediaStream([videoTrack, audioTrack]);
677
+ pc.addTrack(videoTrack, stream);
678
+ pc.addTrack(audioTrack, stream);
679
+ if (verbose) console.error('[webrtc] tracks attached to peer');
680
+ },
681
+ onPeerConnected(pc) {
682
+ if (verbose) console.error('[webrtc] peer ICE connected');
683
+ // Reduce video sender bitrate after connection to minimise encode
684
+ // latency. A tight ceiling keeps frame sizes small and predictable,
685
+ // reducing the encoder's internal queue and decode buffer on the
686
+ // receiving end.
687
+ try {
688
+ const senders = pc.getSenders();
689
+ for (const sender of senders) {
690
+ if (sender.track && sender.track.kind === 'video') {
691
+ const params = sender.getParameters();
692
+ const maxBitrateBps = Math.max(100_000, Math.round(webrtcMaxBitrateKbpsSafe * 1000));
693
+ if (params.encodings && params.encodings.length > 0) {
694
+ params.encodings[0].maxBitrate = maxBitrateBps;
695
+ } else {
696
+ params.encodings = [{ maxBitrate: maxBitrateBps }];
697
+ }
698
+ sender.setParameters(params).catch(() => {});
699
+ break;
700
+ }
701
+ }
702
+ } catch (_) {}
703
+ },
704
+ });
705
+ if (typeof webrtcServer.getTelemetrySnapshot === 'function') {
706
+ getWebrtcTelemetry = () => webrtcServer.getTelemetrySnapshot();
707
+ }
708
+ if (typeof webrtcServer.getPeerSnapshot === 'function') {
709
+ getWebrtcPeerSnapshot = () => webrtcServer.getPeerSnapshot();
710
+ }
711
+ if (typeof webrtcServer.disconnectPeersByAddr === 'function') {
712
+ disconnectWebrtcPeersByAddr = (addr, reason) => webrtcServer.disconnectPeersByAddr(addr, reason);
713
+ }
714
+ if (typeof webrtcServer.disconnectAllPeers === 'function') {
715
+ disconnectAllWebrtcPeers = (reason) => webrtcServer.disconnectAllPeers(reason);
716
+ }
717
+
718
+ out.push(`WebRTC player at http://0.0.0.0:${webrtcPort}/ (send cap: ${webrtcOutputFpsSafe > 0 ? `${webrtcOutputFpsSafe}fps` : 'off'})`);
719
+ } catch (e) {
720
+ console.error('[headless] Failed to start WebRTC server:', e && e.message ? e.message : e);
721
+ out.push(`webrtc-server-failed: ${String(e)}`);
722
+ webrtc = false;
723
+ }
724
+ }
725
+
249
726
  // Run state and timing
250
727
  let frameCount = 0;
251
728
  let ffmpegDied = false; // set to true if ffmpeg exits unexpectedly and we give up
252
729
  const targetFps = (typeof fps === 'number' && !Number.isNaN(fps) && fps > 0) ? fps : 60;
730
+ const frameMs = Math.round(1000 / targetFps);
731
+ const webrtcSendFps = webrtcOutputFpsSafe > 0 ? Math.max(1, Math.min(targetFps, webrtcOutputFpsSafe)) : targetFps;
732
+ const webrtcSendIntervalMs = 1000 / webrtcSendFps;
733
+ let nextVideoDueAtMs = nowMonoMs();
734
+ let videoFramesSent = 0;
735
+ let videoFramesDroppedLate = 0;
736
+ let videoFramesDroppedCap = 0;
737
+ let videoFramesDroppedLateWindow = 0;
738
+ let videoFramesDroppedCapWindow = 0;
739
+ runtimeStats.webrtcSendFps = webrtcSendFps;
740
+ // Now that targetFps is known, configure the WebRTC encoder's frame duration
741
+ // so video timestamps are driven by frame count × frame duration (µs) rather
742
+ // than wall clock — making loadCartridge blockages invisible to the receiver.
743
+ if (webrtcEncoder) webrtcEncoder.setFps(targetFps);
744
+
745
+ // ── Event loop lag monitoring (for input flood investigation) ─────────────
746
+ let eventLoopMonitor = null;
747
+ let eventLoopLogTimer = null;
748
+ try {
749
+ const perfHooks = await import('perf_hooks');
750
+ eventLoopMonitor = perfHooks.monitorEventLoopDelay();
751
+ eventLoopMonitor.enable();
752
+ const EVENT_LOOP_LOG_MS = 5000;
753
+ eventLoopLogTimer = setInterval(() => {
754
+ const lag = eventLoopMonitor ? eventLoopMonitor.min / 1e6 : 0; // ms
755
+ if (lag > 5 && (logEvents || verbose)) { // only log if >5ms lag
756
+ console.error(`[event] event-loop-lag min=${lag.toFixed(2)}ms`);
757
+ }
758
+ if (eventLoopMonitor) eventLoopMonitor.reset();
759
+ }, EVENT_LOOP_LOG_MS);
760
+ } catch (e) {
761
+ // perf_hooks not available (e.g., old Node) — skip monitoring
762
+ }
253
763
 
254
764
  // ── Audio timing ──────────────────────────────────────────────────────────
255
765
  const audioSampleRate = 44100;
256
- const samplesPerFrame = Math.floor(audioSampleRate / targetFps); // 882 @ 50fps
766
+ const FALLBACK_DELTA_MS = 1000 / 60;
767
+ const MAX_DELTA_MS = 100;
768
+ const MAX_AUDIO_SAMPLES_PER_ITER = Math.ceil((audioSampleRate * MAX_DELTA_MS) / 1000);
257
769
  let audioInterval = null;
258
770
 
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.
771
+ // SID audio design — two-stage pipeline:
263
772
  //
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
773
+ // Stage 1 (WASM → JS ring):
774
+ // Call sid_getAudioBuffer() exactly once per SID_BUFFER_SIZE samples of
775
+ // emulated audio (every ~4.65 video frames at 50fps). This is the ONLY
776
+ // safe call rate — calling it more often resets the SID's internal write
777
+ // counter and causes runaway emulation speed (per AGENTS.md).
778
+ // Each pull copies the full 4096-sample WASM buffer into a JS-side ring.
779
+ //
780
+ // Stage 2 (JS ring → ffmpeg/WebRTC):
781
+ // Every loop iteration, dequeue samples based on REAL elapsed wall-clock
782
+ // time, not target fps. This keeps audio throughput anchored to 44100 Hz
783
+ // even if the loop temporarily runs at 42fps, preventing A/V clock drift.
784
+ // The ring provides the decoupling: WASM pushes in 4096-sample chunks,
785
+ // consumers pull in 882-sample chunks.
786
+ //
787
+ // Ring sizing: hold at least 2× SID_BUFFER_SIZE so one full WASM pull
788
+ // never overflows while the consumer hasn't caught up yet.
789
+ const SID_RING_SIZE = SID_BUFFER_SIZE * 4; // 16384 samples of headroom
790
+ const sidRing = new Float32Array(SID_RING_SIZE);
791
+ let sidRingWrite = 0; // next write position in sidRing
792
+ let sidRingRead = 0; // next read position in sidRing
793
+ let sidRingCount = 0; // samples currently in the ring
794
+ // Accumulator: how many emulated samples have passed since last WASM pull.
795
+ let sidSampleAccum = 0;
796
+ // Single staging buffer for per-frame audio delivered to ffmpeg/WebRTC.
797
+ const sidFrameBufMax = new Float32Array(MAX_AUDIO_SAMPLES_PER_ITER);
798
+ let sidFrameView = sidFrameBufMax.subarray(0, 1);
799
+
800
+ /** Pull one 4096-sample chunk from the WASM SID buffer into the JS ring. */
801
+ function pullSidBuffer() {
802
+ if (!exports || !heap || typeof exports.sid_getAudioBuffer !== 'function') return;
803
+ try {
804
+ const ptr = exports.sid_getAudioBuffer();
805
+ const base = ptr >> 2;
806
+ const src = heap.heapF32;
807
+ for (let i = 0; i < SID_BUFFER_SIZE; i++) {
808
+ sidRing[(sidRingWrite + i) % SID_RING_SIZE] = src[base + i];
809
+ }
810
+ sidRingWrite = (sidRingWrite + SID_BUFFER_SIZE) % SID_RING_SIZE;
811
+ sidRingCount = Math.min(sidRingCount + SID_BUFFER_SIZE, SID_RING_SIZE);
812
+ } catch (_) {}
813
+ }
814
+
815
+ /**
816
+ * Re-prime the JS SID ring with 2 full WASM buffer pulls (~8192 samples).
817
+ * Must be called after any emulator reset/cart-change once the WASM SID's
818
+ * own write cursor has been restarted — i.e. AFTER resetSidRing() zeros
819
+ * the JS ring state. Runs ~186ms of emulated pre-roll (not captured).
820
+ */
821
+ function primeSidRing() {
822
+ if (!exports || typeof exports.debugger_update !== 'function') return;
823
+ const primeMs = Math.ceil(SID_BUFFER_SIZE / (audioSampleRate / 1000)); // ~93ms
824
+ for (let p = 0; p < 2; p++) {
825
+ exports.debugger_update(primeMs);
826
+ pullSidBuffer();
827
+ }
828
+ }
829
+
830
+ /** Dequeue n samples from JS ring into sidFrameBufMax and expose sidFrameView. */
831
+ function dequeueSidFrame(n) {
832
+ const samplesNeeded = Math.max(1, Math.min(n, MAX_AUDIO_SAMPLES_PER_ITER));
833
+ sidFrameView = sidFrameBufMax.subarray(0, samplesNeeded);
834
+ // If the ring doesn't have a full frame yet, pad with silence rather than
835
+ // stalling — this can happen on the very first frames before the SID has
836
+ // had time to fill a full 4096-sample chunk.
837
+ if (sidRingCount < samplesNeeded) {
838
+ sidFrameBufMax.fill(0, 0, samplesNeeded);
839
+ return false;
840
+ }
841
+ for (let i = 0; i < samplesNeeded; i++) {
842
+ sidFrameBufMax[i] = sidRing[(sidRingRead + i) % SID_RING_SIZE];
843
+ }
844
+ sidRingRead = (sidRingRead + samplesNeeded) % SID_RING_SIZE;
845
+ sidRingCount -= samplesNeeded;
846
+ return true;
847
+ }
848
+
270
849
 
271
850
  // Resolve output path once — treat remote URLs verbatim, local file paths
272
851
  // should be resolved relative to the current working directory (process.cwd()).
@@ -317,49 +896,97 @@ export async function runHeadless(options = {}) {
317
896
  }
318
897
  }
319
898
 
899
+ // ── SID ring pre-prime ───────────────────────────────────────────────────
900
+ // Without pre-priming, the ring starts empty and the first ~4 frames are
901
+ // silent (sidSampleAccum hasn't crossed SID_BUFFER_SIZE yet). Worse, the
902
+ // ring drains to zero every ~4.65 frames (882 × 4 = 3528 < 4096) so the
903
+ // 5th frame after each pull would also be silent in steady state.
904
+ //
905
+ // Fix: run 2× SID_BUFFER_SIZE worth of emulation (~186ms) before the frame
906
+ // loop and pull both 4096-sample chunks into the JS ring. The ring then
907
+ // starts at 8192 samples — a comfortable ~9.3 frames of headroom — and
908
+ // never runs dry because subsequent pulls always arrive before it reaches 0.
909
+ //
910
+ // This emulation is "throwaway" pre-roll: the pixel buffer is not captured
911
+ // and the CPU state matches what a real C64 would be doing at startup.
912
+ if (audio || (webrtc && webrtcEncoder)) {
913
+ primeSidRing();
914
+ if (verbose) console.error(`[headless] SID ring primed: ${sidRingCount} samples ready`);
915
+ }
916
+
320
917
  // runStartTime is set AFTER ffmpeg starts so --duration counts from when
321
918
  // recording actually begins (after any RTMP probe/stabilisation delay).
322
919
  const runStartTime = Date.now();
323
- // When recording without an explicit --duration, run forever (endTime = Infinity).
324
- const endTime = record
920
+ const isStreamingMode = record || webrtc;
921
+ const endTime = isStreamingMode
325
922
  ? (durationSec ? runStartTime + durationSec * 1000 : Infinity)
326
923
  : null;
327
- let lastTick = Date.now();
328
- let windowStart = Date.now();
924
+
925
+ let windowStart = nowMonoMs();
329
926
  let windowCount = 0;
927
+ let lastStepAt = nowMonoMs();
330
928
 
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();
929
+ while (isStreamingMode ? Date.now() < endTime : frameCount < frames) {
335
930
  try {
336
931
  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);
932
+
933
+ // Capture frame start time BEFORE emulation so sleepMs accounts for
934
+ // ALL work in this iteration (emulation + audio + video push + ffmpeg).
935
+ const iterStart = nowMonoMs();
936
+ // Drive emulation with real wall-clock delta to avoid long-term A/V drift
937
+ // when actual loop FPS differs from target FPS.
938
+ const nowMs = nowMonoMs();
939
+ let emuDeltaMs = nowMs - lastStepAt;
940
+ lastStepAt = nowMs;
941
+ if (!emuDeltaMs || emuDeltaMs > MAX_DELTA_MS) emuDeltaMs = FALLBACK_DELTA_MS;
942
+
943
+ // Run a single full-frame emulation step.
944
+ // debugger_update() returns truthy when the emulator has completed a full
945
+ // video frame (VSync). c64.js gates its redraw on both this return value
946
+ // AND debugger_isRunning() — we mirror that here so we never push a stale
947
+ // or repeated pixel buffer into WebRTC during boot/reset sequences.
948
+ const frameReady = !!exports.debugger_update(emuDeltaMs);
949
+ const isRunning = !!exports.debugger_isRunning();
950
+
951
+ // ── Audio: pull from WASM SID → JS ring → per-frame slice ───────────
952
+ // Audio runs every frame regardless of frameReady/isRunning so the WebRTC
953
+ // audio clock stays continuous — gaps cause desync, not silence.
954
+ if (audio || (webrtc && webrtcEncoder)) {
955
+ const samplesThisIter = Math.max(1, Math.round((audioSampleRate * emuDeltaMs) / 1000));
956
+ sidSampleAccum += samplesThisIter;
957
+ while (sidSampleAccum >= SID_BUFFER_SIZE) {
958
+ sidSampleAccum -= SID_BUFFER_SIZE;
959
+ pullSidBuffer();
960
+ }
961
+ dequeueSidFrame(samplesThisIter); // fills sidFrameView (or silence)
350
962
  }
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);
963
+
964
+ // ── WebRTC: push video + audio into the live track ─────────────────
965
+ if (webrtc && webrtcEncoder) {
966
+ // Only push a video frame when the emulator confirms one is ready and
967
+ // is actively running — mirrors c64.js: if (update && !!debugger_isRunning())
968
+ if (frameReady && isRunning) {
969
+ const nowVideoMs = nowMonoMs();
970
+ if (nowVideoMs + 1 < nextVideoDueAtMs) {
971
+ videoFramesDroppedCap++;
972
+ videoFramesDroppedCapWindow++;
973
+ } else {
974
+ const overdueMs = Math.max(0, nowVideoMs - nextVideoDueAtMs);
975
+ if (overdueMs >= webrtcSendIntervalMs) {
976
+ const lateDrops = Math.floor(overdueMs / webrtcSendIntervalMs);
977
+ videoFramesDroppedLate += lateDrops;
978
+ videoFramesDroppedLateWindow += lateDrops;
979
+ nextVideoDueAtMs += lateDrops * webrtcSendIntervalMs;
980
+ }
981
+ const ptr = exports.c64_getPixelBuffer();
982
+ const rgba = heap.heapU8.subarray(ptr, ptr + 384 * 272 * 4);
983
+ webrtcEncoder.pushVideoFrame(rgba);
984
+ videoFramesSent++;
985
+ nextVideoDueAtMs = Math.max(nextVideoDueAtMs + webrtcSendIntervalMs, nowVideoMs + 1);
986
+ }
987
+ }
988
+
989
+ webrtcEncoder.pushAudioFrame(sidFrameView);
363
990
  }
364
991
 
365
992
  // Capture video frame and audio chunk, then write both atomically.
@@ -401,71 +1028,85 @@ export async function runHeadless(options = {}) {
401
1028
  break;
402
1029
  }
403
1030
  }
404
- try {
1031
+ if (frameReady && isRunning) {
405
1032
  const ptr = exports.c64_getPixelBuffer();
406
1033
  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
- }
1034
+ const audioChunk = audio ? sidFrameView : null;
425
1035
  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
1036
  }
438
1037
  }
1038
+ // Throttle to target FPS, then yield so input events are committed
1039
+ // to WASM before the next debugger_update.
1040
+ //
1041
+ // Ordering matters for input latency:
1042
+ // 1. setTimeout(sleepMs) — event loop sleeps; WebSocket 'message'
1043
+ // I/O callbacks fire during this window and call onInput() which
1044
+ // writes directly to WASM exports (keyboard_keyPressed, etc.)
1045
+ // 2. setImmediate yield — runs after all pending I/O callbacks,
1046
+ // guaranteeing any message that arrived right at the end of the
1047
+ // sleep is also committed before we continue.
1048
+ // 3. top of next iteration: debugger_update() reads the now-current
1049
+ // WASM input state.
1050
+ //
1051
+ // Worst-case input latency = one full frame (20ms @ 50fps): a keydown
1052
+ // that lands just AFTER step 2 waits until the following frame.
1053
+ // Average latency = half a frame (~10ms).
1054
+ const workMs = nowMonoMs() - iterStart;
1055
+ const sleepMs = Math.max(0, frameMs - workMs);
1056
+ if (sleepMs > 0) await new Promise((r) => setTimeout(r, sleepMs));
1057
+ await new Promise((r) => setImmediate(r)); // drain any remaining I/O callbacks
439
1058
  } catch (_) {
440
1059
  }
441
1060
  frameCount++;
442
1061
  // diagnostics
443
1062
  windowCount++;
444
1063
  if (windowCount >= 50) {
445
- const now = Date.now();
1064
+ const now = nowMonoMs();
446
1065
  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})`);
1066
+ const actualFps = windowCount / secs;
449
1067
  windowStart = now;
450
1068
  windowCount = 0;
1069
+ // Drift reporting: if actual FPS deviates more than 10% from target, warn.
1070
+ // Only emit when --log-events is set; never emit per-frame.
1071
+ if (logEvents || verbose) {
1072
+ const drift = actualFps - targetFps;
1073
+ const driftPct = Math.abs(drift / targetFps) * 100;
1074
+ if (driftPct > 10) {
1075
+ console.error(`[event] drift fps-actual=${actualFps.toFixed(1)} fps-target=${targetFps} drift=${drift > 0 ? '+' : ''}${drift.toFixed(1)} (${driftPct.toFixed(0)}%)`);
1076
+ }
1077
+ if (videoFramesDroppedLateWindow > 0 || videoFramesDroppedCapWindow > 0) {
1078
+ console.error(`[event] webrtc-video-drop sent=${videoFramesSent} late=${videoFramesDroppedLateWindow} cap=${videoFramesDroppedCapWindow} totalLate=${videoFramesDroppedLate} totalCap=${videoFramesDroppedCap} fpsCap=${webrtcSendFps}`);
1079
+ }
1080
+ }
1081
+ runtimeStats.videoFramesSent = videoFramesSent;
1082
+ runtimeStats.videoFramesDroppedLate = videoFramesDroppedLate;
1083
+ runtimeStats.videoFramesDroppedCap = videoFramesDroppedCap;
1084
+ const webrtcTelemetry = getWebrtcTelemetry();
1085
+ if (webrtcTelemetry) {
1086
+ runtimeStats.webrtcPeerCount = webrtcTelemetry.peerCount ?? null;
1087
+ runtimeStats.webrtcAvgRttMs = Number.isFinite(webrtcTelemetry.avgRttMs) ? webrtcTelemetry.avgRttMs : null;
1088
+ runtimeStats.webrtcSendDelayMsPerPacket = Number.isFinite(webrtcTelemetry.sendDelayMsPerPacket) ? webrtcTelemetry.sendDelayMsPerPacket : null;
1089
+ runtimeStats.webrtcEncodeMsPerFrame = Number.isFinite(webrtcTelemetry.encodeMsPerFrame) ? webrtcTelemetry.encodeMsPerFrame : null;
1090
+ runtimeStats.webrtcFramesSentPerSec = Number.isFinite(webrtcTelemetry.framesSentPerSec) ? webrtcTelemetry.framesSentPerSec : null;
1091
+ runtimeStats.webrtcFramesEncodedPerSec = Number.isFinite(webrtcTelemetry.framesEncodedPerSec) ? webrtcTelemetry.framesEncodedPerSec : null;
1092
+ runtimeStats.webrtcBytesSentPerSec = Number.isFinite(webrtcTelemetry.bytesSentPerSec) ? webrtcTelemetry.bytesSentPerSec : null;
1093
+ runtimeStats.webrtcQualityLimitation = webrtcTelemetry.qualityLimitation ?? null;
1094
+ }
1095
+ runtimeStats.sampledAt = Date.now();
1096
+ if (videoFramesDroppedLateWindow > 0 || videoFramesDroppedCapWindow > 0) {
1097
+ videoFramesDroppedLateWindow = 0;
1098
+ videoFramesDroppedCapWindow = 0;
1099
+ }
451
1100
  }
452
1101
  if (verify && frameCount % 60 === 0) {
453
1102
  const cycleCount = exports.c64_getCycleCount ? exports.c64_getCycleCount() : null;
454
1103
  out.push(JSON.stringify({pid: process.pid, frame: frameCount, cycles: cycleCount}));
455
- // Also emit a stderr heartbeat so interactive runs show progress.
456
1104
  try {
457
1105
  const pc = exports.c64_getPC ? exports.c64_getPC() : null;
458
1106
  console.error(`[headless] verify: frame=${frameCount} pc=${pc} cycles=${cycleCount}`);
459
1107
  } catch (_) {
460
1108
  }
461
- } else if (frameCount % 120 === 0) {
462
- //out.push(`HEADLESS: frame=${frameCount}`);
463
1109
  }
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
1110
  }
470
1111
 
471
1112
  const elapsed = (Date.now() - runStartTime) / 1000;
@@ -481,6 +1122,19 @@ export async function runHeadless(options = {}) {
481
1122
  }
482
1123
  }
483
1124
 
1125
+ // ── Shut down WebRTC server ───────────────────────────────────────────────
1126
+ if (webrtcServer) {
1127
+ try {
1128
+ await webrtcServer.close();
1129
+ if (verbose) console.error('[headless] webrtc server closed');
1130
+ } catch (e) {
1131
+ console.error('[headless] webrtc server close error:', e && e.message ? e.message : e);
1132
+ }
1133
+ }
1134
+
1135
+ // ── Log file teardown ──────────────────────────────────────────────────────
1136
+ _teardownLogFile();
1137
+
484
1138
  if (record && ffmpegRunner) {
485
1139
  // Clear audio interval if it was used (currently null/no-op)
486
1140
  if (audioInterval) {
@@ -539,4 +1193,3 @@ try {
539
1193
  } catch (e) {
540
1194
  // ignore errors in CLI wrapper detection
541
1195
  }
542
-