c64-ready 2.5.0 → 3.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 +52 -1
- package/bin/admin.mjs +7 -1
- package/bin/agent.mjs +18 -0
- package/bin/headless.mjs +1 -1
- package/dist/assets/BeachHead-CuSwFD4k.js +1 -0
- package/dist/assets/ChuckieEgg-CPqBnAOF.js +1 -0
- package/dist/assets/ForbiddenForest-DsQ9jsc8.js +1 -0
- package/dist/assets/Galaga-Cutc3p9s.js +1 -0
- package/dist/assets/Gribbly-DdZ_hHFt.js +1 -0
- package/dist/assets/Hercules-vZYKm7GG.js +1 -0
- package/dist/assets/LegendOfWilf-CxSMOjsj.js +1 -0
- package/dist/assets/MariosCementFactory-z0IZ0q30.js +1 -0
- package/dist/assets/MoleAttack-buC6ChYy.js +1 -0
- package/dist/assets/MunchyWorm-D2Zv7i0Q.js +1 -0
- package/dist/assets/ParkPatrol-CVj7hyoB.js +1 -0
- package/dist/assets/PottyPigeon-0SYpIUBa.js +1 -0
- package/dist/assets/RainbowIslands-BjfmJB8z.js +1 -0
- package/dist/assets/Stix-BU-qUCeC.js +1 -0
- package/dist/assets/Tilt-C5KtKisF.js +1 -0
- package/dist/assets/UpNDown-CATRO7Mz.js +1 -0
- package/dist/assets/Uridium-DanS2KoH.js +1 -0
- package/dist/assets/VegetablesDeluxe-C41ViimS.js +1 -0
- package/dist/assets/index-B8DSjPqI.js +243 -0
- package/dist/assets/src-DX0rJQsE.js +1 -0
- package/dist/assets/src-_trgwTvp.js +2 -0
- package/dist/assets/string-utils-CMVABfx0.js +1 -0
- package/dist/index.html +1 -1
- package/dist-ts/emulator/c64-emulator.d.ts +2 -2
- package/dist-ts/emulator/c64-emulator.js +2 -2
- package/dist-ts/emulator/c64-keys.d.ts +69 -0
- package/dist-ts/emulator/c64-keys.d.ts.map +1 -0
- package/dist-ts/emulator/c64-keys.js +69 -0
- package/dist-ts/emulator/c64-keys.js.map +1 -0
- package/dist-ts/emulator/c64-wasm.d.ts +1 -1
- package/dist-ts/emulator/gamepad-mapping.d.ts +64 -0
- package/dist-ts/emulator/gamepad-mapping.d.ts.map +1 -0
- package/dist-ts/emulator/gamepad-mapping.js +154 -0
- package/dist-ts/emulator/gamepad-mapping.js.map +1 -0
- package/dist-ts/emulator/input.d.ts +27 -78
- package/dist-ts/emulator/input.d.ts.map +1 -1
- package/dist-ts/emulator/input.js +94 -215
- package/dist-ts/emulator/input.js.map +1 -1
- package/dist-ts/headless/audio-capture.d.ts +1 -1
- package/dist-ts/headless/c64-headless.d.ts +2 -2
- package/dist-ts/headless/c64-headless.js +4 -4
- package/dist-ts/headless/frame-capture.d.ts +1 -1
- package/dist-ts/headless/input-bridge.d.ts +1 -1
- package/dist-ts/player/c64-player.d.ts +21 -5
- package/dist-ts/player/c64-player.d.ts.map +1 -1
- package/dist-ts/player/c64-player.js +32 -5
- package/dist-ts/player/c64-player.js.map +1 -1
- package/dist-ts/player/canvas-renderer.d.ts +2 -2
- package/dist-ts/player/cheevos-dev.d.ts +65 -0
- package/dist-ts/player/cheevos-dev.d.ts.map +1 -0
- package/dist-ts/player/cheevos-dev.js +237 -0
- package/dist-ts/player/cheevos-dev.js.map +1 -0
- package/dist-ts/player/cheevos-tracker-panel.d.ts +21 -0
- package/dist-ts/player/cheevos-tracker-panel.d.ts.map +1 -0
- package/dist-ts/player/cheevos-tracker-panel.js +242 -0
- package/dist-ts/player/cheevos-tracker-panel.js.map +1 -0
- package/dist-ts/player/index.d.ts +10 -7
- package/dist-ts/player/index.d.ts.map +1 -1
- package/dist-ts/player/index.js +6 -4
- package/dist-ts/player/index.js.map +1 -1
- package/dist-ts/player/input-handler.d.ts +7 -3
- package/dist-ts/player/input-handler.d.ts.map +1 -1
- package/dist-ts/player/input-handler.js +24 -1
- package/dist-ts/player/input-handler.js.map +1 -1
- package/dist-ts/player/load-formats.d.ts +1 -1
- package/dist-ts/player/local-rom-store.d.ts +23 -0
- package/dist-ts/player/local-rom-store.d.ts.map +1 -0
- package/dist-ts/player/local-rom-store.js +87 -0
- package/dist-ts/player/local-rom-store.js.map +1 -0
- package/dist-ts/player/startup-params.d.ts +7 -0
- package/dist-ts/player/startup-params.d.ts.map +1 -0
- package/dist-ts/player/startup-params.js +47 -0
- package/dist-ts/player/startup-params.js.map +1 -0
- package/dist-ts/player/ui-controller.d.ts +23 -1
- package/dist-ts/player/ui-controller.d.ts.map +1 -1
- package/dist-ts/player/ui-controller.js +665 -1
- package/dist-ts/player/ui-controller.js.map +1 -1
- package/package.json +11 -4
- package/src/emulator/c64-keys.ts +68 -0
- package/src/emulator/gamepad-mapping.ts +212 -0
- package/src/emulator/input.ts +106 -209
- package/src/headless/agent-cli.mjs +825 -0
- package/src/headless/headless-cli.mjs +10 -4
- package/src/headless/input-server.mjs +92 -17
- package/src/headless/png.mjs +72 -0
- package/src/headless/webrtc-server.mjs +458 -34
- package/src/main.ts +197 -12
- package/src/player/c64-player.ts +58 -1
- package/src/player/cheevos-dev.ts +340 -0
- package/src/player/cheevos-tracker-panel.ts +309 -0
- package/src/player/index.ts +19 -0
- package/src/player/input-handler.ts +32 -0
- package/src/player/local-rom-store.ts +126 -0
- package/src/player/startup-params.ts +40 -0
- package/src/player/ui-controller.ts +751 -0
- package/src/player/ultimate-bridge.ts +161 -0
- package/src/player/ultimate-panel.ts +315 -0
- package/src/types/c64-cheevos.d.ts +6 -0
- package/dist/assets/index-BAsZcXuS.js +0 -178
- /package/dist/assets/{marked.esm--kBm026b.js → marked.esm-fTuuvbcB.js} +0 -0
- /package/dist/assets/{purify.es-BcoGFDcJ.js → purify.es-CRM-GE0Y.js} +0 -0
|
@@ -127,6 +127,69 @@ function buildIceServers({
|
|
|
127
127
|
return iceServers;
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
+
export const DEFAULT_ICE_PORT_RANGE = '50000-50100';
|
|
131
|
+
const ROUTE_SNAPSHOT_RETRIES = 5;
|
|
132
|
+
const FALLBACK_STUN_URL = 'stun:stun.l.google.com:19302';
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Whether the server's own peer connections may allocate TURN relay candidates.
|
|
136
|
+
*
|
|
137
|
+
* A host with a public IP and a published ICE port range never needs a relay
|
|
138
|
+
* itself, but offering one lets ICE settle on server-relayed pairs — on a remote
|
|
139
|
+
* TURN service that adds a detour to every packet. Browsers still receive the
|
|
140
|
+
* TURN config via /ice-config, so clients behind strict NATs can relay.
|
|
141
|
+
*
|
|
142
|
+
* @param {string} [raw] "0"/"false"/"off"/"no" disables; anything else enables
|
|
143
|
+
* @returns {boolean}
|
|
144
|
+
*/
|
|
145
|
+
export function parseServerUseTurn(raw = process.env.ICE_SERVER_USE_TURN) {
|
|
146
|
+
const value = String(raw ?? '').trim().toLowerCase();
|
|
147
|
+
return !['0', 'false', 'off', 'no'].includes(value);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Strip turn:/turns: URLs from an iceServers list, keeping at least one STUN
|
|
152
|
+
* server so the host still gathers its server-reflexive (public) candidate.
|
|
153
|
+
*
|
|
154
|
+
* @param {RTCIceServer[]} iceServers
|
|
155
|
+
* @returns {RTCIceServer[]}
|
|
156
|
+
*/
|
|
157
|
+
export function withoutTurnServers(iceServers) {
|
|
158
|
+
const stunOnly = (iceServers ?? [])
|
|
159
|
+
.map((server) => ({
|
|
160
|
+
urls: [].concat(server?.urls ?? []).filter((url) => !/^turns?:/i.test(String(url))),
|
|
161
|
+
}))
|
|
162
|
+
.filter((server) => server.urls.length > 0);
|
|
163
|
+
return stunOnly.length > 0 ? stunOnly : [{ urls: [FALLBACK_STUN_URL] }];
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Parse the UDP/TCP port range libwebrtc may bind ICE candidates to.
|
|
168
|
+
*
|
|
169
|
+
* Without a range libwebrtc picks random ephemeral ports. Inside Docker only the
|
|
170
|
+
* published range (`-p 50000-50100:50000-50100/udp`) is reachable from outside,
|
|
171
|
+
* so direct (host/srflx) candidates fail and every peer falls back to a TURN
|
|
172
|
+
* relay — adding the relay's round trip to every input and frame.
|
|
173
|
+
*
|
|
174
|
+
* @param {string} [raw] "min-max", or "off" to let libwebrtc choose freely
|
|
175
|
+
* @returns {{ min: number, max: number } | null}
|
|
176
|
+
*/
|
|
177
|
+
export function parseIcePortRange(raw = process.env.ICE_PORT_RANGE) {
|
|
178
|
+
const value = String(raw ?? '').trim().toLowerCase() || DEFAULT_ICE_PORT_RANGE;
|
|
179
|
+
if (value === 'off' || value === '0') return null;
|
|
180
|
+
|
|
181
|
+
const match = /^(\d+)\s*-\s*(\d+)$/.exec(value);
|
|
182
|
+
const min = match ? Number(match[1]) : NaN;
|
|
183
|
+
const max = match ? Number(match[2]) : NaN;
|
|
184
|
+
if (!(min >= 1024 && max <= 65535 && min <= max)) {
|
|
185
|
+
console.error(
|
|
186
|
+
`[webrtc] invalid ICE_PORT_RANGE "${raw}" — expected "min-max" within 1024-65535; using ${DEFAULT_ICE_PORT_RANGE}`,
|
|
187
|
+
);
|
|
188
|
+
return parseIcePortRange(DEFAULT_ICE_PORT_RANGE);
|
|
189
|
+
}
|
|
190
|
+
return { min, max };
|
|
191
|
+
}
|
|
192
|
+
|
|
130
193
|
/**
|
|
131
194
|
* @param {object} opts
|
|
132
195
|
* @param {number} [opts.port=9002] HTTP + WS listen port
|
|
@@ -147,6 +210,10 @@ function buildIceServers({
|
|
|
147
210
|
* @param {string} [opts.iceTurnUsernameLabel] Optional TURN username suffix for timed creds
|
|
148
211
|
* @param {string} [opts.iceTurnUsername] Optional TURN username
|
|
149
212
|
* @param {string} [opts.iceTurnPassword] Optional TURN credential/password
|
|
213
|
+
* @param {string} [opts.icePortRange] ICE port range "min-max" or "off"
|
|
214
|
+
* (default ICE_PORT_RANGE env, else 50000-50100)
|
|
215
|
+
* @param {string|boolean} [opts.iceServerUseTurn] Let server peers use TURN (default
|
|
216
|
+
* ICE_SERVER_USE_TURN env, else enabled)
|
|
150
217
|
* @param {(pc: RTCPeerConnection) => void} opts.onOffer
|
|
151
218
|
* Called synchronously when an SDP offer arrives, BEFORE createAnswer().
|
|
152
219
|
* Attach tracks here: pc.addTrack(videoTrack, stream)
|
|
@@ -171,6 +238,8 @@ export function createWebRTCServer({
|
|
|
171
238
|
iceTurnUsernameLabel,
|
|
172
239
|
iceTurnUsername,
|
|
173
240
|
iceTurnPassword,
|
|
241
|
+
icePortRange,
|
|
242
|
+
iceServerUseTurn,
|
|
174
243
|
onOffer,
|
|
175
244
|
onPeerConnected,
|
|
176
245
|
onDataChannelInput,
|
|
@@ -188,6 +257,26 @@ export function createWebRTCServer({
|
|
|
188
257
|
});
|
|
189
258
|
|
|
190
259
|
const iceServers = buildRuntimeIceServers();
|
|
260
|
+
const portRange = parseIcePortRange(icePortRange);
|
|
261
|
+
if (verbose) {
|
|
262
|
+
console.error(
|
|
263
|
+
`[webrtc] ICE port range ${portRange ? `${portRange.min}-${portRange.max}` : 'unrestricted'}`,
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
const serverUseTurn =
|
|
267
|
+
typeof iceServerUseTurn === 'boolean' ? iceServerUseTurn : parseServerUseTurn(iceServerUseTurn);
|
|
268
|
+
if (!serverUseTurn) {
|
|
269
|
+
console.error(
|
|
270
|
+
'[webrtc] server-side TURN disabled (ICE_SERVER_USE_TURN=0); browsers still get TURN via /ice-config',
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
const buildPeerConnectionConfig = () => {
|
|
274
|
+
const runtimeIceServers = buildRuntimeIceServers();
|
|
275
|
+
return {
|
|
276
|
+
iceServers: serverUseTurn ? runtimeIceServers : withoutTurnServers(runtimeIceServers),
|
|
277
|
+
...(portRange ? { portRange } : {}),
|
|
278
|
+
};
|
|
279
|
+
};
|
|
191
280
|
|
|
192
281
|
/** Emit a structured [event] line — same format as input-server.mjs. */
|
|
193
282
|
function logEv(tag, fields = {}) {
|
|
@@ -244,31 +333,44 @@ export function createWebRTCServer({
|
|
|
244
333
|
);
|
|
245
334
|
}
|
|
246
335
|
|
|
247
|
-
async function logRouteSnapshot(pc, remoteAddr) {
|
|
336
|
+
async function logRouteSnapshot(pc, remoteAddr, attempt = 0) {
|
|
248
337
|
try {
|
|
249
338
|
const report = await pc.getStats();
|
|
250
|
-
let
|
|
339
|
+
let nominated = null;
|
|
340
|
+
const selectedPairIds = new Set();
|
|
341
|
+
const pairsById = new Map();
|
|
251
342
|
const localById = new Map();
|
|
252
343
|
const remoteById = new Map();
|
|
253
344
|
for (const stat of report.values()) {
|
|
254
|
-
if (
|
|
255
|
-
stat.
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
selected = stat;
|
|
345
|
+
if (stat.type === 'transport' && stat.selectedCandidatePairId) {
|
|
346
|
+
selectedPairIds.add(stat.selectedCandidatePairId);
|
|
347
|
+
}
|
|
348
|
+
if (stat.type === 'candidate-pair') {
|
|
349
|
+
pairsById.set(stat.id, stat);
|
|
350
|
+
if (stat.nominated && (stat.state === 'succeeded' || stat.selected)) nominated = stat;
|
|
351
|
+
}
|
|
260
352
|
if (stat.type === 'local-candidate') localById.set(stat.id, stat);
|
|
261
353
|
if (stat.type === 'remote-candidate') remoteById.set(stat.id, stat);
|
|
262
354
|
}
|
|
263
|
-
|
|
355
|
+
// Prefer the transport's selected pair: libwebrtc's nominated/state flags on
|
|
356
|
+
// candidate-pair stats can lag ICE 'connected', which left this log empty.
|
|
357
|
+
const selected =
|
|
358
|
+
[...selectedPairIds].map((id) => pairsById.get(id)).find(Boolean) ?? nominated;
|
|
359
|
+
if (!selected) {
|
|
360
|
+
if (attempt < ROUTE_SNAPSHOT_RETRIES && pc.connectionState !== 'closed') {
|
|
361
|
+
setTimeout(() => logRouteSnapshot(pc, remoteAddr, attempt + 1), 1000);
|
|
362
|
+
}
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
264
365
|
const local = localById.get(selected.localCandidateId);
|
|
265
366
|
const remote = remoteById.get(selected.remoteCandidateId);
|
|
367
|
+
const protocol = selected.protocol ?? local?.protocol ?? '-';
|
|
266
368
|
const rttMs = Number.isFinite(selected.currentRoundTripTime)
|
|
267
369
|
? Math.round(selected.currentRoundTripTime * 1000)
|
|
268
370
|
: null;
|
|
269
371
|
logEv('webrtc-route', {
|
|
270
372
|
addr: remoteAddr,
|
|
271
|
-
protocol
|
|
373
|
+
protocol,
|
|
272
374
|
localType: local?.candidateType ?? '-',
|
|
273
375
|
remoteType: remote?.candidateType ?? '-',
|
|
274
376
|
networkType: local?.networkType ?? '-',
|
|
@@ -276,7 +378,7 @@ export function createWebRTCServer({
|
|
|
276
378
|
});
|
|
277
379
|
if (verbose) {
|
|
278
380
|
console.error(
|
|
279
|
-
`[webrtc-route] addr=${remoteAddr} protocol=${
|
|
381
|
+
`[webrtc-route] addr=${remoteAddr} protocol=${protocol} local=${local?.candidateType ?? '-'} remote=${remote?.candidateType ?? '-'} net=${local?.networkType ?? '-'} rtt=${rttMs ?? '-'}ms`,
|
|
280
382
|
);
|
|
281
383
|
}
|
|
282
384
|
} catch (_) {
|
|
@@ -524,11 +626,235 @@ export function createWebRTCServer({
|
|
|
524
626
|
return sessionKey;
|
|
525
627
|
}
|
|
526
628
|
|
|
629
|
+
function applyAnswerBitrate(sdp) {
|
|
630
|
+
if (!sdp) return sdp;
|
|
631
|
+
return sdp.replace(/(a=rtpmap:(\d+) VP8\/\d+\r?\n)/, (match, line, pt) => {
|
|
632
|
+
const minKbps = Math.max(50, minBitrateKbpsSafe);
|
|
633
|
+
const maxKbps = Math.max(minKbps, maxBitrateKbpsSafe);
|
|
634
|
+
const fmtp = `a=fmtp:${pt} x-google-min-bitrate=${minKbps};x-google-max-bitrate=${maxKbps}\r\n`;
|
|
635
|
+
return line + fmtp;
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
function readRequestBody(req, limitBytes = 1024 * 1024) {
|
|
640
|
+
return new Promise((resolve, reject) => {
|
|
641
|
+
const chunks = [];
|
|
642
|
+
let size = 0;
|
|
643
|
+
req.on('data', (chunk) => {
|
|
644
|
+
size += chunk.length;
|
|
645
|
+
if (size > limitBytes) {
|
|
646
|
+
reject(new Error('request body too large'));
|
|
647
|
+
req.destroy();
|
|
648
|
+
return;
|
|
649
|
+
}
|
|
650
|
+
chunks.push(chunk);
|
|
651
|
+
});
|
|
652
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
653
|
+
req.on('error', reject);
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function sendText(res, status, body, headers = {}) {
|
|
658
|
+
res.writeHead(status, {
|
|
659
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
660
|
+
'Cache-Control': 'no-store',
|
|
661
|
+
...headers,
|
|
662
|
+
});
|
|
663
|
+
res.end(body);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function parseTrickleIceSdpFrag(body) {
|
|
667
|
+
const candidates = [];
|
|
668
|
+
let currentMid = null;
|
|
669
|
+
let currentMLineIndex = null;
|
|
670
|
+
for (const rawLine of String(body ?? '').split(/\r?\n/)) {
|
|
671
|
+
const line = rawLine.trim();
|
|
672
|
+
if (!line) continue;
|
|
673
|
+
if (line.startsWith('m=')) {
|
|
674
|
+
currentMLineIndex = currentMLineIndex == null ? 0 : currentMLineIndex + 1;
|
|
675
|
+
currentMid = null;
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
if (line.startsWith('a=mid:')) {
|
|
679
|
+
currentMid = line.slice('a=mid:'.length);
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
if (line.startsWith('a=candidate:')) {
|
|
683
|
+
candidates.push({
|
|
684
|
+
candidate: line.slice(2),
|
|
685
|
+
sdpMid: currentMid,
|
|
686
|
+
sdpMLineIndex: currentMLineIndex ?? 0,
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
return candidates;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function waitForIceGatheringComplete(pc, timeoutMs = 1500) {
|
|
694
|
+
if (pc.iceGatheringState === 'complete') return Promise.resolve();
|
|
695
|
+
return new Promise((resolve) => {
|
|
696
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
697
|
+
function finish() {
|
|
698
|
+
clearTimeout(timer);
|
|
699
|
+
pc.removeEventListener?.('icegatheringstatechange', onStateChange);
|
|
700
|
+
resolve();
|
|
701
|
+
}
|
|
702
|
+
function onStateChange() {
|
|
703
|
+
if (pc.iceGatheringState === 'complete') finish();
|
|
704
|
+
}
|
|
705
|
+
pc.addEventListener?.('icegatheringstatechange', onStateChange);
|
|
706
|
+
pc.onicegatheringstatechange = onStateChange;
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const whepSessions = new Map();
|
|
711
|
+
|
|
712
|
+
function closeWhepSession(sessionId, reason = 'whep-closed') {
|
|
713
|
+
const controller = whepSessions.get(sessionId);
|
|
714
|
+
if (!controller) return false;
|
|
715
|
+
controller.closePeer?.(reason);
|
|
716
|
+
return true;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
async function handleWhepPost(req, res) {
|
|
720
|
+
const currentTotal = activePeers.size + pendingPeers;
|
|
721
|
+
if (currentTotal >= MAX_CONNECTIONS) {
|
|
722
|
+
sendText(res, 429, 'capacity full\n', {
|
|
723
|
+
'Retry-After': '10',
|
|
724
|
+
});
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
const offerSdp = await readRequestBody(req);
|
|
729
|
+
if (!offerSdp.trim()) {
|
|
730
|
+
sendText(res, 400, 'missing SDP offer\n');
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
const remoteAddr = req.socket.remoteAddress;
|
|
735
|
+
const sessionId = crypto.randomUUID();
|
|
736
|
+
pendingPeers++;
|
|
737
|
+
const pc = new RTCPeerConnection(buildPeerConnectionConfig());
|
|
738
|
+
const controller = {
|
|
739
|
+
pc,
|
|
740
|
+
ws: null,
|
|
741
|
+
remoteAddr,
|
|
742
|
+
connected: false,
|
|
743
|
+
iceState: 'new',
|
|
744
|
+
sessionKey: sessionId,
|
|
745
|
+
closePeer: null,
|
|
746
|
+
};
|
|
747
|
+
let everConnected = false;
|
|
748
|
+
let closed = false;
|
|
749
|
+
let disconnectTimer = null;
|
|
750
|
+
peerControllers.add(controller);
|
|
751
|
+
peerBySession.set(sessionId, controller);
|
|
752
|
+
whepSessions.set(sessionId, controller);
|
|
753
|
+
logEv('whep-peer-created', { addr: remoteAddr, session: sessionId });
|
|
754
|
+
logLoadSnapshot('webrtc-load-change', { reason: 'whep-peer-created' });
|
|
755
|
+
|
|
756
|
+
const pendingTimeout = setTimeout(() => {
|
|
757
|
+
if (!everConnected) closeWhepSession(sessionId, 'whep-connect-timeout');
|
|
758
|
+
}, 30_000);
|
|
759
|
+
if (typeof pendingTimeout.unref === 'function') pendingTimeout.unref();
|
|
760
|
+
|
|
761
|
+
function clearDisconnectTimer() {
|
|
762
|
+
if (disconnectTimer) {
|
|
763
|
+
clearTimeout(disconnectTimer);
|
|
764
|
+
disconnectTimer = null;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function closePeer(reason) {
|
|
769
|
+
if (closed) return;
|
|
770
|
+
closed = true;
|
|
771
|
+
clearTimeout(pendingTimeout);
|
|
772
|
+
clearDisconnectTimer();
|
|
773
|
+
const wasActive = activePeers.delete(pc);
|
|
774
|
+
peerStatsPrev.delete(pc);
|
|
775
|
+
peerControllers.delete(controller);
|
|
776
|
+
peerBySession.delete(sessionId);
|
|
777
|
+
whepSessions.delete(sessionId);
|
|
778
|
+
if (!wasActive && !everConnected && pendingPeers > 0) pendingPeers--;
|
|
779
|
+
logEv('whep-peer-closed', { addr: remoteAddr, session: sessionId, reason });
|
|
780
|
+
logLoadSnapshot('webrtc-load-change', { reason: `whep-peer-closed:${reason}` });
|
|
781
|
+
try {
|
|
782
|
+
pc.close();
|
|
783
|
+
} catch (_) {}
|
|
784
|
+
}
|
|
785
|
+
controller.closePeer = closePeer;
|
|
786
|
+
|
|
787
|
+
pc.oniceconnectionstatechange = () => {
|
|
788
|
+
const s = pc.iceConnectionState;
|
|
789
|
+
controller.iceState = s;
|
|
790
|
+
if (s === 'connected' || s === 'completed') {
|
|
791
|
+
clearDisconnectTimer();
|
|
792
|
+
if (!everConnected) {
|
|
793
|
+
everConnected = true;
|
|
794
|
+
if (pendingPeers > 0) pendingPeers--;
|
|
795
|
+
}
|
|
796
|
+
controller.connected = true;
|
|
797
|
+
activePeers.add(pc);
|
|
798
|
+
logEv('whep-ice-connected', { addr: remoteAddr, session: sessionId, state: s });
|
|
799
|
+
logLoadSnapshot('webrtc-load-change', { reason: `whep-ice-${s}` });
|
|
800
|
+
logRouteSnapshot(pc, remoteAddr);
|
|
801
|
+
onPeerConnected?.(pc);
|
|
802
|
+
} else if (s === 'disconnected') {
|
|
803
|
+
activePeers.delete(pc);
|
|
804
|
+
controller.connected = false;
|
|
805
|
+
logEv('whep-ice-disconnected', { addr: remoteAddr, session: sessionId, grace: 6000 });
|
|
806
|
+
clearDisconnectTimer();
|
|
807
|
+
disconnectTimer = setTimeout(() => {
|
|
808
|
+
logEv('whep-ice-grace-expired', { addr: remoteAddr, session: sessionId });
|
|
809
|
+
closePeer('whep-disconnected-timeout');
|
|
810
|
+
}, 6000);
|
|
811
|
+
if (typeof disconnectTimer.unref === 'function') disconnectTimer.unref();
|
|
812
|
+
} else if (s === 'failed' || s === 'closed') {
|
|
813
|
+
closePeer(s);
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
|
|
817
|
+
try {
|
|
818
|
+
await pc.setRemoteDescription({ type: 'offer', sdp: offerSdp });
|
|
819
|
+
onOffer?.(pc);
|
|
820
|
+
const answer = await pc.createAnswer();
|
|
821
|
+
answer.sdp = applyAnswerBitrate(answer.sdp);
|
|
822
|
+
await pc.setLocalDescription(answer);
|
|
823
|
+
await waitForIceGatheringComplete(pc);
|
|
824
|
+
const body = pc.localDescription?.sdp ?? answer.sdp ?? '';
|
|
825
|
+
res.writeHead(201, {
|
|
826
|
+
'Content-Type': 'application/sdp',
|
|
827
|
+
'Cache-Control': 'no-store',
|
|
828
|
+
Location: `/whep/${encodeURIComponent(sessionId)}`,
|
|
829
|
+
});
|
|
830
|
+
res.end(body);
|
|
831
|
+
} catch (err) {
|
|
832
|
+
closePeer('whep-offer-error');
|
|
833
|
+
sendText(res, 400, `invalid WHEP offer: ${err?.message ?? err}\n`);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
async function handleWhepPatch(req, res, sessionId) {
|
|
838
|
+
const controller = whepSessions.get(sessionId);
|
|
839
|
+
if (!controller) {
|
|
840
|
+
sendText(res, 404, 'WHEP session not found\n');
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
const body = await readRequestBody(req);
|
|
844
|
+
const candidates = parseTrickleIceSdpFrag(body);
|
|
845
|
+
for (const candidate of candidates) {
|
|
846
|
+
await controller.pc.addIceCandidate(candidate);
|
|
847
|
+
}
|
|
848
|
+
res.writeHead(204, { 'Cache-Control': 'no-store' });
|
|
849
|
+
res.end();
|
|
850
|
+
}
|
|
851
|
+
|
|
527
852
|
const senderTelemetryTimer = setInterval(() => {
|
|
528
853
|
sampleSenderTelemetry().catch(() => {});
|
|
529
854
|
}, 5000);
|
|
530
855
|
|
|
531
856
|
const httpServer = http.createServer((req, res) => {
|
|
857
|
+
const reqUrl = new URL(req.url || '/', 'http://localhost');
|
|
532
858
|
if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
|
|
533
859
|
const requestIceServers = buildRuntimeIceServers();
|
|
534
860
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
@@ -539,6 +865,22 @@ export function createWebRTCServer({
|
|
|
539
865
|
const requestIceServers = buildRuntimeIceServers();
|
|
540
866
|
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
541
867
|
res.end(JSON.stringify({ iceServers: requestIceServers }));
|
|
868
|
+
} else if (req.method === 'POST' && reqUrl.pathname === '/whep') {
|
|
869
|
+
handleWhepPost(req, res).catch((err) => {
|
|
870
|
+
console.error('[webrtc] WHEP POST error:', err?.message ?? err);
|
|
871
|
+
if (!res.headersSent) sendText(res, 500, 'WHEP offer failed\n');
|
|
872
|
+
});
|
|
873
|
+
} else if (req.method === 'PATCH' && reqUrl.pathname.startsWith('/whep/')) {
|
|
874
|
+
const sessionId = decodeURIComponent(reqUrl.pathname.slice('/whep/'.length));
|
|
875
|
+
handleWhepPatch(req, res, sessionId).catch((err) => {
|
|
876
|
+
console.error('[webrtc] WHEP PATCH error:', err?.message ?? err);
|
|
877
|
+
if (!res.headersSent) sendText(res, 400, `WHEP ICE failed: ${err?.message ?? err}\n`);
|
|
878
|
+
});
|
|
879
|
+
} else if (req.method === 'DELETE' && reqUrl.pathname.startsWith('/whep/')) {
|
|
880
|
+
const sessionId = decodeURIComponent(reqUrl.pathname.slice('/whep/'.length));
|
|
881
|
+
closeWhepSession(sessionId, 'whep-delete');
|
|
882
|
+
res.writeHead(204, { 'Cache-Control': 'no-store' });
|
|
883
|
+
res.end();
|
|
542
884
|
} else if (req.url === '/favicon.ico') {
|
|
543
885
|
// Return a minimal 1×1 transparent ICO so browsers don't log a 404
|
|
544
886
|
res.writeHead(204);
|
|
@@ -620,7 +962,7 @@ export function createWebRTCServer({
|
|
|
620
962
|
logEv('webrtc-peer-connected', { addr: remoteAddr });
|
|
621
963
|
logLoadSnapshot('webrtc-load-change', { reason: 'peer-connected' });
|
|
622
964
|
|
|
623
|
-
const pc = new RTCPeerConnection(
|
|
965
|
+
const pc = new RTCPeerConnection(buildPeerConnectionConfig());
|
|
624
966
|
const controller = {
|
|
625
967
|
pc,
|
|
626
968
|
ws,
|
|
@@ -648,6 +990,7 @@ export function createWebRTCServer({
|
|
|
648
990
|
|
|
649
991
|
// Track whether this peer has ever reached ICE connected (to manage pendingPeers correctly).
|
|
650
992
|
let everConnected = false;
|
|
993
|
+
let closed = false;
|
|
651
994
|
const pendingRemoteCandidates = [];
|
|
652
995
|
|
|
653
996
|
async function addRemoteCandidate(candidate, source = 'live') {
|
|
@@ -680,6 +1023,8 @@ export function createWebRTCServer({
|
|
|
680
1023
|
}
|
|
681
1024
|
|
|
682
1025
|
function closePeer(reason) {
|
|
1026
|
+
if (closed) return;
|
|
1027
|
+
closed = true;
|
|
683
1028
|
clearDisconnectTimer();
|
|
684
1029
|
const wasActive = activePeers.delete(pc);
|
|
685
1030
|
const detail = {
|
|
@@ -784,6 +1129,7 @@ export function createWebRTCServer({
|
|
|
784
1129
|
controller.connected = false;
|
|
785
1130
|
logEv('webrtc-ice-disconnected', { addr: remoteAddr, grace: 6000 });
|
|
786
1131
|
logLoadSnapshot('webrtc-load-change', { reason: 'ice-disconnected' });
|
|
1132
|
+
clearDisconnectTimer();
|
|
787
1133
|
disconnectTimer = setTimeout(() => {
|
|
788
1134
|
console.error(`[webrtc] ICE 'disconnected' grace expired (${remoteAddr}) — closing`);
|
|
789
1135
|
logEv('webrtc-ice-grace-expired', { addr: remoteAddr });
|
|
@@ -831,17 +1177,7 @@ export function createWebRTCServer({
|
|
|
831
1177
|
// smaller frames which reduces encode latency and queuing delay.
|
|
832
1178
|
// x-google-min-bitrate prevents the encoder from dropping to 0 kbps
|
|
833
1179
|
// (which causes I-frame-only bursts on reconnect).
|
|
834
|
-
|
|
835
|
-
if (sdp) {
|
|
836
|
-
// Find VP8 payload type in the offer and append fmtp constraints
|
|
837
|
-
sdp = sdp.replace(/(a=rtpmap:(\d+) VP8\/\d+\r?\n)/, (match, line, pt) => {
|
|
838
|
-
const minKbps = Math.max(50, minBitrateKbpsSafe);
|
|
839
|
-
const maxKbps = Math.max(minKbps, maxBitrateKbpsSafe);
|
|
840
|
-
const fmtp = `a=fmtp:${pt} x-google-min-bitrate=${minKbps};x-google-max-bitrate=${maxKbps}\r\n`;
|
|
841
|
-
return line + fmtp;
|
|
842
|
-
});
|
|
843
|
-
answer.sdp = sdp;
|
|
844
|
-
}
|
|
1180
|
+
answer.sdp = applyAnswerBitrate(answer.sdp);
|
|
845
1181
|
|
|
846
1182
|
await pc.setLocalDescription(answer);
|
|
847
1183
|
|
|
@@ -972,6 +1308,7 @@ export function createWebRTCServer({
|
|
|
972
1308
|
new Promise((resolve) => {
|
|
973
1309
|
clearInterval(pingInterval);
|
|
974
1310
|
clearInterval(senderTelemetryTimer);
|
|
1311
|
+
for (const c of Array.from(peerControllers)) c.closePeer?.('server-close');
|
|
975
1312
|
wss.close(() => httpServer.close(() => resolve()));
|
|
976
1313
|
}),
|
|
977
1314
|
};
|
|
@@ -1013,7 +1350,7 @@ function buildBrowserHtml(
|
|
|
1013
1350
|
/* ── Screen ── */
|
|
1014
1351
|
#screen-wrap {
|
|
1015
1352
|
position: relative;
|
|
1016
|
-
width: 768px;
|
|
1353
|
+
width: min(768px, 100%); aspect-ratio: 48 / 34;
|
|
1017
1354
|
flex-shrink: 0;
|
|
1018
1355
|
}
|
|
1019
1356
|
#screen {
|
|
@@ -1049,6 +1386,7 @@ function buildBrowserHtml(
|
|
|
1049
1386
|
|
|
1050
1387
|
/* ── Controls bar ── */
|
|
1051
1388
|
.controls-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
|
1389
|
+
.controls-row[hidden] { display: none; }
|
|
1052
1390
|
button {
|
|
1053
1391
|
padding: 5px 12px; border-radius: 3px; border: 1px solid #333;
|
|
1054
1392
|
background: #1a1a1a; color: #aaa; font-family: inherit; font-size: 11px;
|
|
@@ -1058,6 +1396,12 @@ function buildBrowserHtml(
|
|
|
1058
1396
|
button:disabled { opacity: 0.35; cursor: default; }
|
|
1059
1397
|
button.hidden { display: none; }
|
|
1060
1398
|
button.active { background: #1a2a1a; color: #8f8; border-color: #464; }
|
|
1399
|
+
label { font-size: 11px; letter-spacing: 0.05em; }
|
|
1400
|
+
input[type=password] {
|
|
1401
|
+
width: min(260px, 55vw); padding: 5px 8px; border-radius: 3px;
|
|
1402
|
+
border: 1px solid #333; background: #111; color: #ddd; font-family: inherit;
|
|
1403
|
+
}
|
|
1404
|
+
input[type=password]:focus { outline: 1px solid #666; border-color: #666; }
|
|
1061
1405
|
|
|
1062
1406
|
/* ── CRT drop zone hint ── */
|
|
1063
1407
|
#drop-hint {
|
|
@@ -1088,14 +1432,19 @@ function buildBrowserHtml(
|
|
|
1088
1432
|
<span id="game-status" class="badge dim">no game</span>
|
|
1089
1433
|
</div>
|
|
1090
1434
|
|
|
1091
|
-
<
|
|
1435
|
+
<form id="host-auth" class="controls-row">
|
|
1436
|
+
<label for="host-token">Admin token</label>
|
|
1437
|
+
<input id="host-token" type="password" autocomplete="current-password" required>
|
|
1438
|
+
<button id="unlock-btn" type="submit">Unlock host controls</button>
|
|
1439
|
+
<span id="auth-status" class="badge dim">spectator mode</span>
|
|
1440
|
+
</form>
|
|
1441
|
+
|
|
1442
|
+
<div id="host-controls" class="controls-row" hidden>
|
|
1092
1443
|
<button id="load-btn" title="Load a .crt cartridge file">📂 load .crt</button>
|
|
1093
1444
|
<button id="detach-btn" title="Eject cartridge → BASIC prompt" disabled>⏏ detach</button>
|
|
1094
1445
|
<button id="reset-btn" title="Hard reset (BASIC prompt)" disabled>↺ reset</button>
|
|
1095
1446
|
<button id="reboot-btn" title="Re-instantiate emulator with no game loaded">⟲ reboot</button>
|
|
1096
1447
|
<span class="sep">|</span>
|
|
1097
|
-
<button id="sync-btn" title="Flush video to live edge — use if display feels laggy">⟳ sync</button>
|
|
1098
|
-
<span class="sep">|</span>
|
|
1099
1448
|
<button id="mode-btn" title="Toggle input mode">🕹+⌨ mixed</button>
|
|
1100
1449
|
<span class="sep">|</span>
|
|
1101
1450
|
<span id="load-status" class="badge dim"></span>
|
|
@@ -1103,6 +1452,10 @@ function buildBrowserHtml(
|
|
|
1103
1452
|
<input type="file" id="file-input" accept=".crt">
|
|
1104
1453
|
</div>
|
|
1105
1454
|
|
|
1455
|
+
<div class="controls-row">
|
|
1456
|
+
<button id="sync-btn" title="Flush video to live edge — use if display feels laggy">⟳ sync</button>
|
|
1457
|
+
</div>
|
|
1458
|
+
|
|
1106
1459
|
<script>
|
|
1107
1460
|
// ── Element refs ─────────────────────────────────────────────────────────
|
|
1108
1461
|
const videoEl = document.getElementById('screen');
|
|
@@ -1112,6 +1465,11 @@ function buildBrowserHtml(
|
|
|
1112
1465
|
const audioBadge = document.getElementById('audio-status');
|
|
1113
1466
|
const inputBadge = document.getElementById('input-status');
|
|
1114
1467
|
const gameBadge = document.getElementById('game-status');
|
|
1468
|
+
const hostAuth = document.getElementById('host-auth');
|
|
1469
|
+
const hostToken = document.getElementById('host-token');
|
|
1470
|
+
const unlockBtn = document.getElementById('unlock-btn');
|
|
1471
|
+
const authStatus = document.getElementById('auth-status');
|
|
1472
|
+
const hostControls = document.getElementById('host-controls');
|
|
1115
1473
|
const loadStatus = document.getElementById('load-status');
|
|
1116
1474
|
const loadBtn = document.getElementById('load-btn');
|
|
1117
1475
|
const detachBtn = document.getElementById('detach-btn');
|
|
@@ -1428,6 +1786,24 @@ function buildBrowserHtml(
|
|
|
1428
1786
|
// ── Input server ──────────────────────────────────────────────────────────
|
|
1429
1787
|
const INPUT_PORT = ${inputPort};
|
|
1430
1788
|
let inputWs = null, inputBackoff = 1000, backoffTimer = null;
|
|
1789
|
+
let isHost = false, hostAuthRequired = true, shouldClaimHost = false, hostClaimToken = '';
|
|
1790
|
+
|
|
1791
|
+
function setHostEnabled(enabled) {
|
|
1792
|
+
isHost = enabled;
|
|
1793
|
+
hostControls.hidden = !enabled;
|
|
1794
|
+
hostAuth.hidden = enabled;
|
|
1795
|
+
if (!enabled) setBadge(authStatus, 'spectator mode', 'dim');
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
function claimHost() {
|
|
1799
|
+
if (!inputWs || inputWs.readyState !== WebSocket.OPEN) return;
|
|
1800
|
+
inputWs.send(JSON.stringify({
|
|
1801
|
+
type: 'host',
|
|
1802
|
+
username: 'player',
|
|
1803
|
+
force: true,
|
|
1804
|
+
...(hostClaimToken ? { token: hostClaimToken } : {}),
|
|
1805
|
+
}));
|
|
1806
|
+
}
|
|
1431
1807
|
|
|
1432
1808
|
function connectInput() {
|
|
1433
1809
|
if (backoffTimer) { clearTimeout(backoffTimer); backoffTimer = null; }
|
|
@@ -1436,15 +1812,23 @@ function buildBrowserHtml(
|
|
|
1436
1812
|
|
|
1437
1813
|
inputWs.onopen = () => {
|
|
1438
1814
|
inputBackoff = 1000;
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
inputWs.send(JSON.stringify({ type: 'host', username: 'player', force: true }));
|
|
1815
|
+
unlockBtn.disabled = false;
|
|
1816
|
+
setBadge(inputBadge, 'input: spectator', 'dim');
|
|
1817
|
+
if (shouldClaimHost) claimHost();
|
|
1443
1818
|
};
|
|
1444
1819
|
|
|
1445
1820
|
inputWs.onmessage = ({ data }) => {
|
|
1446
1821
|
try {
|
|
1447
1822
|
const msg = JSON.parse(data);
|
|
1823
|
+
if (msg.type === 'hello') {
|
|
1824
|
+
hostAuthRequired = msg.hostAuthRequired !== false;
|
|
1825
|
+
hostToken.required = hostAuthRequired;
|
|
1826
|
+
if (!hostAuthRequired) {
|
|
1827
|
+
hostToken.hidden = true;
|
|
1828
|
+
hostAuth.querySelector('label').hidden = true;
|
|
1829
|
+
unlockBtn.textContent = 'Take host controls';
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1448
1832
|
// Cart lifecycle
|
|
1449
1833
|
if (msg.type === 'cart-loaded' || msg.type === 'machine-reset' || msg.type === 'cart-detached' || msg.type === 'machine-rebooted') {
|
|
1450
1834
|
blurAll();
|
|
@@ -1488,17 +1872,41 @@ function buildBrowserHtml(
|
|
|
1488
1872
|
}
|
|
1489
1873
|
if (msg.type === 'cart-loading') setLoadStatus('loading…', 'warn');
|
|
1490
1874
|
if (msg.type === 'cart-load-error') setLoadStatus('error: ' + (msg.reason || '?'), 'err');
|
|
1491
|
-
if (msg.type === 'host-confirmed')
|
|
1875
|
+
if (msg.type === 'host-confirmed') {
|
|
1876
|
+
setHostEnabled(true);
|
|
1877
|
+
unlockBtn.disabled = false;
|
|
1878
|
+
hostToken.value = '';
|
|
1879
|
+
setBadge(inputBadge, 'input: host', 'ok');
|
|
1880
|
+
}
|
|
1881
|
+
if (msg.type === 'host-auth-failed') {
|
|
1882
|
+
shouldClaimHost = false;
|
|
1883
|
+
hostClaimToken = '';
|
|
1884
|
+
unlockBtn.disabled = false;
|
|
1885
|
+
hostToken.value = '';
|
|
1886
|
+
hostToken.focus();
|
|
1887
|
+
setBadge(authStatus, 'invalid token', 'err');
|
|
1888
|
+
setBadge(inputBadge, 'input: spectator', 'dim');
|
|
1889
|
+
}
|
|
1890
|
+
if (msg.type === 'host-taken' || msg.type === 'host-evicted') {
|
|
1891
|
+
shouldClaimHost = false;
|
|
1892
|
+
hostClaimToken = '';
|
|
1893
|
+
setHostEnabled(false);
|
|
1894
|
+
unlockBtn.disabled = false;
|
|
1895
|
+
setBadge(authStatus, msg.type === 'host-taken' ? 'host already active' : 'host access revoked', 'warn');
|
|
1896
|
+
setBadge(inputBadge, 'input: spectator', 'dim');
|
|
1897
|
+
}
|
|
1492
1898
|
} catch (_) {}
|
|
1493
1899
|
};
|
|
1494
1900
|
inputWs.onclose = () => {
|
|
1901
|
+
setHostEnabled(false);
|
|
1902
|
+
unlockBtn.disabled = true;
|
|
1495
1903
|
setBadge(inputBadge, 'input: retrying ' + (inputBackoff/1000).toFixed(0) + 's…', 'warn');
|
|
1496
1904
|
backoffTimer = setTimeout(() => { inputBackoff = Math.min(inputBackoff * 2, 30000); connectInput(); }, inputBackoff);
|
|
1497
1905
|
};
|
|
1498
1906
|
inputWs.onerror = () => setBadge(inputBadge, 'input: unavailable', 'err');
|
|
1499
1907
|
}
|
|
1500
1908
|
function sendInput(msg) {
|
|
1501
|
-
if (inputWs && inputWs.readyState === WebSocket.OPEN) inputWs.send(JSON.stringify(msg));
|
|
1909
|
+
if (isHost && inputWs && inputWs.readyState === WebSocket.OPEN) inputWs.send(JSON.stringify(msg));
|
|
1502
1910
|
}
|
|
1503
1911
|
// Blur any focused UI element so keyboard events go to the emulator,
|
|
1504
1912
|
// not to whichever button was last clicked.
|
|
@@ -1507,13 +1915,27 @@ function buildBrowserHtml(
|
|
|
1507
1915
|
document.activeElement.blur();
|
|
1508
1916
|
}
|
|
1509
1917
|
connectInput();
|
|
1918
|
+
hostAuth.addEventListener('submit', (e) => {
|
|
1919
|
+
e.preventDefault();
|
|
1920
|
+
const token = hostToken.value.trim();
|
|
1921
|
+
if (hostAuthRequired && !token) {
|
|
1922
|
+
setBadge(authStatus, 'token required', 'warn');
|
|
1923
|
+
hostToken.focus();
|
|
1924
|
+
return;
|
|
1925
|
+
}
|
|
1926
|
+
hostClaimToken = token;
|
|
1927
|
+
shouldClaimHost = true;
|
|
1928
|
+
unlockBtn.disabled = true;
|
|
1929
|
+
setBadge(authStatus, 'checking…', 'warn');
|
|
1930
|
+
claimHost();
|
|
1931
|
+
});
|
|
1510
1932
|
function setLoadStatus(text, cls) {
|
|
1511
1933
|
loadStatus.textContent = text;
|
|
1512
1934
|
loadStatus.className = 'badge ' + (cls || 'dim');
|
|
1513
1935
|
}
|
|
1514
1936
|
// ── CRT loading ───────────────────────────────────────────────────────────
|
|
1515
1937
|
async function loadCrt(file) {
|
|
1516
|
-
if (!file) return;
|
|
1938
|
+
if (!isHost || !file) return;
|
|
1517
1939
|
setLoadStatus('reading…', 'warn');
|
|
1518
1940
|
try {
|
|
1519
1941
|
const b64 = await new Promise((resolve, reject) => {
|
|
@@ -1569,6 +1991,7 @@ function buildBrowserHtml(
|
|
|
1569
1991
|
const MIXED_JOY_KEYS = new Set(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','z','Z','x','X']);
|
|
1570
1992
|
const PREVENT_DEFAULTS = new Set(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight',' ','Tab']);
|
|
1571
1993
|
document.addEventListener('keydown', (e) => {
|
|
1994
|
+
if (!isHost) return;
|
|
1572
1995
|
if (PREVENT_DEFAULTS.has(e.key)) e.preventDefault();
|
|
1573
1996
|
if (e.repeat) return;
|
|
1574
1997
|
const tag = e.target instanceof Element ? e.target.tagName : '';
|
|
@@ -1585,6 +2008,7 @@ function buildBrowserHtml(
|
|
|
1585
2008
|
}
|
|
1586
2009
|
});
|
|
1587
2010
|
document.addEventListener('keyup', (e) => {
|
|
2011
|
+
if (!isHost) return;
|
|
1588
2012
|
const tag = e.target instanceof Element ? e.target.tagName : '';
|
|
1589
2013
|
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
|
|
1590
2014
|
const mode = getMode();
|