c64-ready 1.0.1 → 1.2.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/dist-ts/emulator/c64-emulator.d.ts +7 -0
- package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
- package/dist-ts/emulator/c64-emulator.js +50 -6
- package/dist-ts/emulator/c64-emulator.js.map +1 -1
- package/dist-ts/emulator/constants.d.ts +3 -1
- package/dist-ts/emulator/constants.d.ts.map +1 -1
- package/dist-ts/emulator/constants.js +2 -0
- package/dist-ts/emulator/constants.js.map +1 -1
- package/dist-ts/emulator/input.d.ts +21 -1
- package/dist-ts/emulator/input.d.ts.map +1 -1
- package/dist-ts/emulator/input.js +295 -10
- package/dist-ts/emulator/input.js.map +1 -1
- package/dist-ts/types/emulator.d.ts +1 -1
- package/dist-ts/types/emulator.d.ts.map +1 -1
- package/package.json +1 -1
- package/public/games/cartridges/goat-beat.crt +0 -0
- package/src/emulator/c64-emulator.ts +6 -5
- package/src/emulator/constants.ts +5 -1
- package/src/emulator/input.ts +331 -19
- package/src/headless/headless-cli.mjs +73 -37
- package/src/headless/input-server.mjs +276 -102
- package/src/headless/webrtc-server.mjs +123 -12
- 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
|
}
|