c64-ready 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +70 -62
  2. package/bin/headless.mjs +1 -1
  3. package/dist/assets/{CHANGELOG-CPlXKLCV.js → CHANGELOG-0a7A8Ekq.js} +113 -1
  4. package/dist/assets/index-BESofQoh.js +627 -0
  5. package/dist/games/cartridges/goat-beat.crt +0 -0
  6. package/dist/index.html +1 -1
  7. package/dist-ts/emulator/c64-emulator.d.ts +3 -0
  8. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  9. package/dist-ts/emulator/c64-emulator.js +36 -4
  10. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  11. package/dist-ts/emulator/crt-info.d.ts +61 -0
  12. package/dist-ts/emulator/crt-info.d.ts.map +1 -0
  13. package/dist-ts/emulator/crt-info.js +190 -0
  14. package/dist-ts/emulator/crt-info.js.map +1 -0
  15. package/dist-ts/emulator/input.d.ts +96 -0
  16. package/dist-ts/emulator/input.d.ts.map +1 -1
  17. package/dist-ts/emulator/input.js +549 -4
  18. package/dist-ts/emulator/input.js.map +1 -1
  19. package/dist-ts/headless/c64-headless.d.ts +1 -0
  20. package/dist-ts/headless/c64-headless.d.ts.map +1 -1
  21. package/dist-ts/headless/c64-headless.js +5 -0
  22. package/dist-ts/headless/c64-headless.js.map +1 -1
  23. package/dist-ts/types/emulator.d.ts +2 -1
  24. package/dist-ts/types/emulator.d.ts.map +1 -1
  25. package/package.json +1 -1
  26. package/public/games/cartridges/goat-beat.crt +0 -0
  27. package/src/emulator/c64-emulator.ts +37 -7
  28. package/src/emulator/crt-info.ts +35 -23
  29. package/src/emulator/input.ts +239 -19
  30. package/src/headless/c64-headless.ts +5 -0
  31. package/src/headless/headless-cli.mjs +462 -249
  32. package/src/headless/input-server.mjs +649 -278
  33. package/src/headless/webrtc-server.mjs +218 -71
  34. package/src/main.ts +30 -4
  35. package/src/player/c64-player.ts +121 -40
  36. package/src/player/input-handler.ts +8 -0
  37. package/src/player/styles/ui-controller.css +103 -21
  38. package/src/player/ui-controller.ts +186 -23
  39. package/src/types/emulator.ts +1 -1
  40. package/dist/assets/index-Ckbi7gQo.js +0 -535
@@ -56,7 +56,9 @@ function buildIceServers({
56
56
  credential: turnPassword,
57
57
  });
58
58
  } else if (turnUrls.length > 0 && verbose) {
59
- console.error('[webrtc] ICE_TURN_URLS provided without ICE_TURN_USERNAME/ICE_TURN_PASSWORD; skipping TURN');
59
+ console.error(
60
+ '[webrtc] ICE_TURN_URLS provided without ICE_TURN_USERNAME/ICE_TURN_PASSWORD; skipping TURN',
61
+ );
60
62
  }
61
63
 
62
64
  if (iceServers.length === 0) {
@@ -67,7 +69,9 @@ function buildIceServers({
67
69
  const stunCount = stunUrls.length;
68
70
  const turnCount = turnUrls.length;
69
71
  const turnEnabled = turnUrls.length > 0 && turnUsername && turnPassword;
70
- console.error(`[webrtc] ICE config stunUrls=${stunCount} turnUrls=${turnCount} turnEnabled=${turnEnabled ? 'yes' : 'no'}`);
72
+ console.error(
73
+ `[webrtc] ICE config stunUrls=${stunCount} turnUrls=${turnCount} turnEnabled=${turnEnabled ? 'yes' : 'no'}`,
74
+ );
71
75
  }
72
76
 
73
77
  return iceServers;
@@ -79,7 +83,7 @@ function buildIceServers({
79
83
  * @param {boolean} [opts.verbose=false] Log state changes to stderr
80
84
  * @param {number} [opts.inputPort=9001] Port the input WebSocket listens on
81
85
  * (embedded in the browser page)
82
- * @param {number} [opts.maxSpectators=3] Maximum number of spectator connections
86
+ * @param {number} [opts.maxSpectators=10] Maximum number of spectator connections
83
87
  * (not counting the 2 player slots).
84
88
  * When the limit is reached, new WebRTC
85
89
  * connections are rejected immediately with
@@ -95,6 +99,8 @@ function buildIceServers({
95
99
  * Attach tracks here: pc.addTrack(videoTrack, stream)
96
100
  * @param {(pc: RTCPeerConnection) => void} [opts.onPeerConnected]
97
101
  * Called once ICE reaches 'connected' or 'completed'.
102
+ * @param {(payload: { msg: any, remoteAddr: string, sessionId: string|null, send: (msg: any) => void }) => boolean | void} [opts.onDataChannelInput]
103
+ * Called for JSON messages received on the browser-created `input` data channel.
98
104
  * @returns {{ close: () => Promise<void> }}
99
105
  */
100
106
  export function createWebRTCServer({
@@ -102,7 +108,7 @@ export function createWebRTCServer({
102
108
  verbose = false,
103
109
  logEvents = false,
104
110
  inputPort = 9001,
105
- maxSpectators = 3,
111
+ maxSpectators = 10,
106
112
  minBitrateKbps = 200,
107
113
  maxBitrateKbps = 600,
108
114
  iceStunUrls,
@@ -111,6 +117,7 @@ export function createWebRTCServer({
111
117
  iceTurnPassword,
112
118
  onOffer,
113
119
  onPeerConnected,
120
+ onDataChannelInput,
114
121
  } = {}) {
115
122
  const iceServers = buildIceServers({
116
123
  iceStunUrls,
@@ -124,7 +131,9 @@ export function createWebRTCServer({
124
131
  function logEv(tag, fields = {}) {
125
132
  if (!logEvents) return;
126
133
  const ts = new Date().toISOString();
127
- const pairs = Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ');
134
+ const pairs = Object.entries(fields)
135
+ .map(([k, v]) => `${k}=${v}`)
136
+ .join(' ');
128
137
  console.error(`[event] ${ts} ${tag}${pairs ? ' ' + pairs : ''}`);
129
138
  }
130
139
  // Track all active peer connections so forceKeyframe() can reach them all.
@@ -145,12 +154,12 @@ export function createWebRTCServer({
145
154
  };
146
155
  let lastPressureLogAt = 0;
147
156
  let lastPressureSignature = '';
148
- const minBitrateKbpsSafe = Number.isFinite(minBitrateKbps) && minBitrateKbps > 0
149
- ? Math.round(minBitrateKbps)
150
- : 200;
151
- const maxBitrateKbpsSafe = Number.isFinite(maxBitrateKbps) && maxBitrateKbps > 0
152
- ? Math.max(minBitrateKbpsSafe, Math.round(maxBitrateKbps))
153
- : Math.max(minBitrateKbpsSafe, 600);
157
+ const minBitrateKbpsSafe =
158
+ Number.isFinite(minBitrateKbps) && minBitrateKbps > 0 ? Math.round(minBitrateKbps) : 200;
159
+ const maxBitrateKbpsSafe =
160
+ Number.isFinite(maxBitrateKbps) && maxBitrateKbps > 0
161
+ ? Math.max(minBitrateKbpsSafe, Math.round(maxBitrateKbps))
162
+ : Math.max(minBitrateKbpsSafe, 600);
154
163
 
155
164
  // Total capacity = 2 player slots + maxSpectators.
156
165
  // We track all in-flight WS connections (including those not yet ICE-connected)
@@ -167,7 +176,10 @@ export function createWebRTCServer({
167
176
  ...extra,
168
177
  };
169
178
  logEv(tag, snapshot);
170
- if (verbose) console.error(`[webrtc-load] ${tag} active=${snapshot.active} pending=${snapshot.pending} total=${snapshot.total}/${snapshot.max}`);
179
+ if (verbose)
180
+ console.error(
181
+ `[webrtc-load] ${tag} active=${snapshot.active} pending=${snapshot.pending} total=${snapshot.total}/${snapshot.max}`,
182
+ );
171
183
  }
172
184
 
173
185
  async function logRouteSnapshot(pc, remoteAddr) {
@@ -177,14 +189,21 @@ export function createWebRTCServer({
177
189
  const localById = new Map();
178
190
  const remoteById = new Map();
179
191
  for (const stat of report.values()) {
180
- if (stat.type === 'candidate-pair' && stat.nominated && (stat.state === 'succeeded' || stat.selected)) selected = stat;
192
+ if (
193
+ stat.type === 'candidate-pair' &&
194
+ stat.nominated &&
195
+ (stat.state === 'succeeded' || stat.selected)
196
+ )
197
+ selected = stat;
181
198
  if (stat.type === 'local-candidate') localById.set(stat.id, stat);
182
199
  if (stat.type === 'remote-candidate') remoteById.set(stat.id, stat);
183
200
  }
184
201
  if (!selected) return;
185
202
  const local = localById.get(selected.localCandidateId);
186
203
  const remote = remoteById.get(selected.remoteCandidateId);
187
- const rttMs = Number.isFinite(selected.currentRoundTripTime) ? Math.round(selected.currentRoundTripTime * 1000) : null;
204
+ const rttMs = Number.isFinite(selected.currentRoundTripTime)
205
+ ? Math.round(selected.currentRoundTripTime * 1000)
206
+ : null;
188
207
  logEv('webrtc-route', {
189
208
  addr: remoteAddr,
190
209
  protocol: selected.protocol ?? '-',
@@ -194,7 +213,9 @@ export function createWebRTCServer({
194
213
  rttMs: rttMs ?? '-',
195
214
  });
196
215
  if (verbose) {
197
- console.error(`[webrtc-route] addr=${remoteAddr} protocol=${selected.protocol ?? '-'} local=${local?.candidateType ?? '-'} remote=${remote?.candidateType ?? '-'} net=${local?.networkType ?? '-'} rtt=${rttMs ?? '-'}ms`);
216
+ console.error(
217
+ `[webrtc-route] addr=${remoteAddr} protocol=${selected.protocol ?? '-'} local=${local?.candidateType ?? '-'} remote=${remote?.candidateType ?? '-'} net=${local?.networkType ?? '-'} rtt=${rttMs ?? '-'}ms`,
218
+ );
198
219
  }
199
220
  } catch (_) {
200
221
  // Best-effort diagnostics only
@@ -221,7 +242,11 @@ export function createWebRTCServer({
221
242
  let selected = null;
222
243
  let outboundVideo = null;
223
244
  for (const stat of report.values()) {
224
- if (stat.type === 'candidate-pair' && stat.nominated && (stat.state === 'succeeded' || stat.selected)) {
245
+ if (
246
+ stat.type === 'candidate-pair' &&
247
+ stat.nominated &&
248
+ (stat.state === 'succeeded' || stat.selected)
249
+ ) {
225
250
  selected = stat;
226
251
  }
227
252
  if (stat.type === 'outbound-rtp' && stat.kind === 'video' && !stat.isRemote) {
@@ -241,33 +266,65 @@ export function createWebRTCServer({
241
266
  const current = {
242
267
  timestampMs: Number.isFinite(outboundVideo.timestamp) ? outboundVideo.timestamp : nowWall,
243
268
  framesSent: Number.isFinite(outboundVideo.framesSent) ? outboundVideo.framesSent : null,
244
- framesEncoded: Number.isFinite(outboundVideo.framesEncoded) ? outboundVideo.framesEncoded : null,
269
+ framesEncoded: Number.isFinite(outboundVideo.framesEncoded)
270
+ ? outboundVideo.framesEncoded
271
+ : null,
245
272
  bytesSent: Number.isFinite(outboundVideo.bytesSent) ? outboundVideo.bytesSent : null,
246
- packetsSent: Number.isFinite(outboundVideo.packetsSent) ? outboundVideo.packetsSent : null,
247
- totalPacketSendDelay: Number.isFinite(outboundVideo.totalPacketSendDelay) ? outboundVideo.totalPacketSendDelay : null,
248
- totalEncodeTime: Number.isFinite(outboundVideo.totalEncodeTime) ? outboundVideo.totalEncodeTime : null,
273
+ packetsSent: Number.isFinite(outboundVideo.packetsSent)
274
+ ? outboundVideo.packetsSent
275
+ : null,
276
+ totalPacketSendDelay: Number.isFinite(outboundVideo.totalPacketSendDelay)
277
+ ? outboundVideo.totalPacketSendDelay
278
+ : null,
279
+ totalEncodeTime: Number.isFinite(outboundVideo.totalEncodeTime)
280
+ ? outboundVideo.totalEncodeTime
281
+ : null,
249
282
  };
250
283
 
251
284
  const prev = peerStatsPrev.get(pc);
252
285
  peerStatsPrev.set(pc, current);
253
286
  if (!prev) continue;
254
287
 
255
- if (current.framesSent != null && prev.framesSent != null && current.framesSent >= prev.framesSent) {
288
+ if (
289
+ current.framesSent != null &&
290
+ prev.framesSent != null &&
291
+ current.framesSent >= prev.framesSent
292
+ ) {
256
293
  deltaFramesSent += current.framesSent - prev.framesSent;
257
294
  }
258
- if (current.framesEncoded != null && prev.framesEncoded != null && current.framesEncoded >= prev.framesEncoded) {
295
+ if (
296
+ current.framesEncoded != null &&
297
+ prev.framesEncoded != null &&
298
+ current.framesEncoded >= prev.framesEncoded
299
+ ) {
259
300
  deltaFramesEncoded += current.framesEncoded - prev.framesEncoded;
260
301
  }
261
- if (current.bytesSent != null && prev.bytesSent != null && current.bytesSent >= prev.bytesSent) {
302
+ if (
303
+ current.bytesSent != null &&
304
+ prev.bytesSent != null &&
305
+ current.bytesSent >= prev.bytesSent
306
+ ) {
262
307
  deltaBytesSent += current.bytesSent - prev.bytesSent;
263
308
  }
264
- if (current.packetsSent != null && prev.packetsSent != null && current.packetsSent >= prev.packetsSent) {
309
+ if (
310
+ current.packetsSent != null &&
311
+ prev.packetsSent != null &&
312
+ current.packetsSent >= prev.packetsSent
313
+ ) {
265
314
  deltaPacketsSent += current.packetsSent - prev.packetsSent;
266
315
  }
267
- if (current.totalPacketSendDelay != null && prev.totalPacketSendDelay != null && current.totalPacketSendDelay >= prev.totalPacketSendDelay) {
316
+ if (
317
+ current.totalPacketSendDelay != null &&
318
+ prev.totalPacketSendDelay != null &&
319
+ current.totalPacketSendDelay >= prev.totalPacketSendDelay
320
+ ) {
268
321
  deltaPacketSendDelay += current.totalPacketSendDelay - prev.totalPacketSendDelay;
269
322
  }
270
- if (current.totalEncodeTime != null && prev.totalEncodeTime != null && current.totalEncodeTime >= prev.totalEncodeTime) {
323
+ if (
324
+ current.totalEncodeTime != null &&
325
+ prev.totalEncodeTime != null &&
326
+ current.totalEncodeTime >= prev.totalEncodeTime
327
+ ) {
271
328
  deltaEncodeTime += current.totalEncodeTime - prev.totalEncodeTime;
272
329
  }
273
330
  } catch (_) {
@@ -278,9 +335,11 @@ export function createWebRTCServer({
278
335
  const sampleIntervalS = 5;
279
336
  senderTelemetry.sampledAt = nowWall;
280
337
  senderTelemetry.peerCount = peerCount;
281
- senderTelemetry.avgRttMs = rttCount > 0 ? (rttSum / rttCount) : null;
282
- senderTelemetry.sendDelayMsPerPacket = deltaPacketsSent > 0 ? (deltaPacketSendDelay / deltaPacketsSent) * 1000 : null;
283
- senderTelemetry.encodeMsPerFrame = deltaFramesEncoded > 0 ? (deltaEncodeTime / deltaFramesEncoded) * 1000 : null;
338
+ senderTelemetry.avgRttMs = rttCount > 0 ? rttSum / rttCount : null;
339
+ senderTelemetry.sendDelayMsPerPacket =
340
+ deltaPacketsSent > 0 ? (deltaPacketSendDelay / deltaPacketsSent) * 1000 : null;
341
+ senderTelemetry.encodeMsPerFrame =
342
+ deltaFramesEncoded > 0 ? (deltaEncodeTime / deltaFramesEncoded) * 1000 : null;
284
343
  senderTelemetry.framesSentPerSec = deltaFramesSent / sampleIntervalS;
285
344
  senderTelemetry.framesEncodedPerSec = deltaFramesEncoded / sampleIntervalS;
286
345
  senderTelemetry.bytesSentPerSec = deltaBytesSent / sampleIntervalS;
@@ -305,11 +364,12 @@ export function createWebRTCServer({
305
364
  const bitrateKbps = Number.isFinite(senderTelemetry.bytesSentPerSec)
306
365
  ? ((senderTelemetry.bytesSentPerSec * 8) / 1000).toFixed(0)
307
366
  : '-';
308
- const qualitySummary = Object.entries(qualityCounts)
309
- .filter(([, count]) => Number.isFinite(count) && count > 0)
310
- .sort((a, b) => b[1] - a[1])
311
- .map(([reason, count]) => `${reason}:${count}`)
312
- .join('|') || 'none:0';
367
+ const qualitySummary =
368
+ Object.entries(qualityCounts)
369
+ .filter(([, count]) => Number.isFinite(count) && count > 0)
370
+ .sort((a, b) => b[1] - a[1])
371
+ .map(([reason, count]) => `${reason}:${count}`)
372
+ .join('|') || 'none:0';
313
373
 
314
374
  logEv('webrtc-sender-telemetry', {
315
375
  peers: peerCount,
@@ -323,13 +383,22 @@ export function createWebRTCServer({
323
383
  });
324
384
 
325
385
  const pressureReasons = [];
326
- if (Number.isFinite(senderTelemetry.framesSentPerSec) && senderTelemetry.framesSentPerSec < 44) {
386
+ if (
387
+ Number.isFinite(senderTelemetry.framesSentPerSec) &&
388
+ senderTelemetry.framesSentPerSec < 44
389
+ ) {
327
390
  pressureReasons.push('low-fps-out');
328
391
  }
329
- if (Number.isFinite(senderTelemetry.encodeMsPerFrame) && senderTelemetry.encodeMsPerFrame > 12) {
392
+ if (
393
+ Number.isFinite(senderTelemetry.encodeMsPerFrame) &&
394
+ senderTelemetry.encodeMsPerFrame > 12
395
+ ) {
330
396
  pressureReasons.push('slow-encode');
331
397
  }
332
- if (Number.isFinite(senderTelemetry.sendDelayMsPerPacket) && senderTelemetry.sendDelayMsPerPacket > 4) {
398
+ if (
399
+ Number.isFinite(senderTelemetry.sendDelayMsPerPacket) &&
400
+ senderTelemetry.sendDelayMsPerPacket > 4
401
+ ) {
333
402
  pressureReasons.push('packet-send-delay');
334
403
  }
335
404
  if ((qualityCounts.cpu ?? 0) > 0) pressureReasons.push('quality-cpu');
@@ -338,7 +407,8 @@ export function createWebRTCServer({
338
407
  if (pressureReasons.length > 0) {
339
408
  const signature = pressureReasons.join('|');
340
409
  const now = Date.now();
341
- const shouldLogPressure = signature !== lastPressureSignature || (now - lastPressureLogAt) >= 30_000;
410
+ const shouldLogPressure =
411
+ signature !== lastPressureSignature || now - lastPressureLogAt >= 30_000;
342
412
  if (shouldLogPressure) {
343
413
  lastPressureSignature = signature;
344
414
  lastPressureLogAt = now;
@@ -382,7 +452,9 @@ export function createWebRTCServer({
382
452
  newAddr: controller.remoteAddr ?? '-',
383
453
  source,
384
454
  });
385
- try { previous.closePeer?.('session-replaced'); } catch (_) {}
455
+ try {
456
+ previous.closePeer?.('session-replaced');
457
+ } catch (_) {}
386
458
  }
387
459
 
388
460
  peerBySession.set(sessionKey, controller);
@@ -398,6 +470,9 @@ export function createWebRTCServer({
398
470
  if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
399
471
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
400
472
  res.end(buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe, iceServers));
473
+ } else if (req.method === 'GET' && req.url === '/ice-config') {
474
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
475
+ res.end(JSON.stringify({ iceServers }));
401
476
  } else if (req.url === '/favicon.ico') {
402
477
  // Return a minimal 1×1 transparent ICO so browsers don't log a 404
403
478
  res.writeHead(204);
@@ -436,14 +511,15 @@ export function createWebRTCServer({
436
511
 
437
512
  wss.on('connection', (ws, req) => {
438
513
  ws._sigAlive = true; // initialise alive flag
439
- ws.on('pong', () => { ws._sigAlive = true; });
514
+ ws.on('pong', () => {
515
+ ws._sigAlive = true;
516
+ });
440
517
  const remoteAddr = req.socket.remoteAddress;
441
518
  let initialSessionId = null;
442
519
  try {
443
520
  const reqUrl = new URL(req.url || '/', 'http://localhost');
444
- initialSessionId = reqUrl.searchParams.get('sid')
445
- || reqUrl.searchParams.get('sessionId')
446
- || null;
521
+ initialSessionId =
522
+ reqUrl.searchParams.get('sid') || reqUrl.searchParams.get('sessionId') || null;
447
523
  } catch (_) {}
448
524
 
449
525
  // ── Capacity gate ─────────────────────────────────────────────────────────
@@ -451,15 +527,23 @@ export function createWebRTCServer({
451
527
  // Players take 2 of the MAX_CONNECTIONS slots; remaining slots are spectators.
452
528
  const currentTotal = activePeers.size + pendingPeers;
453
529
  if (currentTotal >= MAX_CONNECTIONS) {
454
- console.error(`[webrtc] capacity full (${currentTotal}/${MAX_CONNECTIONS}) — rejecting ${remoteAddr}`);
455
- logEv('webrtc-capacity-full', { addr: remoteAddr, current: currentTotal, max: MAX_CONNECTIONS });
530
+ console.error(
531
+ `[webrtc] capacity full (${currentTotal}/${MAX_CONNECTIONS}) — rejecting ${remoteAddr}`,
532
+ );
533
+ logEv('webrtc-capacity-full', {
534
+ addr: remoteAddr,
535
+ current: currentTotal,
536
+ max: MAX_CONNECTIONS,
537
+ });
456
538
  try {
457
- ws.send(JSON.stringify({
458
- type: 'capacity-full',
459
- current: currentTotal,
460
- max: MAX_CONNECTIONS,
461
- maxSpectators,
462
- }));
539
+ ws.send(
540
+ JSON.stringify({
541
+ type: 'capacity-full',
542
+ current: currentTotal,
543
+ max: MAX_CONNECTIONS,
544
+ maxSpectators,
545
+ }),
546
+ );
463
547
  } catch (_) {}
464
548
  ws.close();
465
549
  return;
@@ -490,7 +574,10 @@ export function createWebRTCServer({
490
574
  let disconnectTimer = null;
491
575
 
492
576
  function clearDisconnectTimer() {
493
- if (disconnectTimer) { clearTimeout(disconnectTimer); disconnectTimer = null; }
577
+ if (disconnectTimer) {
578
+ clearTimeout(disconnectTimer);
579
+ disconnectTimer = null;
580
+ }
494
581
  }
495
582
 
496
583
  // Track whether this peer has ever reached ICE connected (to manage pendingPeers correctly).
@@ -506,7 +593,7 @@ export function createWebRTCServer({
506
593
  const errName = err?.name ?? 'Error';
507
594
  const errMsg = err?.message ?? String(err);
508
595
  console.error(
509
- `[webrtc] addIceCandidate failed (${source}) addr=${remoteAddr} hasRemoteDescription=${hasRemoteDescription} signalingState=${signalingState} err=${errName}: ${errMsg}`
596
+ `[webrtc] addIceCandidate failed (${source}) addr=${remoteAddr} hasRemoteDescription=${hasRemoteDescription} signalingState=${signalingState} err=${errName}: ${errMsg}`,
510
597
  );
511
598
  logEv('webrtc-ice-candidate-error', {
512
599
  addr: remoteAddr,
@@ -529,6 +616,15 @@ export function createWebRTCServer({
529
616
  function closePeer(reason) {
530
617
  clearDisconnectTimer();
531
618
  const wasActive = activePeers.delete(pc);
619
+ const detail = {
620
+ reason,
621
+ iceState: controller.iceState,
622
+ everConnected,
623
+ connected: controller.connected,
624
+ sessionId: controller.sessionKey ?? null,
625
+ signalingState: pc.signalingState,
626
+ connectionState: pc.connectionState,
627
+ };
532
628
  peerStatsPrev.delete(pc);
533
629
  if (controller.sessionKey) {
534
630
  const mapped = peerBySession.get(controller.sessionKey);
@@ -536,14 +632,20 @@ export function createWebRTCServer({
536
632
  }
537
633
  peerControllers.delete(controller);
538
634
  // Decrement pendingPeers only if this peer never made it to ICE connected.
539
- if (!wasActive && !everConnected) { if (pendingPeers > 0) pendingPeers--; }
540
- console.error(`[webrtc] closing peer (${remoteAddr}): ${reason}`);
541
- logEv('webrtc-peer-closed', { addr: remoteAddr, reason });
635
+ if (!wasActive && !everConnected) {
636
+ if (pendingPeers > 0) pendingPeers--;
637
+ }
638
+ console.error(
639
+ `[webrtc] closing peer (${remoteAddr}): ${reason} ice=${detail.iceState} everConnected=${detail.everConnected} signaling=${detail.signalingState} pc=${detail.connectionState}`,
640
+ );
641
+ logEv('webrtc-peer-closed', { addr: remoteAddr, ...detail });
542
642
  logLoadSnapshot('webrtc-load-change', { reason: `peer-closed:${reason}` });
543
643
  // Tell the browser the stream died so it can reconnect immediately
544
644
  // rather than sitting on a frozen frame.
545
645
  if (ws.readyState === ws.OPEN) {
546
- try { ws.send(JSON.stringify({ type: 'peer-closed', reason })); } catch (_) {}
646
+ try {
647
+ ws.send(JSON.stringify({ type: 'peer-closed', ...detail }));
648
+ } catch (_) {}
547
649
  }
548
650
  pc.close();
549
651
  }
@@ -557,6 +659,35 @@ export function createWebRTCServer({
557
659
  }
558
660
  };
559
661
 
662
+ pc.ondatachannel = ({ channel }) => {
663
+ if (!channel || channel.label !== 'input') return;
664
+
665
+ channel.onmessage = ({ data }) => {
666
+ let msg;
667
+ try {
668
+ msg = JSON.parse(typeof data === 'string' ? data : data.toString('utf8'));
669
+ } catch {
670
+ if (verbose) console.error(`[webrtc] bad datachannel JSON from ${remoteAddr}`);
671
+ return;
672
+ }
673
+
674
+ try {
675
+ onDataChannelInput?.({
676
+ msg,
677
+ remoteAddr,
678
+ sessionId: controller.sessionKey ?? null,
679
+ send(reply) {
680
+ if (!reply) return;
681
+ if (channel.readyState !== 'open') return;
682
+ channel.send(JSON.stringify(reply));
683
+ },
684
+ });
685
+ } catch (err) {
686
+ console.error(`[webrtc] datachannel input error (${remoteAddr}): ${err?.message ?? err}`);
687
+ }
688
+ };
689
+ };
690
+
560
691
  pc.oniceconnectionstatechange = () => {
561
692
  const s = pc.iceConnectionState;
562
693
  controller.iceState = s;
@@ -612,7 +743,11 @@ export function createWebRTCServer({
612
743
 
613
744
  try {
614
745
  if (msg.type === 'offer') {
615
- bindControllerSession(controller, msg.sessionId ?? msg.sid ?? msg.clientSessionId ?? null, 'offer');
746
+ bindControllerSession(
747
+ controller,
748
+ msg.sessionId ?? msg.sid ?? msg.clientSessionId ?? null,
749
+ 'offer',
750
+ );
616
751
  await pc.setRemoteDescription(msg);
617
752
  await flushRemoteCandidates('post-offer');
618
753
 
@@ -633,15 +768,12 @@ export function createWebRTCServer({
633
768
  let sdp = answer.sdp;
634
769
  if (sdp) {
635
770
  // Find VP8 payload type in the offer and append fmtp constraints
636
- sdp = sdp.replace(
637
- /(a=rtpmap:(\d+) VP8\/\d+\r?\n)/,
638
- (match, line, pt) => {
639
- const minKbps = Math.max(50, minBitrateKbpsSafe);
640
- const maxKbps = Math.max(minKbps, maxBitrateKbpsSafe);
641
- const fmtp = `a=fmtp:${pt} x-google-min-bitrate=${minKbps};x-google-max-bitrate=${maxKbps}\r\n`;
642
- return line + fmtp;
643
- }
644
- );
771
+ sdp = sdp.replace(/(a=rtpmap:(\d+) VP8\/\d+\r?\n)/, (match, line, pt) => {
772
+ const minKbps = Math.max(50, minBitrateKbpsSafe);
773
+ const maxKbps = Math.max(minKbps, maxBitrateKbpsSafe);
774
+ const fmtp = `a=fmtp:${pt} x-google-min-bitrate=${minKbps};x-google-max-bitrate=${maxKbps}\r\n`;
775
+ return line + fmtp;
776
+ });
645
777
  answer.sdp = sdp;
646
778
  }
647
779
 
@@ -651,12 +783,13 @@ export function createWebRTCServer({
651
783
  ws.send(JSON.stringify(pc.localDescription));
652
784
  }
653
785
  if (verbose) console.error(`[webrtc] answered offer from ${remoteAddr}`);
654
-
655
786
  } else if (msg.type === 'candidate' && msg.candidate) {
656
787
  if (!pc.remoteDescription) {
657
788
  pendingRemoteCandidates.push(msg.candidate);
658
789
  if (verbose) {
659
- console.error(`[webrtc] queued remote candidate (${pendingRemoteCandidates.length}) pending offer (${remoteAddr})`);
790
+ console.error(
791
+ `[webrtc] queued remote candidate (${pendingRemoteCandidates.length}) pending offer (${remoteAddr})`,
792
+ );
660
793
  }
661
794
  } else {
662
795
  await addRemoteCandidate(msg.candidate, 'live');
@@ -779,7 +912,12 @@ export function createWebRTCServer({
779
912
  }
780
913
 
781
914
  // ─── Embedded browser-side player page ──────────────────────────────────────
782
- function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600, iceServers = [{ urls: 'stun:stun.l.google.com:19302' }]) {
915
+ function buildBrowserHtml(
916
+ inputPort,
917
+ minBitrateKbps = 200,
918
+ maxBitrateKbps = 600,
919
+ iceServers = [{ urls: 'stun:stun.l.google.com:19302' }],
920
+ ) {
783
921
  const minKbps = Math.max(50, Math.round(minBitrateKbps));
784
922
  const maxKbps = Math.max(minKbps, Math.round(maxBitrateKbps));
785
923
  const iceServersJson = JSON.stringify(iceServers).replace(/</g, '\\u003c');
@@ -888,6 +1026,7 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600,
888
1026
  <button id="load-btn" title="Load a .crt cartridge file">📂 load .crt</button>
889
1027
  <button id="detach-btn" title="Eject cartridge → BASIC prompt" disabled>⏏ detach</button>
890
1028
  <button id="reset-btn" title="Hard reset (BASIC prompt)" disabled>↺ reset</button>
1029
+ <button id="reboot-btn" title="Re-instantiate emulator with no game loaded">⟲ reboot</button>
891
1030
  <span class="sep">|</span>
892
1031
  <button id="sync-btn" title="Flush video to live edge — use if display feels laggy">⟳ sync</button>
893
1032
  <span class="sep">|</span>
@@ -911,6 +1050,7 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600,
911
1050
  const loadBtn = document.getElementById('load-btn');
912
1051
  const detachBtn = document.getElementById('detach-btn');
913
1052
  const resetBtn = document.getElementById('reset-btn');
1053
+ const rebootBtn = document.getElementById('reboot-btn');
914
1054
  const syncBtn = document.getElementById('sync-btn');
915
1055
  const modeBtn = document.getElementById('mode-btn');
916
1056
  const fileInput = document.getElementById('file-input');
@@ -1240,12 +1380,18 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600,
1240
1380
  try {
1241
1381
  const msg = JSON.parse(data);
1242
1382
  // Cart lifecycle
1243
- if (msg.type === 'cart-loaded' || msg.type === 'machine-reset' || msg.type === 'cart-detached') {
1383
+ if (msg.type === 'cart-loaded' || msg.type === 'machine-reset' || msg.type === 'cart-detached' || msg.type === 'machine-rebooted') {
1244
1384
  blurAll();
1245
1385
  const cartName = msg.filename ? msg.filename.replace(/\\.crt$/i,'').replace(/[-_]/g,' ') : '';
1246
1386
  if (msg.type === 'cart-loaded') { setBadge(gameBadge, '🎮 ' + (cartName || 'game loaded'), 'ok'); setLoadStatus('loaded', 'ok'); detachBtn.disabled = false; resetBtn.disabled = false; }
1247
1387
  if (msg.type === 'cart-detached') { setBadge(gameBadge, 'no game', 'dim'); setLoadStatus('', ''); detachBtn.disabled = true; }
1248
1388
  if (msg.type === 'machine-reset') { setLoadStatus('reset', 'warn'); }
1389
+ if (msg.type === 'machine-rebooted') {
1390
+ setBadge(gameBadge, 'no game', 'dim');
1391
+ setLoadStatus('rebooted', 'warn');
1392
+ detachBtn.disabled = true;
1393
+ resetBtn.disabled = true;
1394
+ }
1249
1395
  // Reconnect the RTCPeerConnection entirely — this is the only
1250
1396
  // reliable way to clear the jitter buffer and decoder state that
1251
1397
  // accumulates during the ~1600ms cart-load gap. Anything less
@@ -1328,6 +1474,7 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600,
1328
1474
  });
1329
1475
  detachBtn.addEventListener('click', () => { sendInput({ type: 'detach-crt' }); setLoadStatus('detaching…', 'warn'); blurAll(); });
1330
1476
  resetBtn.addEventListener('click', () => { sendInput({ type: 'hard-reset' }); setLoadStatus('resetting…', 'warn'); blurAll(); });
1477
+ rebootBtn.addEventListener('click', () => { sendInput({ type: 'reboot' }); setLoadStatus('rebooting…', 'warn'); blurAll(); });
1331
1478
  syncBtn.addEventListener('click', () => {
1332
1479
  const wasMuted = videoEl.muted;
1333
1480
  connectWebRTC();
package/src/main.ts CHANGED
@@ -45,7 +45,7 @@ player
45
45
  .catch((err) => {
46
46
  console.error(err);
47
47
  renderer.setError('ERROR');
48
- status.textContent = `Error: ${err}`;
48
+ status.textContent = `Error: ${normalizeErrorMessage(String(err))}`;
49
49
  status.style.color = '#f44';
50
50
  });
51
51
 
@@ -84,11 +84,23 @@ window.addEventListener('c64-load-file', async (e: Event) => {
84
84
  } catch (err) {
85
85
  console.error(err);
86
86
  renderer.setError('LOAD ERROR');
87
- status.textContent = `Load error: ${err}`;
87
+ status.textContent = `Load error: ${normalizeErrorMessage(String(err))}`;
88
88
  status.style.color = '#f44';
89
89
  }
90
90
  });
91
91
 
92
+ window.addEventListener('c64-controller-connected', (e: Event) => {
93
+ const detail = (e as CustomEvent).detail;
94
+ status.textContent = `Controller Connected: ${detail.index} - ${detail.name}`;
95
+ status.style.color = '#9ecbff';
96
+ });
97
+
98
+ window.addEventListener('c64-controller-disconnected', (e: Event) => {
99
+ const detail = (e as CustomEvent).detail;
100
+ status.textContent = `Controller Disconnected : ${detail.index} - ${detail.name}`;
101
+ status.style.color = '#9ecbff';
102
+ })
103
+
92
104
  window.addEventListener('c64-load-tool', async (e: Event) => {
93
105
  const detail = (e as CustomEvent).detail as
94
106
  | { name?: string; url?: string; type?: string }
@@ -104,7 +116,7 @@ window.addEventListener('c64-load-tool', async (e: Event) => {
104
116
  } catch (err) {
105
117
  console.error(err);
106
118
  renderer.setError('LOAD ERROR');
107
- status.textContent = `Tool load error: ${err}`;
119
+ status.textContent = `Tool load error: ${normalizeErrorMessage(String(err))}`;
108
120
  status.style.color = '#f44';
109
121
  }
110
122
  });
@@ -114,7 +126,7 @@ window.addEventListener('c64-load-error', (e: Event) => {
114
126
  const detail = (e as CustomEvent).detail as
115
127
  | { error?: string; url?: string; file?: string; type?: string }
116
128
  | undefined;
117
- const msg = detail?.error ?? 'Unknown load error';
129
+ const msg = normalizeErrorMessage(detail?.error ?? 'Unknown load error');
118
130
  console.error('C64 load error event:', detail);
119
131
  renderer.setError('LOAD ERROR');
120
132
  status.textContent = `Load error: ${msg}`;
@@ -130,3 +142,17 @@ window.addEventListener('c64-load-info', (e: Event) => {
130
142
  status.style.color = detail.mode === 'warning' ? '#f9c74f' : '#9ecbff';
131
143
  console.info('C64 load info event:', detail);
132
144
  });
145
+
146
+ window.addEventListener('c64-reboot', () => {
147
+ status.textContent = 'Emulator rebooted. Load a cartridge to continue.';
148
+ status.style.color = '#9ecbff';
149
+ renderer.hideLoader(0);
150
+ });
151
+
152
+ function normalizeErrorMessage(msg: string): string {
153
+ let out = String(msg ?? '').trim();
154
+ while (/^(uncaught\s+)?error\s*:\s*/i.test(out)) {
155
+ out = out.replace(/^(uncaught\s+)?error\s*:\s*/i, '').trim();
156
+ }
157
+ return out || 'Unknown load error';
158
+ }