c64-ready 0.11.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +10 -2
  2. package/dist/assets/CHANGELOG-B12WeYEc.js +116 -0
  3. package/dist/assets/index-fUdEY2R7.js +610 -0
  4. package/dist/index.html +1 -1
  5. package/dist/tools/anykey-c64.prg +0 -0
  6. package/dist/tools/tools.json +6 -0
  7. package/dist-ts/emulator/c64-emulator.d.ts +3 -0
  8. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  9. package/dist-ts/emulator/c64-emulator.js +36 -4
  10. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  11. package/dist-ts/emulator/crt-info.d.ts +61 -0
  12. package/dist-ts/emulator/crt-info.d.ts.map +1 -0
  13. package/dist-ts/emulator/crt-info.js +190 -0
  14. package/dist-ts/emulator/crt-info.js.map +1 -0
  15. package/dist-ts/emulator/input.d.ts +96 -0
  16. package/dist-ts/emulator/input.d.ts.map +1 -1
  17. package/dist-ts/emulator/input.js +549 -4
  18. package/dist-ts/emulator/input.js.map +1 -1
  19. package/dist-ts/headless/c64-headless.d.ts +1 -0
  20. package/dist-ts/headless/c64-headless.d.ts.map +1 -1
  21. package/dist-ts/headless/c64-headless.js +5 -0
  22. package/dist-ts/headless/c64-headless.js.map +1 -1
  23. package/dist-ts/types/emulator.d.ts +2 -1
  24. package/dist-ts/types/emulator.d.ts.map +1 -1
  25. package/package.json +1 -1
  26. package/src/emulator/c64-emulator.ts +34 -2
  27. package/src/emulator/crt-info.ts +35 -23
  28. package/src/emulator/input.ts +5 -2
  29. package/src/headless/c64-headless.ts +5 -0
  30. package/src/headless/c64-key-map.mjs +1 -1
  31. package/src/headless/headless-cli.mjs +410 -232
  32. package/src/headless/input-server.mjs +463 -198
  33. package/src/headless/webrtc-server.mjs +235 -70
  34. package/src/main.ts +37 -3
  35. package/src/player/c64-player.ts +121 -37
  36. package/src/player/styles/ui-controller.css +114 -21
  37. package/src/player/ui-controller.ts +176 -8
  38. package/dist/assets/CHANGELOG-CPMeNyjb.js +0 -261
  39. package/dist/assets/index-CeQto0sd.js +0 -499
@@ -25,6 +25,58 @@ import wrtc from '@roamhq/wrtc';
25
25
 
26
26
  const { RTCPeerConnection } = wrtc;
27
27
 
28
+ function parseCsvList(raw) {
29
+ return String(raw ?? '')
30
+ .split(',')
31
+ .map((part) => part.trim())
32
+ .filter(Boolean);
33
+ }
34
+
35
+ function buildIceServers({
36
+ iceStunUrls,
37
+ iceTurnUrls,
38
+ iceTurnUsername,
39
+ iceTurnPassword,
40
+ verbose = false,
41
+ } = {}) {
42
+ const stunUrls = parseCsvList(iceStunUrls ?? process.env.ICE_STUN_URLS);
43
+ const turnUrls = parseCsvList(iceTurnUrls ?? process.env.ICE_TURN_URLS);
44
+ const turnUsername = String(iceTurnUsername ?? process.env.ICE_TURN_USERNAME ?? '').trim();
45
+ const turnPassword = String(iceTurnPassword ?? process.env.ICE_TURN_PASSWORD ?? '').trim();
46
+
47
+ const iceServers = [];
48
+ if (stunUrls.length > 0) {
49
+ iceServers.push({ urls: stunUrls });
50
+ }
51
+
52
+ if (turnUrls.length > 0 && turnUsername && turnPassword) {
53
+ iceServers.push({
54
+ urls: turnUrls,
55
+ username: turnUsername,
56
+ credential: turnPassword,
57
+ });
58
+ } else if (turnUrls.length > 0 && verbose) {
59
+ console.error(
60
+ '[webrtc] ICE_TURN_URLS provided without ICE_TURN_USERNAME/ICE_TURN_PASSWORD; skipping TURN',
61
+ );
62
+ }
63
+
64
+ if (iceServers.length === 0) {
65
+ iceServers.push({ urls: 'stun:stun.l.google.com:19302' });
66
+ }
67
+
68
+ if (verbose) {
69
+ const stunCount = stunUrls.length;
70
+ const turnCount = turnUrls.length;
71
+ const turnEnabled = turnUrls.length > 0 && turnUsername && turnPassword;
72
+ console.error(
73
+ `[webrtc] ICE config stunUrls=${stunCount} turnUrls=${turnCount} turnEnabled=${turnEnabled ? 'yes' : 'no'}`,
74
+ );
75
+ }
76
+
77
+ return iceServers;
78
+ }
79
+
28
80
  /**
29
81
  * @param {object} opts
30
82
  * @param {number} [opts.port=9002] HTTP + WS listen port
@@ -38,6 +90,10 @@ const { RTCPeerConnection } = wrtc;
38
90
  * a { type: 'capacity-full' } message.
39
91
  * @param {number} [opts.minBitrateKbps=200] SDP x-google-min-bitrate for VP8 answer
40
92
  * @param {number} [opts.maxBitrateKbps=600] SDP x-google-max-bitrate for VP8 answer
93
+ * @param {string|string[]} [opts.iceStunUrls] Optional STUN URL list
94
+ * @param {string|string[]} [opts.iceTurnUrls] Optional TURN URL list
95
+ * @param {string} [opts.iceTurnUsername] Optional TURN username
96
+ * @param {string} [opts.iceTurnPassword] Optional TURN credential/password
41
97
  * @param {(pc: RTCPeerConnection) => void} opts.onOffer
42
98
  * Called synchronously when an SDP offer arrives, BEFORE createAnswer().
43
99
  * Attach tracks here: pc.addTrack(videoTrack, stream)
@@ -53,14 +109,28 @@ export function createWebRTCServer({
53
109
  maxSpectators = 3,
54
110
  minBitrateKbps = 200,
55
111
  maxBitrateKbps = 600,
112
+ iceStunUrls,
113
+ iceTurnUrls,
114
+ iceTurnUsername,
115
+ iceTurnPassword,
56
116
  onOffer,
57
117
  onPeerConnected,
58
118
  } = {}) {
119
+ const iceServers = buildIceServers({
120
+ iceStunUrls,
121
+ iceTurnUrls,
122
+ iceTurnUsername,
123
+ iceTurnPassword,
124
+ verbose,
125
+ });
126
+
59
127
  /** Emit a structured [event] line — same format as input-server.mjs. */
60
128
  function logEv(tag, fields = {}) {
61
129
  if (!logEvents) return;
62
130
  const ts = new Date().toISOString();
63
- const pairs = Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ');
131
+ const pairs = Object.entries(fields)
132
+ .map(([k, v]) => `${k}=${v}`)
133
+ .join(' ');
64
134
  console.error(`[event] ${ts} ${tag}${pairs ? ' ' + pairs : ''}`);
65
135
  }
66
136
  // Track all active peer connections so forceKeyframe() can reach them all.
@@ -81,12 +151,12 @@ export function createWebRTCServer({
81
151
  };
82
152
  let lastPressureLogAt = 0;
83
153
  let lastPressureSignature = '';
84
- const minBitrateKbpsSafe = Number.isFinite(minBitrateKbps) && minBitrateKbps > 0
85
- ? Math.round(minBitrateKbps)
86
- : 200;
87
- const maxBitrateKbpsSafe = Number.isFinite(maxBitrateKbps) && maxBitrateKbps > 0
88
- ? Math.max(minBitrateKbpsSafe, Math.round(maxBitrateKbps))
89
- : Math.max(minBitrateKbpsSafe, 600);
154
+ const minBitrateKbpsSafe =
155
+ Number.isFinite(minBitrateKbps) && minBitrateKbps > 0 ? Math.round(minBitrateKbps) : 200;
156
+ const maxBitrateKbpsSafe =
157
+ Number.isFinite(maxBitrateKbps) && maxBitrateKbps > 0
158
+ ? Math.max(minBitrateKbpsSafe, Math.round(maxBitrateKbps))
159
+ : Math.max(minBitrateKbpsSafe, 600);
90
160
 
91
161
  // Total capacity = 2 player slots + maxSpectators.
92
162
  // We track all in-flight WS connections (including those not yet ICE-connected)
@@ -103,7 +173,10 @@ export function createWebRTCServer({
103
173
  ...extra,
104
174
  };
105
175
  logEv(tag, snapshot);
106
- if (verbose) console.error(`[webrtc-load] ${tag} active=${snapshot.active} pending=${snapshot.pending} total=${snapshot.total}/${snapshot.max}`);
176
+ if (verbose)
177
+ console.error(
178
+ `[webrtc-load] ${tag} active=${snapshot.active} pending=${snapshot.pending} total=${snapshot.total}/${snapshot.max}`,
179
+ );
107
180
  }
108
181
 
109
182
  async function logRouteSnapshot(pc, remoteAddr) {
@@ -113,14 +186,21 @@ export function createWebRTCServer({
113
186
  const localById = new Map();
114
187
  const remoteById = new Map();
115
188
  for (const stat of report.values()) {
116
- if (stat.type === 'candidate-pair' && stat.nominated && (stat.state === 'succeeded' || stat.selected)) selected = stat;
189
+ if (
190
+ stat.type === 'candidate-pair' &&
191
+ stat.nominated &&
192
+ (stat.state === 'succeeded' || stat.selected)
193
+ )
194
+ selected = stat;
117
195
  if (stat.type === 'local-candidate') localById.set(stat.id, stat);
118
196
  if (stat.type === 'remote-candidate') remoteById.set(stat.id, stat);
119
197
  }
120
198
  if (!selected) return;
121
199
  const local = localById.get(selected.localCandidateId);
122
200
  const remote = remoteById.get(selected.remoteCandidateId);
123
- const rttMs = Number.isFinite(selected.currentRoundTripTime) ? Math.round(selected.currentRoundTripTime * 1000) : null;
201
+ const rttMs = Number.isFinite(selected.currentRoundTripTime)
202
+ ? Math.round(selected.currentRoundTripTime * 1000)
203
+ : null;
124
204
  logEv('webrtc-route', {
125
205
  addr: remoteAddr,
126
206
  protocol: selected.protocol ?? '-',
@@ -130,7 +210,9 @@ export function createWebRTCServer({
130
210
  rttMs: rttMs ?? '-',
131
211
  });
132
212
  if (verbose) {
133
- console.error(`[webrtc-route] addr=${remoteAddr} protocol=${selected.protocol ?? '-'} local=${local?.candidateType ?? '-'} remote=${remote?.candidateType ?? '-'} net=${local?.networkType ?? '-'} rtt=${rttMs ?? '-'}ms`);
213
+ console.error(
214
+ `[webrtc-route] addr=${remoteAddr} protocol=${selected.protocol ?? '-'} local=${local?.candidateType ?? '-'} remote=${remote?.candidateType ?? '-'} net=${local?.networkType ?? '-'} rtt=${rttMs ?? '-'}ms`,
215
+ );
134
216
  }
135
217
  } catch (_) {
136
218
  // Best-effort diagnostics only
@@ -157,7 +239,11 @@ export function createWebRTCServer({
157
239
  let selected = null;
158
240
  let outboundVideo = null;
159
241
  for (const stat of report.values()) {
160
- if (stat.type === 'candidate-pair' && stat.nominated && (stat.state === 'succeeded' || stat.selected)) {
242
+ if (
243
+ stat.type === 'candidate-pair' &&
244
+ stat.nominated &&
245
+ (stat.state === 'succeeded' || stat.selected)
246
+ ) {
161
247
  selected = stat;
162
248
  }
163
249
  if (stat.type === 'outbound-rtp' && stat.kind === 'video' && !stat.isRemote) {
@@ -177,33 +263,65 @@ export function createWebRTCServer({
177
263
  const current = {
178
264
  timestampMs: Number.isFinite(outboundVideo.timestamp) ? outboundVideo.timestamp : nowWall,
179
265
  framesSent: Number.isFinite(outboundVideo.framesSent) ? outboundVideo.framesSent : null,
180
- framesEncoded: Number.isFinite(outboundVideo.framesEncoded) ? outboundVideo.framesEncoded : null,
266
+ framesEncoded: Number.isFinite(outboundVideo.framesEncoded)
267
+ ? outboundVideo.framesEncoded
268
+ : null,
181
269
  bytesSent: Number.isFinite(outboundVideo.bytesSent) ? outboundVideo.bytesSent : null,
182
- packetsSent: Number.isFinite(outboundVideo.packetsSent) ? outboundVideo.packetsSent : null,
183
- totalPacketSendDelay: Number.isFinite(outboundVideo.totalPacketSendDelay) ? outboundVideo.totalPacketSendDelay : null,
184
- totalEncodeTime: Number.isFinite(outboundVideo.totalEncodeTime) ? outboundVideo.totalEncodeTime : null,
270
+ packetsSent: Number.isFinite(outboundVideo.packetsSent)
271
+ ? outboundVideo.packetsSent
272
+ : null,
273
+ totalPacketSendDelay: Number.isFinite(outboundVideo.totalPacketSendDelay)
274
+ ? outboundVideo.totalPacketSendDelay
275
+ : null,
276
+ totalEncodeTime: Number.isFinite(outboundVideo.totalEncodeTime)
277
+ ? outboundVideo.totalEncodeTime
278
+ : null,
185
279
  };
186
280
 
187
281
  const prev = peerStatsPrev.get(pc);
188
282
  peerStatsPrev.set(pc, current);
189
283
  if (!prev) continue;
190
284
 
191
- if (current.framesSent != null && prev.framesSent != null && current.framesSent >= prev.framesSent) {
285
+ if (
286
+ current.framesSent != null &&
287
+ prev.framesSent != null &&
288
+ current.framesSent >= prev.framesSent
289
+ ) {
192
290
  deltaFramesSent += current.framesSent - prev.framesSent;
193
291
  }
194
- if (current.framesEncoded != null && prev.framesEncoded != null && current.framesEncoded >= prev.framesEncoded) {
292
+ if (
293
+ current.framesEncoded != null &&
294
+ prev.framesEncoded != null &&
295
+ current.framesEncoded >= prev.framesEncoded
296
+ ) {
195
297
  deltaFramesEncoded += current.framesEncoded - prev.framesEncoded;
196
298
  }
197
- if (current.bytesSent != null && prev.bytesSent != null && current.bytesSent >= prev.bytesSent) {
299
+ if (
300
+ current.bytesSent != null &&
301
+ prev.bytesSent != null &&
302
+ current.bytesSent >= prev.bytesSent
303
+ ) {
198
304
  deltaBytesSent += current.bytesSent - prev.bytesSent;
199
305
  }
200
- if (current.packetsSent != null && prev.packetsSent != null && current.packetsSent >= prev.packetsSent) {
306
+ if (
307
+ current.packetsSent != null &&
308
+ prev.packetsSent != null &&
309
+ current.packetsSent >= prev.packetsSent
310
+ ) {
201
311
  deltaPacketsSent += current.packetsSent - prev.packetsSent;
202
312
  }
203
- if (current.totalPacketSendDelay != null && prev.totalPacketSendDelay != null && current.totalPacketSendDelay >= prev.totalPacketSendDelay) {
313
+ if (
314
+ current.totalPacketSendDelay != null &&
315
+ prev.totalPacketSendDelay != null &&
316
+ current.totalPacketSendDelay >= prev.totalPacketSendDelay
317
+ ) {
204
318
  deltaPacketSendDelay += current.totalPacketSendDelay - prev.totalPacketSendDelay;
205
319
  }
206
- if (current.totalEncodeTime != null && prev.totalEncodeTime != null && current.totalEncodeTime >= prev.totalEncodeTime) {
320
+ if (
321
+ current.totalEncodeTime != null &&
322
+ prev.totalEncodeTime != null &&
323
+ current.totalEncodeTime >= prev.totalEncodeTime
324
+ ) {
207
325
  deltaEncodeTime += current.totalEncodeTime - prev.totalEncodeTime;
208
326
  }
209
327
  } catch (_) {
@@ -214,9 +332,11 @@ export function createWebRTCServer({
214
332
  const sampleIntervalS = 5;
215
333
  senderTelemetry.sampledAt = nowWall;
216
334
  senderTelemetry.peerCount = peerCount;
217
- senderTelemetry.avgRttMs = rttCount > 0 ? (rttSum / rttCount) : null;
218
- senderTelemetry.sendDelayMsPerPacket = deltaPacketsSent > 0 ? (deltaPacketSendDelay / deltaPacketsSent) * 1000 : null;
219
- senderTelemetry.encodeMsPerFrame = deltaFramesEncoded > 0 ? (deltaEncodeTime / deltaFramesEncoded) * 1000 : null;
335
+ senderTelemetry.avgRttMs = rttCount > 0 ? rttSum / rttCount : null;
336
+ senderTelemetry.sendDelayMsPerPacket =
337
+ deltaPacketsSent > 0 ? (deltaPacketSendDelay / deltaPacketsSent) * 1000 : null;
338
+ senderTelemetry.encodeMsPerFrame =
339
+ deltaFramesEncoded > 0 ? (deltaEncodeTime / deltaFramesEncoded) * 1000 : null;
220
340
  senderTelemetry.framesSentPerSec = deltaFramesSent / sampleIntervalS;
221
341
  senderTelemetry.framesEncodedPerSec = deltaFramesEncoded / sampleIntervalS;
222
342
  senderTelemetry.bytesSentPerSec = deltaBytesSent / sampleIntervalS;
@@ -241,11 +361,12 @@ export function createWebRTCServer({
241
361
  const bitrateKbps = Number.isFinite(senderTelemetry.bytesSentPerSec)
242
362
  ? ((senderTelemetry.bytesSentPerSec * 8) / 1000).toFixed(0)
243
363
  : '-';
244
- const qualitySummary = Object.entries(qualityCounts)
245
- .filter(([, count]) => Number.isFinite(count) && count > 0)
246
- .sort((a, b) => b[1] - a[1])
247
- .map(([reason, count]) => `${reason}:${count}`)
248
- .join('|') || 'none:0';
364
+ const qualitySummary =
365
+ Object.entries(qualityCounts)
366
+ .filter(([, count]) => Number.isFinite(count) && count > 0)
367
+ .sort((a, b) => b[1] - a[1])
368
+ .map(([reason, count]) => `${reason}:${count}`)
369
+ .join('|') || 'none:0';
249
370
 
250
371
  logEv('webrtc-sender-telemetry', {
251
372
  peers: peerCount,
@@ -259,13 +380,22 @@ export function createWebRTCServer({
259
380
  });
260
381
 
261
382
  const pressureReasons = [];
262
- if (Number.isFinite(senderTelemetry.framesSentPerSec) && senderTelemetry.framesSentPerSec < 44) {
383
+ if (
384
+ Number.isFinite(senderTelemetry.framesSentPerSec) &&
385
+ senderTelemetry.framesSentPerSec < 44
386
+ ) {
263
387
  pressureReasons.push('low-fps-out');
264
388
  }
265
- if (Number.isFinite(senderTelemetry.encodeMsPerFrame) && senderTelemetry.encodeMsPerFrame > 12) {
389
+ if (
390
+ Number.isFinite(senderTelemetry.encodeMsPerFrame) &&
391
+ senderTelemetry.encodeMsPerFrame > 12
392
+ ) {
266
393
  pressureReasons.push('slow-encode');
267
394
  }
268
- if (Number.isFinite(senderTelemetry.sendDelayMsPerPacket) && senderTelemetry.sendDelayMsPerPacket > 4) {
395
+ if (
396
+ Number.isFinite(senderTelemetry.sendDelayMsPerPacket) &&
397
+ senderTelemetry.sendDelayMsPerPacket > 4
398
+ ) {
269
399
  pressureReasons.push('packet-send-delay');
270
400
  }
271
401
  if ((qualityCounts.cpu ?? 0) > 0) pressureReasons.push('quality-cpu');
@@ -274,7 +404,8 @@ export function createWebRTCServer({
274
404
  if (pressureReasons.length > 0) {
275
405
  const signature = pressureReasons.join('|');
276
406
  const now = Date.now();
277
- const shouldLogPressure = signature !== lastPressureSignature || (now - lastPressureLogAt) >= 30_000;
407
+ const shouldLogPressure =
408
+ signature !== lastPressureSignature || now - lastPressureLogAt >= 30_000;
278
409
  if (shouldLogPressure) {
279
410
  lastPressureSignature = signature;
280
411
  lastPressureLogAt = now;
@@ -318,7 +449,9 @@ export function createWebRTCServer({
318
449
  newAddr: controller.remoteAddr ?? '-',
319
450
  source,
320
451
  });
321
- try { previous.closePeer?.('session-replaced'); } catch (_) {}
452
+ try {
453
+ previous.closePeer?.('session-replaced');
454
+ } catch (_) {}
322
455
  }
323
456
 
324
457
  peerBySession.set(sessionKey, controller);
@@ -333,7 +466,7 @@ export function createWebRTCServer({
333
466
  const httpServer = http.createServer((req, res) => {
334
467
  if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
335
468
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
336
- res.end(buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe));
469
+ res.end(buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe, iceServers));
337
470
  } else if (req.url === '/favicon.ico') {
338
471
  // Return a minimal 1×1 transparent ICO so browsers don't log a 404
339
472
  res.writeHead(204);
@@ -372,14 +505,15 @@ export function createWebRTCServer({
372
505
 
373
506
  wss.on('connection', (ws, req) => {
374
507
  ws._sigAlive = true; // initialise alive flag
375
- ws.on('pong', () => { ws._sigAlive = true; });
508
+ ws.on('pong', () => {
509
+ ws._sigAlive = true;
510
+ });
376
511
  const remoteAddr = req.socket.remoteAddress;
377
512
  let initialSessionId = null;
378
513
  try {
379
514
  const reqUrl = new URL(req.url || '/', 'http://localhost');
380
- initialSessionId = reqUrl.searchParams.get('sid')
381
- || reqUrl.searchParams.get('sessionId')
382
- || null;
515
+ initialSessionId =
516
+ reqUrl.searchParams.get('sid') || reqUrl.searchParams.get('sessionId') || null;
383
517
  } catch (_) {}
384
518
 
385
519
  // ── Capacity gate ─────────────────────────────────────────────────────────
@@ -387,15 +521,23 @@ export function createWebRTCServer({
387
521
  // Players take 2 of the MAX_CONNECTIONS slots; remaining slots are spectators.
388
522
  const currentTotal = activePeers.size + pendingPeers;
389
523
  if (currentTotal >= MAX_CONNECTIONS) {
390
- console.error(`[webrtc] capacity full (${currentTotal}/${MAX_CONNECTIONS}) — rejecting ${remoteAddr}`);
391
- logEv('webrtc-capacity-full', { addr: remoteAddr, current: currentTotal, max: MAX_CONNECTIONS });
524
+ console.error(
525
+ `[webrtc] capacity full (${currentTotal}/${MAX_CONNECTIONS}) — rejecting ${remoteAddr}`,
526
+ );
527
+ logEv('webrtc-capacity-full', {
528
+ addr: remoteAddr,
529
+ current: currentTotal,
530
+ max: MAX_CONNECTIONS,
531
+ });
392
532
  try {
393
- ws.send(JSON.stringify({
394
- type: 'capacity-full',
395
- current: currentTotal,
396
- max: MAX_CONNECTIONS,
397
- maxSpectators,
398
- }));
533
+ ws.send(
534
+ JSON.stringify({
535
+ type: 'capacity-full',
536
+ current: currentTotal,
537
+ max: MAX_CONNECTIONS,
538
+ maxSpectators,
539
+ }),
540
+ );
399
541
  } catch (_) {}
400
542
  ws.close();
401
543
  return;
@@ -406,9 +548,7 @@ export function createWebRTCServer({
406
548
  logEv('webrtc-peer-connected', { addr: remoteAddr });
407
549
  logLoadSnapshot('webrtc-load-change', { reason: 'peer-connected' });
408
550
 
409
- const pc = new RTCPeerConnection({
410
- iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
411
- });
551
+ const pc = new RTCPeerConnection({ iceServers });
412
552
  const controller = {
413
553
  pc,
414
554
  ws,
@@ -428,7 +568,10 @@ export function createWebRTCServer({
428
568
  let disconnectTimer = null;
429
569
 
430
570
  function clearDisconnectTimer() {
431
- if (disconnectTimer) { clearTimeout(disconnectTimer); disconnectTimer = null; }
571
+ if (disconnectTimer) {
572
+ clearTimeout(disconnectTimer);
573
+ disconnectTimer = null;
574
+ }
432
575
  }
433
576
 
434
577
  // Track whether this peer has ever reached ICE connected (to manage pendingPeers correctly).
@@ -444,7 +587,7 @@ export function createWebRTCServer({
444
587
  const errName = err?.name ?? 'Error';
445
588
  const errMsg = err?.message ?? String(err);
446
589
  console.error(
447
- `[webrtc] addIceCandidate failed (${source}) addr=${remoteAddr} hasRemoteDescription=${hasRemoteDescription} signalingState=${signalingState} err=${errName}: ${errMsg}`
590
+ `[webrtc] addIceCandidate failed (${source}) addr=${remoteAddr} hasRemoteDescription=${hasRemoteDescription} signalingState=${signalingState} err=${errName}: ${errMsg}`,
448
591
  );
449
592
  logEv('webrtc-ice-candidate-error', {
450
593
  addr: remoteAddr,
@@ -474,14 +617,18 @@ export function createWebRTCServer({
474
617
  }
475
618
  peerControllers.delete(controller);
476
619
  // Decrement pendingPeers only if this peer never made it to ICE connected.
477
- if (!wasActive && !everConnected) { if (pendingPeers > 0) pendingPeers--; }
620
+ if (!wasActive && !everConnected) {
621
+ if (pendingPeers > 0) pendingPeers--;
622
+ }
478
623
  console.error(`[webrtc] closing peer (${remoteAddr}): ${reason}`);
479
624
  logEv('webrtc-peer-closed', { addr: remoteAddr, reason });
480
625
  logLoadSnapshot('webrtc-load-change', { reason: `peer-closed:${reason}` });
481
626
  // Tell the browser the stream died so it can reconnect immediately
482
627
  // rather than sitting on a frozen frame.
483
628
  if (ws.readyState === ws.OPEN) {
484
- try { ws.send(JSON.stringify({ type: 'peer-closed', reason })); } catch (_) {}
629
+ try {
630
+ ws.send(JSON.stringify({ type: 'peer-closed', reason }));
631
+ } catch (_) {}
485
632
  }
486
633
  pc.close();
487
634
  }
@@ -550,7 +697,11 @@ export function createWebRTCServer({
550
697
 
551
698
  try {
552
699
  if (msg.type === 'offer') {
553
- bindControllerSession(controller, msg.sessionId ?? msg.sid ?? msg.clientSessionId ?? null, 'offer');
700
+ bindControllerSession(
701
+ controller,
702
+ msg.sessionId ?? msg.sid ?? msg.clientSessionId ?? null,
703
+ 'offer',
704
+ );
554
705
  await pc.setRemoteDescription(msg);
555
706
  await flushRemoteCandidates('post-offer');
556
707
 
@@ -571,15 +722,12 @@ export function createWebRTCServer({
571
722
  let sdp = answer.sdp;
572
723
  if (sdp) {
573
724
  // Find VP8 payload type in the offer and append fmtp constraints
574
- sdp = sdp.replace(
575
- /(a=rtpmap:(\d+) VP8\/\d+\r?\n)/,
576
- (match, line, pt) => {
577
- const minKbps = Math.max(50, minBitrateKbpsSafe);
578
- const maxKbps = Math.max(minKbps, maxBitrateKbpsSafe);
579
- const fmtp = `a=fmtp:${pt} x-google-min-bitrate=${minKbps};x-google-max-bitrate=${maxKbps}\r\n`;
580
- return line + fmtp;
581
- }
582
- );
725
+ sdp = sdp.replace(/(a=rtpmap:(\d+) VP8\/\d+\r?\n)/, (match, line, pt) => {
726
+ const minKbps = Math.max(50, minBitrateKbpsSafe);
727
+ const maxKbps = Math.max(minKbps, maxBitrateKbpsSafe);
728
+ const fmtp = `a=fmtp:${pt} x-google-min-bitrate=${minKbps};x-google-max-bitrate=${maxKbps}\r\n`;
729
+ return line + fmtp;
730
+ });
583
731
  answer.sdp = sdp;
584
732
  }
585
733
 
@@ -589,12 +737,13 @@ export function createWebRTCServer({
589
737
  ws.send(JSON.stringify(pc.localDescription));
590
738
  }
591
739
  if (verbose) console.error(`[webrtc] answered offer from ${remoteAddr}`);
592
-
593
740
  } else if (msg.type === 'candidate' && msg.candidate) {
594
741
  if (!pc.remoteDescription) {
595
742
  pendingRemoteCandidates.push(msg.candidate);
596
743
  if (verbose) {
597
- console.error(`[webrtc] queued remote candidate (${pendingRemoteCandidates.length}) pending offer (${remoteAddr})`);
744
+ console.error(
745
+ `[webrtc] queued remote candidate (${pendingRemoteCandidates.length}) pending offer (${remoteAddr})`,
746
+ );
598
747
  }
599
748
  } else {
600
749
  await addRemoteCandidate(msg.candidate, 'live');
@@ -717,9 +866,15 @@ export function createWebRTCServer({
717
866
  }
718
867
 
719
868
  // ─── Embedded browser-side player page ──────────────────────────────────────
720
- function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600) {
869
+ function buildBrowserHtml(
870
+ inputPort,
871
+ minBitrateKbps = 200,
872
+ maxBitrateKbps = 600,
873
+ iceServers = [{ urls: 'stun:stun.l.google.com:19302' }],
874
+ ) {
721
875
  const minKbps = Math.max(50, Math.round(minBitrateKbps));
722
876
  const maxKbps = Math.max(minKbps, Math.round(maxBitrateKbps));
877
+ const iceServersJson = JSON.stringify(iceServers).replace(/</g, '\\u003c');
723
878
  return /* html */ `<!DOCTYPE html>
724
879
  <html lang="en">
725
880
  <head>
@@ -825,6 +980,7 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600)
825
980
  <button id="load-btn" title="Load a .crt cartridge file">📂 load .crt</button>
826
981
  <button id="detach-btn" title="Eject cartridge → BASIC prompt" disabled>⏏ detach</button>
827
982
  <button id="reset-btn" title="Hard reset (BASIC prompt)" disabled>↺ reset</button>
983
+ <button id="reboot-btn" title="Re-instantiate emulator with no game loaded">⟲ reboot</button>
828
984
  <span class="sep">|</span>
829
985
  <button id="sync-btn" title="Flush video to live edge — use if display feels laggy">⟳ sync</button>
830
986
  <span class="sep">|</span>
@@ -848,9 +1004,11 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600)
848
1004
  const loadBtn = document.getElementById('load-btn');
849
1005
  const detachBtn = document.getElementById('detach-btn');
850
1006
  const resetBtn = document.getElementById('reset-btn');
1007
+ const rebootBtn = document.getElementById('reboot-btn');
851
1008
  const syncBtn = document.getElementById('sync-btn');
852
1009
  const modeBtn = document.getElementById('mode-btn');
853
1010
  const fileInput = document.getElementById('file-input');
1011
+ const ICE_SERVERS = ${iceServersJson};
854
1012
 
855
1013
  function setBadge(el, text, cls) {
856
1014
  el.textContent = text;
@@ -994,7 +1152,7 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600)
994
1152
  const sigUrl = new URL('ws://' + location.host);
995
1153
  sigUrl.searchParams.set('sid', rtcSessionId);
996
1154
  sigWs = new WebSocket(sigUrl.toString());
997
- pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] });
1155
+ pc = new RTCPeerConnection({ iceServers: ICE_SERVERS });
998
1156
  let offerSent = false;
999
1157
  const pendingLocalCandidates = [];
1000
1158
  const pendingRemoteCandidates = [];
@@ -1176,12 +1334,18 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600)
1176
1334
  try {
1177
1335
  const msg = JSON.parse(data);
1178
1336
  // Cart lifecycle
1179
- if (msg.type === 'cart-loaded' || msg.type === 'machine-reset' || msg.type === 'cart-detached') {
1337
+ if (msg.type === 'cart-loaded' || msg.type === 'machine-reset' || msg.type === 'cart-detached' || msg.type === 'machine-rebooted') {
1180
1338
  blurAll();
1181
1339
  const cartName = msg.filename ? msg.filename.replace(/\\.crt$/i,'').replace(/[-_]/g,' ') : '';
1182
1340
  if (msg.type === 'cart-loaded') { setBadge(gameBadge, '🎮 ' + (cartName || 'game loaded'), 'ok'); setLoadStatus('loaded', 'ok'); detachBtn.disabled = false; resetBtn.disabled = false; }
1183
1341
  if (msg.type === 'cart-detached') { setBadge(gameBadge, 'no game', 'dim'); setLoadStatus('', ''); detachBtn.disabled = true; }
1184
1342
  if (msg.type === 'machine-reset') { setLoadStatus('reset', 'warn'); }
1343
+ if (msg.type === 'machine-rebooted') {
1344
+ setBadge(gameBadge, 'no game', 'dim');
1345
+ setLoadStatus('rebooted', 'warn');
1346
+ detachBtn.disabled = true;
1347
+ resetBtn.disabled = true;
1348
+ }
1185
1349
  // Reconnect the RTCPeerConnection entirely — this is the only
1186
1350
  // reliable way to clear the jitter buffer and decoder state that
1187
1351
  // accumulates during the ~1600ms cart-load gap. Anything less
@@ -1264,6 +1428,7 @@ function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600)
1264
1428
  });
1265
1429
  detachBtn.addEventListener('click', () => { sendInput({ type: 'detach-crt' }); setLoadStatus('detaching…', 'warn'); blurAll(); });
1266
1430
  resetBtn.addEventListener('click', () => { sendInput({ type: 'hard-reset' }); setLoadStatus('resetting…', 'warn'); blurAll(); });
1431
+ rebootBtn.addEventListener('click', () => { sendInput({ type: 'reboot' }); setLoadStatus('rebooting…', 'warn'); blurAll(); });
1267
1432
  syncBtn.addEventListener('click', () => {
1268
1433
  const wasMuted = videoEl.muted;
1269
1434
  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,7 +84,27 @@ 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
+ status.style.color = '#f44';
89
+ }
90
+ });
91
+
92
+ window.addEventListener('c64-load-tool', async (e: Event) => {
93
+ const detail = (e as CustomEvent).detail as
94
+ | { name?: string; url?: string; type?: string }
95
+ | undefined;
96
+ if (!detail?.url) return;
97
+ const loadType = isSupportedLoadType(detail.type) ? detail.type : undefined;
98
+ try {
99
+ status.textContent = `Loading tool: ${detail.name ?? detail.url}`;
100
+ status.style.color = '#9ecbff';
101
+ renderer.showLoader();
102
+ await player.loadTool(detail.url, loadType);
103
+ renderer.hideLoader();
104
+ } catch (err) {
105
+ console.error(err);
106
+ renderer.setError('LOAD ERROR');
107
+ status.textContent = `Tool load error: ${normalizeErrorMessage(String(err))}`;
88
108
  status.style.color = '#f44';
89
109
  }
90
110
  });
@@ -94,7 +114,7 @@ window.addEventListener('c64-load-error', (e: Event) => {
94
114
  const detail = (e as CustomEvent).detail as
95
115
  | { error?: string; url?: string; file?: string; type?: string }
96
116
  | undefined;
97
- const msg = detail?.error ?? 'Unknown load error';
117
+ const msg = normalizeErrorMessage(detail?.error ?? 'Unknown load error');
98
118
  console.error('C64 load error event:', detail);
99
119
  renderer.setError('LOAD ERROR');
100
120
  status.textContent = `Load error: ${msg}`;
@@ -110,3 +130,17 @@ window.addEventListener('c64-load-info', (e: Event) => {
110
130
  status.style.color = detail.mode === 'warning' ? '#f9c74f' : '#9ecbff';
111
131
  console.info('C64 load info event:', detail);
112
132
  });
133
+
134
+ window.addEventListener('c64-reboot', () => {
135
+ status.textContent = 'Emulator rebooted. Load a cartridge to continue.';
136
+ status.style.color = '#9ecbff';
137
+ renderer.hideLoader(0);
138
+ });
139
+
140
+ function normalizeErrorMessage(msg: string): string {
141
+ let out = String(msg ?? '').trim();
142
+ while (/^(uncaught\s+)?error\s*:\s*/i.test(out)) {
143
+ out = out.replace(/^(uncaught\s+)?error\s*:\s*/i, '').trim();
144
+ }
145
+ return out || 'Unknown load error';
146
+ }