c64-ready 1.0.1 → 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.
- package/README.md +70 -62
- package/bin/headless.mjs +1 -1
- package/dist/assets/CHANGELOG-0a7A8Ekq.js +391 -0
- package/dist/assets/index-BESofQoh.js +627 -0
- package/dist/games/cartridges/goat-beat.crt +0 -0
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/public/games/cartridges/goat-beat.crt +0 -0
- package/src/emulator/c64-emulator.ts +3 -5
- package/src/emulator/input.ts +239 -19
- package/src/headless/headless-cli.mjs +73 -37
- package/src/headless/input-server.mjs +276 -102
- package/src/headless/webrtc-server.mjs +51 -5
- package/src/main.ts +12 -0
- package/src/player/c64-player.ts +21 -6
- package/src/player/input-handler.ts +8 -0
- package/src/player/styles/ui-controller.css +13 -0
- package/src/player/ui-controller.ts +128 -12
- package/src/types/emulator.ts +1 -1
- package/dist/assets/CHANGELOG-B12WeYEc.js +0 -116
- package/dist/assets/index-fUdEY2R7.js +0 -610
|
@@ -372,7 +372,17 @@ export function createInputServer(opts = {}) {
|
|
|
372
372
|
}
|
|
373
373
|
|
|
374
374
|
let clientCount = 0;
|
|
375
|
-
const clientMeta = new Map(); // Map<WebSocket, { addr: string, role: string, username: string|null }>
|
|
375
|
+
const clientMeta = new Map(); // Map<WebSocket, { addr: string, role: string, username: string|null, sessionId: string|null }>
|
|
376
|
+
|
|
377
|
+
function normalizeSessionId(value) {
|
|
378
|
+
const raw = String(value ?? '').trim();
|
|
379
|
+
return raw || null;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function normalizeUsername(value) {
|
|
383
|
+
const username = String(value ?? '').trim().toLowerCase();
|
|
384
|
+
return username || null;
|
|
385
|
+
}
|
|
376
386
|
|
|
377
387
|
function normalizeAddr(addr) {
|
|
378
388
|
if (!addr) return '';
|
|
@@ -386,45 +396,211 @@ export function createInputServer(opts = {}) {
|
|
|
386
396
|
meta.username = username;
|
|
387
397
|
}
|
|
388
398
|
|
|
399
|
+
function getRoleByPeer({ addr = null, sessionId = null } = {}) {
|
|
400
|
+
const normalizedSessionId = normalizeSessionId(sessionId);
|
|
401
|
+
const hostMeta = hostClient ? clientMeta.get(hostClient) : null;
|
|
402
|
+
const p2Meta = p2Client ? clientMeta.get(p2Client) : null;
|
|
403
|
+
|
|
404
|
+
if (normalizedSessionId) {
|
|
405
|
+
if (hostMeta?.sessionId && hostMeta.sessionId === normalizedSessionId) {
|
|
406
|
+
return { role: 'host', username: hostUsername, ws: hostClient };
|
|
407
|
+
}
|
|
408
|
+
if (p2Meta?.sessionId && p2Meta.sessionId === normalizedSessionId) {
|
|
409
|
+
return { role: 'p2', username: p2Username, ws: p2Client };
|
|
410
|
+
}
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
const normalizedAddr = normalizeAddr(addr);
|
|
415
|
+
if (!normalizedAddr) return null;
|
|
416
|
+
const hostMatches = !!(hostMeta?.addr && hostMeta.addr === normalizedAddr);
|
|
417
|
+
const p2Matches = !!(p2Meta?.addr && p2Meta.addr === normalizedAddr);
|
|
418
|
+
if (hostMatches && !p2Matches) return { role: 'host', username: hostUsername, ws: hostClient };
|
|
419
|
+
if (p2Matches && !hostMatches) return { role: 'p2', username: p2Username, ws: p2Client };
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function handleInputTransportMessage({ msg, role, respond = null } = {}) {
|
|
424
|
+
if (!msg || (msg.type !== 'joystick' && msg.type !== 'key' && msg.type !== 'ping')) return false;
|
|
425
|
+
|
|
426
|
+
if (msg.type === 'ping') {
|
|
427
|
+
const now = Date.now();
|
|
428
|
+
const payload = {
|
|
429
|
+
type: 'pong',
|
|
430
|
+
pingId: msg.pingId ?? null,
|
|
431
|
+
serverTime: now,
|
|
432
|
+
clientTime: msg.clientTime ?? null,
|
|
433
|
+
};
|
|
434
|
+
try {
|
|
435
|
+
respond?.(payload);
|
|
436
|
+
} catch (_) {}
|
|
437
|
+
if (verbose) console.error(`[ping] role=${role} pong pingId=${msg.pingId ?? '-'} `);
|
|
438
|
+
return true;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
if (role === 'host') resetHostTimeout();
|
|
442
|
+
if (role === 'p2') resetP2Timeout();
|
|
443
|
+
|
|
444
|
+
const stats = role === 'host' ? _inputStats.host : _inputStats.p2;
|
|
445
|
+
if (msg.type === 'joystick') stats.joystick++;
|
|
446
|
+
else stats.key++;
|
|
447
|
+
stats.lastMsgTime = Date.now();
|
|
448
|
+
|
|
449
|
+
if (msg.clientTime) {
|
|
450
|
+
const now = Date.now();
|
|
451
|
+
const latency = now - msg.clientTime;
|
|
452
|
+
const bucket = _networkStats[role];
|
|
453
|
+
if (bucket) {
|
|
454
|
+
bucket.lastLatency = latency;
|
|
455
|
+
}
|
|
456
|
+
if (!_latencyLogTimer) {
|
|
457
|
+
_latencyLogTimer = setInterval(() => {
|
|
458
|
+
const hostActive = _latencyCount.host > 0;
|
|
459
|
+
const p2Active = _latencyCount.p2 > 0;
|
|
460
|
+
if (hostActive || p2Active) {
|
|
461
|
+
const hostAvg = hostActive ? Number(_avgLatency.host.toFixed(0)) : null;
|
|
462
|
+
const p2Avg = p2Active ? Number(_avgLatency.p2.toFixed(0)) : null;
|
|
463
|
+
const hostLabel = hostAvg != null ? `${hostAvg}` : '--';
|
|
464
|
+
const p2Label = p2Avg != null ? `${p2Avg}` : '--';
|
|
465
|
+
if (logEvents || verbose) {
|
|
466
|
+
console.error(
|
|
467
|
+
`[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`,
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
_networkStats.host.avgLatency = hostAvg;
|
|
471
|
+
_networkStats.p2.avgLatency = p2Avg;
|
|
472
|
+
broadcastNetworkStats();
|
|
473
|
+
}
|
|
474
|
+
_avgLatency.host = 0;
|
|
475
|
+
_avgLatency.p2 = 0;
|
|
476
|
+
_latencyCount.host = 0;
|
|
477
|
+
_latencyCount.p2 = 0;
|
|
478
|
+
}, 5000);
|
|
479
|
+
}
|
|
480
|
+
_latencyCount[role]++;
|
|
481
|
+
_avgLatency[role] =
|
|
482
|
+
(_avgLatency[role] * (_latencyCount[role] - 1) + latency) / _latencyCount[role];
|
|
483
|
+
if (latency > LATENCY_SPIKE_MS) {
|
|
484
|
+
if (bucket) {
|
|
485
|
+
bucket.lastSpikeLatency = latency;
|
|
486
|
+
bucket.lastSpikeAt = now;
|
|
487
|
+
}
|
|
488
|
+
if (logEvents || verbose) {
|
|
489
|
+
console.error(
|
|
490
|
+
`[event] input-latency-spike role=${role} latency=${latency}ms type=${msg.type} action=${msg.action ?? '-'} ` +
|
|
491
|
+
`dir=${msg.direction ?? '-'} fire=${msg.fire ? 1 : 0}`,
|
|
492
|
+
);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
msg._role = role;
|
|
498
|
+
if (msg.type === 'joystick') {
|
|
499
|
+
msg.joystickPort = role === 'host' ? hostPort() : p2Port();
|
|
500
|
+
}
|
|
501
|
+
if (onInput) onInput(msg);
|
|
502
|
+
if (Number.isFinite(msg.inputId)) {
|
|
503
|
+
try {
|
|
504
|
+
respond?.({ type: 'input-ack', inputId: msg.inputId });
|
|
505
|
+
} catch (_) {}
|
|
506
|
+
}
|
|
507
|
+
return true;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function resetRoleActivity(role, source = 'unknown') {
|
|
511
|
+
if (role === 'host') resetHostTimeout();
|
|
512
|
+
else if (role === 'p2') resetP2Timeout();
|
|
513
|
+
else return false;
|
|
514
|
+
if (verbose) console.error(`[input-server] activity role=${role} source=${source}`);
|
|
515
|
+
logEv('activity', { role, source });
|
|
516
|
+
return true;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function handlePeerDataMessage({ addr = null, sessionId = null, msg, send = null } = {}) {
|
|
520
|
+
const identity = getRoleByPeer({ addr, sessionId });
|
|
521
|
+
if (!identity || (identity.role !== 'host' && identity.role !== 'p2')) return false;
|
|
522
|
+
return handleInputTransportMessage({ msg, role: identity.role, respond: send, isWebSocket: false, ws: identity.ws });
|
|
523
|
+
}
|
|
524
|
+
|
|
389
525
|
function getWebrtcPeerCountByAddr() {
|
|
390
526
|
const snapshot = getWebrtcPeerSnapshot?.() ?? null;
|
|
391
527
|
const peers = Array.isArray(snapshot?.peers) ? snapshot.peers : [];
|
|
392
528
|
const byAddr = new Map();
|
|
529
|
+
const bySession = new Map();
|
|
393
530
|
for (const p of peers) {
|
|
394
531
|
const addr = normalizeAddr(p?.addr);
|
|
532
|
+
const session = normalizeSessionId(p?.session);
|
|
395
533
|
if (!addr) continue;
|
|
396
534
|
byAddr.set(addr, (byAddr.get(addr) ?? 0) + 1);
|
|
535
|
+
if (session) bySession.set(session, (bySession.get(session) ?? 0) + 1);
|
|
397
536
|
}
|
|
398
|
-
return { snapshot, byAddr };
|
|
537
|
+
return { snapshot, byAddr, bySession };
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function getSpectatorIdentity(meta, ws) {
|
|
541
|
+
const sessionId = normalizeSessionId(meta?.sessionId);
|
|
542
|
+
if (sessionId) return `session:${sessionId}`;
|
|
543
|
+
const username = normalizeUsername(meta?.username);
|
|
544
|
+
if (username) return `user:${username}`;
|
|
545
|
+
return `socket:${String(meta?.addr ?? 'unknown')}:${ws._socket?._handle?.fd ?? 'na'}`;
|
|
399
546
|
}
|
|
400
547
|
|
|
401
548
|
function buildAdminStatus() {
|
|
402
549
|
const hostMeta = hostClient ? clientMeta.get(hostClient) : null;
|
|
403
550
|
const p2Meta = p2Client ? clientMeta.get(p2Client) : null;
|
|
404
551
|
const spectators = [];
|
|
405
|
-
const { snapshot: webrtcSnapshot, byAddr: webrtcByAddr } = getWebrtcPeerCountByAddr();
|
|
406
|
-
const
|
|
407
|
-
|
|
408
|
-
|
|
552
|
+
const { snapshot: webrtcSnapshot, byAddr: webrtcByAddr, bySession: webrtcBySession } = getWebrtcPeerCountByAddr();
|
|
553
|
+
const matchedPeerSlots = new Set();
|
|
554
|
+
const webrtcPeers = Array.isArray(webrtcSnapshot?.peers) ? webrtcSnapshot.peers : [];
|
|
555
|
+
|
|
556
|
+
function matchWebrtcPeers(meta) {
|
|
557
|
+
const sessionId = normalizeSessionId(meta?.sessionId);
|
|
558
|
+
if (sessionId && webrtcBySession.has(sessionId)) {
|
|
559
|
+
let matched = 0;
|
|
560
|
+
webrtcPeers.forEach((peer, index) => {
|
|
561
|
+
if (normalizeSessionId(peer?.session) !== sessionId) return;
|
|
562
|
+
matchedPeerSlots.add(index);
|
|
563
|
+
matched++;
|
|
564
|
+
});
|
|
565
|
+
return matched;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const addr = normalizeAddr(meta?.addr);
|
|
569
|
+
if (!addr || !webrtcByAddr.has(addr)) return 0;
|
|
570
|
+
let matched = 0;
|
|
571
|
+
webrtcPeers.forEach((peer, index) => {
|
|
572
|
+
if (normalizeAddr(peer?.addr) !== addr) return;
|
|
573
|
+
matchedPeerSlots.add(index);
|
|
574
|
+
matched++;
|
|
575
|
+
});
|
|
576
|
+
return matched;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const spectatorByIdentity = new Map();
|
|
580
|
+
const hostWebrtcPeers = matchWebrtcPeers(hostMeta);
|
|
581
|
+
const p2WebrtcPeers = matchWebrtcPeers(p2Meta);
|
|
409
582
|
for (const [ws, meta] of clientMeta.entries()) {
|
|
410
583
|
if (ws === hostClient || ws === p2Client) continue;
|
|
411
584
|
if (ws.readyState !== ws.OPEN) continue;
|
|
412
585
|
if (meta.role === 'admin') continue;
|
|
413
|
-
|
|
414
|
-
|
|
586
|
+
const identity = getSpectatorIdentity(meta, ws);
|
|
587
|
+
const existing = spectatorByIdentity.get(identity);
|
|
588
|
+
const spectator = existing ?? {
|
|
415
589
|
addr: meta.addr,
|
|
416
590
|
role: meta.role ?? 'spectator',
|
|
417
591
|
username: meta.username ?? null,
|
|
418
|
-
webrtcPeers:
|
|
419
|
-
}
|
|
592
|
+
webrtcPeers: 0,
|
|
593
|
+
};
|
|
594
|
+
spectator.addr = spectator.addr ?? meta.addr;
|
|
595
|
+
spectator.username = spectator.username ?? meta.username ?? null;
|
|
596
|
+
spectator.webrtcPeers = Math.max(spectator.webrtcPeers, matchWebrtcPeers(meta));
|
|
597
|
+
spectatorByIdentity.set(identity, spectator);
|
|
420
598
|
}
|
|
421
599
|
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
mappedWebrtcPeers += webrtcByAddr.get(addr) ?? 0;
|
|
425
|
-
}
|
|
600
|
+
spectators.push(...spectatorByIdentity.values());
|
|
601
|
+
|
|
426
602
|
const webrtcTotal = Number.isFinite(webrtcSnapshot?.total) ? webrtcSnapshot.total : 0;
|
|
427
|
-
const anonymousWebrtcPeers = Math.max(0, webrtcTotal -
|
|
603
|
+
const anonymousWebrtcPeers = Math.max(0, webrtcTotal - matchedPeerSlots.size);
|
|
428
604
|
|
|
429
605
|
return {
|
|
430
606
|
host: hostClient
|
|
@@ -432,7 +608,7 @@ export function createInputServer(opts = {}) {
|
|
|
432
608
|
connected: hostClient.readyState === hostClient.OPEN,
|
|
433
609
|
username: hostUsername,
|
|
434
610
|
addr: hostMeta?.addr ?? null,
|
|
435
|
-
webrtcPeers:
|
|
611
|
+
webrtcPeers: hostWebrtcPeers,
|
|
436
612
|
}
|
|
437
613
|
: null,
|
|
438
614
|
p2: p2Client
|
|
@@ -440,7 +616,7 @@ export function createInputServer(opts = {}) {
|
|
|
440
616
|
connected: p2Client.readyState === p2Client.OPEN,
|
|
441
617
|
username: p2Username,
|
|
442
618
|
addr: p2Meta?.addr ?? null,
|
|
443
|
-
webrtcPeers:
|
|
619
|
+
webrtcPeers: p2WebrtcPeers,
|
|
444
620
|
}
|
|
445
621
|
: null,
|
|
446
622
|
spectators,
|
|
@@ -469,7 +645,9 @@ export function createInputServer(opts = {}) {
|
|
|
469
645
|
wss.on('connection', (ws, req) => {
|
|
470
646
|
clientCount++;
|
|
471
647
|
const addr = req.socket.remoteAddress;
|
|
472
|
-
|
|
648
|
+
const reqUrl = new URL(req.url || '/', 'http://localhost');
|
|
649
|
+
const sessionId = normalizeSessionId(reqUrl.searchParams.get('sid'));
|
|
650
|
+
clientMeta.set(ws, { addr: normalizeAddr(addr), role: 'spectator', username: null, sessionId });
|
|
473
651
|
if (verbose)
|
|
474
652
|
console.error(`[input-server] client connected from ${addr} (${clientCount} total)`);
|
|
475
653
|
logEv('client-connected', { addr, total: clientCount });
|
|
@@ -891,6 +1069,40 @@ export function createInputServer(opts = {}) {
|
|
|
891
1069
|
return;
|
|
892
1070
|
}
|
|
893
1071
|
|
|
1072
|
+
if (msg.type === 'admin-activity') {
|
|
1073
|
+
const valid = validateAdminToken(msg.token ?? '');
|
|
1074
|
+
if (!valid) {
|
|
1075
|
+
ws.send(
|
|
1076
|
+
JSON.stringify({ type: 'admin-error', command: 'activity', reason: 'invalid-token' }),
|
|
1077
|
+
);
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
setWsIdentity(ws, 'admin', null);
|
|
1081
|
+
const role = msg.role === 'p2' ? 'p2' : msg.role === 'host' ? 'host' : null;
|
|
1082
|
+
if (!role) {
|
|
1083
|
+
ws.send(
|
|
1084
|
+
JSON.stringify({ type: 'admin-error', command: 'activity', reason: 'invalid-role' }),
|
|
1085
|
+
);
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
const active = role === 'host' ? !!hostClient : !!p2Client;
|
|
1089
|
+
if (!active) {
|
|
1090
|
+
ws.send(
|
|
1091
|
+
JSON.stringify({ type: 'admin-error', command: 'activity', reason: 'role-not-present' }),
|
|
1092
|
+
);
|
|
1093
|
+
return;
|
|
1094
|
+
}
|
|
1095
|
+
resetRoleActivity(role, msg.source ?? 'admin');
|
|
1096
|
+
ws.send(
|
|
1097
|
+
JSON.stringify({
|
|
1098
|
+
type: 'admin-activity-ok',
|
|
1099
|
+
role,
|
|
1100
|
+
source: msg.source ?? 'admin',
|
|
1101
|
+
}),
|
|
1102
|
+
);
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
894
1106
|
if (msg.type === 'admin-kick-all') {
|
|
895
1107
|
const valid = validateAdminToken(msg.token ?? '');
|
|
896
1108
|
if (!valid) {
|
|
@@ -1077,98 +1289,57 @@ export function createInputServer(opts = {}) {
|
|
|
1077
1289
|
return;
|
|
1078
1290
|
}
|
|
1079
1291
|
|
|
1292
|
+
if (msg.type === 'save-snapshot') {
|
|
1293
|
+
if (ws !== hostClient) return;
|
|
1294
|
+
if (verbose) console.error('[input-server] save-snapshot');
|
|
1295
|
+
logEv('cmd-save-snapshot', { host: hostUsername });
|
|
1296
|
+
Promise.resolve()
|
|
1297
|
+
.then(() => onCommand({ type: 'save-snapshot' }))
|
|
1298
|
+
.then((result) => {
|
|
1299
|
+
if (!result || ws.readyState !== ws.OPEN) return;
|
|
1300
|
+
ws.send(
|
|
1301
|
+
JSON.stringify({
|
|
1302
|
+
type: 'snapshot-data',
|
|
1303
|
+
filename: result.filename ?? 'snapshot.c64',
|
|
1304
|
+
data: result.data ?? '',
|
|
1305
|
+
}),
|
|
1306
|
+
);
|
|
1307
|
+
})
|
|
1308
|
+
.catch((e) => {
|
|
1309
|
+
if (ws.readyState === ws.OPEN) {
|
|
1310
|
+
ws.send(JSON.stringify({ type: 'snapshot-save-error', reason: String(e?.message ?? e) }));
|
|
1311
|
+
}
|
|
1312
|
+
if (verbose) console.error('[input-server] save-snapshot error:', e);
|
|
1313
|
+
logEv('error', { kind: 'save-snapshot-failed', err: String(e?.message ?? e) });
|
|
1314
|
+
});
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1080
1318
|
// ── Input events ─────────────────────────────────────────────────────
|
|
1081
1319
|
if (msg.type === 'joystick' || msg.type === 'key') {
|
|
1082
1320
|
if (ws !== hostClient && ws !== p2Client) return;
|
|
1083
|
-
if (ws === hostClient) resetHostTimeout();
|
|
1084
|
-
if (ws === p2Client) resetP2Timeout();
|
|
1085
|
-
// Track input counts for flood investigation
|
|
1086
1321
|
const role = ws === hostClient ? 'host' : 'p2';
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
const now = Date.now();
|
|
1095
|
-
const latency = now - msg.clientTime;
|
|
1096
|
-
const bucket = _networkStats[role];
|
|
1097
|
-
if (bucket) {
|
|
1098
|
-
bucket.lastLatency = latency;
|
|
1099
|
-
}
|
|
1100
|
-
// Log latency periodically (every 5s) to avoid spam
|
|
1101
|
-
if (!_latencyLogTimer) {
|
|
1102
|
-
_latencyLogTimer = setInterval(() => {
|
|
1103
|
-
const hostActive = _latencyCount.host > 0;
|
|
1104
|
-
const p2Active = _latencyCount.p2 > 0;
|
|
1105
|
-
if (hostActive || p2Active) {
|
|
1106
|
-
const hostAvg = hostActive ? Number(_avgLatency.host.toFixed(0)) : null;
|
|
1107
|
-
const p2Avg = p2Active ? Number(_avgLatency.p2.toFixed(0)) : null;
|
|
1108
|
-
const hostLabel = hostAvg != null ? `${hostAvg}` : '--';
|
|
1109
|
-
const p2Label = p2Avg != null ? `${p2Avg}` : '--';
|
|
1110
|
-
if (logEvents || verbose) {
|
|
1111
|
-
console.error(
|
|
1112
|
-
`[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`,
|
|
1113
|
-
);
|
|
1114
|
-
}
|
|
1115
|
-
_networkStats.host.avgLatency = hostAvg;
|
|
1116
|
-
_networkStats.p2.avgLatency = p2Avg;
|
|
1117
|
-
broadcastNetworkStats();
|
|
1118
|
-
}
|
|
1119
|
-
// Reset averages
|
|
1120
|
-
_avgLatency.host = 0;
|
|
1121
|
-
_avgLatency.p2 = 0;
|
|
1122
|
-
_latencyCount.host = 0;
|
|
1123
|
-
_latencyCount.p2 = 0;
|
|
1124
|
-
}, 5000);
|
|
1125
|
-
}
|
|
1126
|
-
// Accumulate for averaging
|
|
1127
|
-
_latencyCount[role]++;
|
|
1128
|
-
_avgLatency[role] =
|
|
1129
|
-
(_avgLatency[role] * (_latencyCount[role] - 1) + latency) / _latencyCount[role];
|
|
1130
|
-
if (latency > LATENCY_SPIKE_MS) {
|
|
1131
|
-
if (bucket) {
|
|
1132
|
-
bucket.lastSpikeLatency = latency;
|
|
1133
|
-
bucket.lastSpikeAt = now;
|
|
1134
|
-
}
|
|
1135
|
-
if (logEvents || verbose) {
|
|
1136
|
-
console.error(
|
|
1137
|
-
`[event] input-latency-spike role=${role} latency=${latency}ms type=${msg.type} action=${msg.action ?? '-'} ` +
|
|
1138
|
-
`dir=${msg.direction ?? '-'} fire=${msg.fire ? 1 : 0}`,
|
|
1139
|
-
);
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
// Tag with role so onInput can include it in logEvents output
|
|
1145
|
-
// without input-server needing to know about logEvents details.
|
|
1146
|
-
msg._role = role;
|
|
1147
|
-
if (msg.type === 'joystick') {
|
|
1148
|
-
msg.joystickPort = role === 'host' ? hostPort() : p2Port();
|
|
1149
|
-
}
|
|
1150
|
-
if (onInput) onInput(msg);
|
|
1151
|
-
if (Number.isFinite(msg.inputId) && ws.readyState === ws.OPEN) {
|
|
1152
|
-
try {
|
|
1153
|
-
ws.send(JSON.stringify({ type: 'input-ack', inputId: msg.inputId }));
|
|
1154
|
-
} catch (_) {}
|
|
1155
|
-
}
|
|
1322
|
+
handleInputTransportMessage({
|
|
1323
|
+
msg,
|
|
1324
|
+
role,
|
|
1325
|
+
respond: (payload) => {
|
|
1326
|
+
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(payload));
|
|
1327
|
+
},
|
|
1328
|
+
});
|
|
1156
1329
|
return;
|
|
1157
1330
|
}
|
|
1158
1331
|
|
|
1159
1332
|
if (msg.type === 'ping') {
|
|
1160
1333
|
const role = ws === hostClient ? 'host' : ws === p2Client ? 'p2' : 'spectator';
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
} catch (_) {}
|
|
1171
|
-
if (verbose) console.error(`[ping] role=${role} pong pingId=${msg.pingId ?? '-'} `);
|
|
1334
|
+
handleInputTransportMessage({
|
|
1335
|
+
msg,
|
|
1336
|
+
role,
|
|
1337
|
+
respond: (payload) => {
|
|
1338
|
+
try {
|
|
1339
|
+
ws.send(JSON.stringify(payload));
|
|
1340
|
+
} catch (_) {}
|
|
1341
|
+
},
|
|
1342
|
+
});
|
|
1172
1343
|
return;
|
|
1173
1344
|
}
|
|
1174
1345
|
});
|
|
@@ -1267,8 +1438,11 @@ export function createInputServer(opts = {}) {
|
|
|
1267
1438
|
clearInterval(_networkStatsTimer);
|
|
1268
1439
|
_networkStatsTimer = null;
|
|
1269
1440
|
}
|
|
1441
|
+
for (const client of wss.clients) {
|
|
1442
|
+
try { client.terminate(); } catch (_) {}
|
|
1443
|
+
}
|
|
1270
1444
|
wss.close(() => resolve());
|
|
1271
1445
|
});
|
|
1272
1446
|
|
|
1273
|
-
return { wss, close };
|
|
1447
|
+
return { wss, close, handlePeerDataMessage };
|
|
1274
1448
|
}
|
|
@@ -83,7 +83,7 @@ function buildIceServers({
|
|
|
83
83
|
* @param {boolean} [opts.verbose=false] Log state changes to stderr
|
|
84
84
|
* @param {number} [opts.inputPort=9001] Port the input WebSocket listens on
|
|
85
85
|
* (embedded in the browser page)
|
|
86
|
-
* @param {number} [opts.maxSpectators=
|
|
86
|
+
* @param {number} [opts.maxSpectators=10] Maximum number of spectator connections
|
|
87
87
|
* (not counting the 2 player slots).
|
|
88
88
|
* When the limit is reached, new WebRTC
|
|
89
89
|
* connections are rejected immediately with
|
|
@@ -99,6 +99,8 @@ function buildIceServers({
|
|
|
99
99
|
* Attach tracks here: pc.addTrack(videoTrack, stream)
|
|
100
100
|
* @param {(pc: RTCPeerConnection) => void} [opts.onPeerConnected]
|
|
101
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.
|
|
102
104
|
* @returns {{ close: () => Promise<void> }}
|
|
103
105
|
*/
|
|
104
106
|
export function createWebRTCServer({
|
|
@@ -106,7 +108,7 @@ export function createWebRTCServer({
|
|
|
106
108
|
verbose = false,
|
|
107
109
|
logEvents = false,
|
|
108
110
|
inputPort = 9001,
|
|
109
|
-
maxSpectators =
|
|
111
|
+
maxSpectators = 10,
|
|
110
112
|
minBitrateKbps = 200,
|
|
111
113
|
maxBitrateKbps = 600,
|
|
112
114
|
iceStunUrls,
|
|
@@ -115,6 +117,7 @@ export function createWebRTCServer({
|
|
|
115
117
|
iceTurnPassword,
|
|
116
118
|
onOffer,
|
|
117
119
|
onPeerConnected,
|
|
120
|
+
onDataChannelInput,
|
|
118
121
|
} = {}) {
|
|
119
122
|
const iceServers = buildIceServers({
|
|
120
123
|
iceStunUrls,
|
|
@@ -467,6 +470,9 @@ export function createWebRTCServer({
|
|
|
467
470
|
if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
|
|
468
471
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
469
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 }));
|
|
470
476
|
} else if (req.url === '/favicon.ico') {
|
|
471
477
|
// Return a minimal 1×1 transparent ICO so browsers don't log a 404
|
|
472
478
|
res.writeHead(204);
|
|
@@ -610,6 +616,15 @@ export function createWebRTCServer({
|
|
|
610
616
|
function closePeer(reason) {
|
|
611
617
|
clearDisconnectTimer();
|
|
612
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
|
+
};
|
|
613
628
|
peerStatsPrev.delete(pc);
|
|
614
629
|
if (controller.sessionKey) {
|
|
615
630
|
const mapped = peerBySession.get(controller.sessionKey);
|
|
@@ -620,14 +635,16 @@ export function createWebRTCServer({
|
|
|
620
635
|
if (!wasActive && !everConnected) {
|
|
621
636
|
if (pendingPeers > 0) pendingPeers--;
|
|
622
637
|
}
|
|
623
|
-
console.error(
|
|
624
|
-
|
|
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 });
|
|
625
642
|
logLoadSnapshot('webrtc-load-change', { reason: `peer-closed:${reason}` });
|
|
626
643
|
// Tell the browser the stream died so it can reconnect immediately
|
|
627
644
|
// rather than sitting on a frozen frame.
|
|
628
645
|
if (ws.readyState === ws.OPEN) {
|
|
629
646
|
try {
|
|
630
|
-
ws.send(JSON.stringify({ type: 'peer-closed',
|
|
647
|
+
ws.send(JSON.stringify({ type: 'peer-closed', ...detail }));
|
|
631
648
|
} catch (_) {}
|
|
632
649
|
}
|
|
633
650
|
pc.close();
|
|
@@ -642,6 +659,35 @@ export function createWebRTCServer({
|
|
|
642
659
|
}
|
|
643
660
|
};
|
|
644
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
|
+
|
|
645
691
|
pc.oniceconnectionstatechange = () => {
|
|
646
692
|
const s = pc.iceConnectionState;
|
|
647
693
|
controller.iceState = s;
|
package/src/main.ts
CHANGED
|
@@ -89,6 +89,18 @@ window.addEventListener('c64-load-file', async (e: Event) => {
|
|
|
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 }
|
package/src/player/c64-player.ts
CHANGED
|
@@ -95,11 +95,11 @@ export class C64Player {
|
|
|
95
95
|
}
|
|
96
96
|
|
|
97
97
|
const contentLength = Number(response.headers.get('content-length') ?? 0);
|
|
98
|
-
let data: Uint8Array
|
|
98
|
+
let data: Uint8Array<ArrayBufferLike>;
|
|
99
99
|
|
|
100
100
|
if (contentLength > 0 && response.body) {
|
|
101
101
|
const reader = response.body.getReader();
|
|
102
|
-
const chunks: Uint8Array[] = [];
|
|
102
|
+
const chunks: Uint8Array<ArrayBufferLike>[] = [];
|
|
103
103
|
let loaded = 0;
|
|
104
104
|
|
|
105
105
|
let result = await reader.read();
|
|
@@ -271,6 +271,21 @@ export class C64Player {
|
|
|
271
271
|
this.inputHandler?.setInputMode(mode);
|
|
272
272
|
}
|
|
273
273
|
|
|
274
|
+
setActiveGamepadIndex(index: number): void {
|
|
275
|
+
this.inputHandler?.setActiveGamepadIndex(index);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
getActiveGamepadIndex(): number {
|
|
279
|
+
return this.inputHandler?.getActiveGamepadIndex() ?? -1;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
getSnapshot(): Uint8Array {
|
|
283
|
+
if (!this.emulator) {
|
|
284
|
+
throw new Error('Emulator not initialised');
|
|
285
|
+
}
|
|
286
|
+
return this.emulator.getSnapshot();
|
|
287
|
+
}
|
|
288
|
+
|
|
274
289
|
setCrtPreloadChecksDisabled(disabled: boolean): void {
|
|
275
290
|
this.disableCrtPreloadChecks = disabled;
|
|
276
291
|
this.emulator?.setCrtPreloadChecksEnabled(!disabled);
|
|
@@ -317,7 +332,7 @@ export class C64Player {
|
|
|
317
332
|
}
|
|
318
333
|
|
|
319
334
|
private assertSnapshotFormatSupported(
|
|
320
|
-
data: Uint8Array
|
|
335
|
+
data: Uint8Array<ArrayBufferLike>,
|
|
321
336
|
type: GameLoadOptions['type'],
|
|
322
337
|
source: string,
|
|
323
338
|
): void {
|
|
@@ -348,7 +363,7 @@ export class C64Player {
|
|
|
348
363
|
}
|
|
349
364
|
|
|
350
365
|
private handleCrtPreloadChecks(
|
|
351
|
-
data: Uint8Array
|
|
366
|
+
data: Uint8Array<ArrayBufferLike>,
|
|
352
367
|
source: string,
|
|
353
368
|
onProgress?: ProgressCallback,
|
|
354
369
|
): void {
|
|
@@ -381,7 +396,7 @@ export class C64Player {
|
|
|
381
396
|
}
|
|
382
397
|
|
|
383
398
|
function validateCrtSupportOrThrow(
|
|
384
|
-
data: Uint8Array
|
|
399
|
+
data: Uint8Array<ArrayBufferLike>,
|
|
385
400
|
source: string,
|
|
386
401
|
onProgress?: ProgressCallback,
|
|
387
402
|
): void {
|
|
@@ -413,7 +428,7 @@ function waitMs(ms: number): Promise<void> {
|
|
|
413
428
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
414
429
|
}
|
|
415
430
|
|
|
416
|
-
function hasViceSnapshotMagic(data: Uint8Array): boolean {
|
|
431
|
+
function hasViceSnapshotMagic(data: Uint8Array<ArrayBufferLike>): boolean {
|
|
417
432
|
const magic = 'VICE Snapshot File\x1a';
|
|
418
433
|
if (data.length < magic.length) return false;
|
|
419
434
|
for (let i = 0; i < magic.length; i++) {
|
|
@@ -40,6 +40,14 @@ export default class InputHandler {
|
|
|
40
40
|
return this.emulatorInput.getInputMode();
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
setActiveGamepadIndex(index: number): void {
|
|
44
|
+
this.emulatorInput.setActiveGamepadIndex(index);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
getActiveGamepadIndex(): number {
|
|
48
|
+
return this.emulatorInput.getActiveGamepadIndex();
|
|
49
|
+
}
|
|
50
|
+
|
|
43
51
|
private onCaptureKeyDown(e: KeyboardEvent): void {
|
|
44
52
|
// Block joystick-mapped keys (standard + mixed mode) when overlays are
|
|
45
53
|
// visible or the document is unfocused. Use the union of both key sets.
|