c64-ready 0.6.1 → 0.10.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/LICENSE +22 -0
- package/README.md +91 -22
- package/bin/admin.mjs +196 -0
- package/bin/headless.mjs +26 -3
- package/bin/serve.mjs +9 -3
- package/package.json +6 -2
- package/public/games/cartridges/bubble-bobble.crt +0 -0
- package/public/games/cartridges/ghosts-n-goblins.crt +0 -0
- package/src/emulator/crt-info.ts +210 -0
- package/src/emulator/input.ts +542 -7
- package/src/headless/c64-key-map.mjs +254 -0
- package/src/headless/c64-wasm.mjs +4 -1
- package/src/headless/headless-cli.mjs +776 -123
- package/src/headless/input-server.mjs +855 -14
- package/src/headless/webrtc-encoder.mjs +251 -0
- package/src/headless/webrtc-server.mjs +1327 -0
- package/src/main.ts +5 -5
- package/src/player/c64-player.ts +24 -6
- package/src/player/input-handler.ts +22 -6
- package/src/player/ui-controller.ts +38 -0
|
@@ -0,0 +1,1327 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* webrtc-server.mjs
|
|
3
|
+
*
|
|
4
|
+
* Lightweight WebRTC signalling server.
|
|
5
|
+
*
|
|
6
|
+
* HTTP GET / → returns the self-contained browser player page (see BROWSER_HTML)
|
|
7
|
+
* WebSocket upgrade → SDP offer/answer + trickle-ICE exchange
|
|
8
|
+
*
|
|
9
|
+
* Signalling flow:
|
|
10
|
+
* 1. Browser connects via WebSocket
|
|
11
|
+
* 2. Browser creates an RTCPeerConnection and sends an SDP offer
|
|
12
|
+
* 3. Server receives the offer, calls onOffer(pc) so the caller can addTrack() BEFORE answer
|
|
13
|
+
* 4. Server creates the SDP answer and sends it back
|
|
14
|
+
* 5. Both sides exchange trickle ICE candidates
|
|
15
|
+
* 6. onPeerConnected(pc) fires once ICE reaches 'connected' / 'completed'
|
|
16
|
+
*
|
|
17
|
+
* The caller (headless-cli.mjs) is responsible for:
|
|
18
|
+
* - Calling onOffer(pc) to attach MediaStreamTracks before answer is sent
|
|
19
|
+
* - Optionally reacting to onPeerConnected(pc) for per-connection bookkeeping
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import http from 'http';
|
|
23
|
+
import { WebSocketServer } from 'ws';
|
|
24
|
+
import wrtc from '@roamhq/wrtc';
|
|
25
|
+
|
|
26
|
+
const { RTCPeerConnection } = wrtc;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* @param {object} opts
|
|
30
|
+
* @param {number} [opts.port=9002] HTTP + WS listen port
|
|
31
|
+
* @param {boolean} [opts.verbose=false] Log state changes to stderr
|
|
32
|
+
* @param {number} [opts.inputPort=9001] Port the input WebSocket listens on
|
|
33
|
+
* (embedded in the browser page)
|
|
34
|
+
* @param {number} [opts.maxSpectators=3] Maximum number of spectator connections
|
|
35
|
+
* (not counting the 2 player slots).
|
|
36
|
+
* When the limit is reached, new WebRTC
|
|
37
|
+
* connections are rejected immediately with
|
|
38
|
+
* a { type: 'capacity-full' } message.
|
|
39
|
+
* @param {number} [opts.minBitrateKbps=200] SDP x-google-min-bitrate for VP8 answer
|
|
40
|
+
* @param {number} [opts.maxBitrateKbps=600] SDP x-google-max-bitrate for VP8 answer
|
|
41
|
+
* @param {(pc: RTCPeerConnection) => void} opts.onOffer
|
|
42
|
+
* Called synchronously when an SDP offer arrives, BEFORE createAnswer().
|
|
43
|
+
* Attach tracks here: pc.addTrack(videoTrack, stream)
|
|
44
|
+
* @param {(pc: RTCPeerConnection) => void} [opts.onPeerConnected]
|
|
45
|
+
* Called once ICE reaches 'connected' or 'completed'.
|
|
46
|
+
* @returns {{ close: () => Promise<void> }}
|
|
47
|
+
*/
|
|
48
|
+
export function createWebRTCServer({
|
|
49
|
+
port = 9002,
|
|
50
|
+
verbose = false,
|
|
51
|
+
logEvents = false,
|
|
52
|
+
inputPort = 9001,
|
|
53
|
+
maxSpectators = 3,
|
|
54
|
+
minBitrateKbps = 200,
|
|
55
|
+
maxBitrateKbps = 600,
|
|
56
|
+
onOffer,
|
|
57
|
+
onPeerConnected,
|
|
58
|
+
} = {}) {
|
|
59
|
+
/** Emit a structured [event] line — same format as input-server.mjs. */
|
|
60
|
+
function logEv(tag, fields = {}) {
|
|
61
|
+
if (!logEvents) return;
|
|
62
|
+
const ts = new Date().toISOString();
|
|
63
|
+
const pairs = Object.entries(fields).map(([k, v]) => `${k}=${v}`).join(' ');
|
|
64
|
+
console.error(`[event] ${ts} ${tag}${pairs ? ' ' + pairs : ''}`);
|
|
65
|
+
}
|
|
66
|
+
// Track all active peer connections so forceKeyframe() can reach them all.
|
|
67
|
+
const activePeers = new Set();
|
|
68
|
+
const peerControllers = new Set();
|
|
69
|
+
const peerBySession = new Map();
|
|
70
|
+
const peerStatsPrev = new Map();
|
|
71
|
+
const senderTelemetry = {
|
|
72
|
+
sampledAt: Date.now(),
|
|
73
|
+
peerCount: 0,
|
|
74
|
+
avgRttMs: null,
|
|
75
|
+
sendDelayMsPerPacket: null,
|
|
76
|
+
encodeMsPerFrame: null,
|
|
77
|
+
framesSentPerSec: null,
|
|
78
|
+
framesEncodedPerSec: null,
|
|
79
|
+
bytesSentPerSec: null,
|
|
80
|
+
qualityLimitation: null,
|
|
81
|
+
};
|
|
82
|
+
let lastPressureLogAt = 0;
|
|
83
|
+
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);
|
|
90
|
+
|
|
91
|
+
// Total capacity = 2 player slots + maxSpectators.
|
|
92
|
+
// We track all in-flight WS connections (including those not yet ICE-connected)
|
|
93
|
+
// so that a burst of simultaneous connects doesn't slip past the gate.
|
|
94
|
+
const MAX_CONNECTIONS = 2 + maxSpectators;
|
|
95
|
+
let pendingPeers = 0; // WS connections not yet ICE-connected or ICE-failed
|
|
96
|
+
|
|
97
|
+
function logLoadSnapshot(tag, extra = {}) {
|
|
98
|
+
const snapshot = {
|
|
99
|
+
active: activePeers.size,
|
|
100
|
+
pending: pendingPeers,
|
|
101
|
+
total: activePeers.size + pendingPeers,
|
|
102
|
+
max: MAX_CONNECTIONS,
|
|
103
|
+
...extra,
|
|
104
|
+
};
|
|
105
|
+
logEv(tag, snapshot);
|
|
106
|
+
if (verbose) console.error(`[webrtc-load] ${tag} active=${snapshot.active} pending=${snapshot.pending} total=${snapshot.total}/${snapshot.max}`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function logRouteSnapshot(pc, remoteAddr) {
|
|
110
|
+
try {
|
|
111
|
+
const report = await pc.getStats();
|
|
112
|
+
let selected = null;
|
|
113
|
+
const localById = new Map();
|
|
114
|
+
const remoteById = new Map();
|
|
115
|
+
for (const stat of report.values()) {
|
|
116
|
+
if (stat.type === 'candidate-pair' && stat.nominated && (stat.state === 'succeeded' || stat.selected)) selected = stat;
|
|
117
|
+
if (stat.type === 'local-candidate') localById.set(stat.id, stat);
|
|
118
|
+
if (stat.type === 'remote-candidate') remoteById.set(stat.id, stat);
|
|
119
|
+
}
|
|
120
|
+
if (!selected) return;
|
|
121
|
+
const local = localById.get(selected.localCandidateId);
|
|
122
|
+
const remote = remoteById.get(selected.remoteCandidateId);
|
|
123
|
+
const rttMs = Number.isFinite(selected.currentRoundTripTime) ? Math.round(selected.currentRoundTripTime * 1000) : null;
|
|
124
|
+
logEv('webrtc-route', {
|
|
125
|
+
addr: remoteAddr,
|
|
126
|
+
protocol: selected.protocol ?? '-',
|
|
127
|
+
localType: local?.candidateType ?? '-',
|
|
128
|
+
remoteType: remote?.candidateType ?? '-',
|
|
129
|
+
networkType: local?.networkType ?? '-',
|
|
130
|
+
rttMs: rttMs ?? '-',
|
|
131
|
+
});
|
|
132
|
+
if (verbose) {
|
|
133
|
+
console.error(`[webrtc-route] addr=${remoteAddr} protocol=${selected.protocol ?? '-'} local=${local?.candidateType ?? '-'} remote=${remote?.candidateType ?? '-'} net=${local?.networkType ?? '-'} rtt=${rttMs ?? '-'}ms`);
|
|
134
|
+
}
|
|
135
|
+
} catch (_) {
|
|
136
|
+
// Best-effort diagnostics only
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function sampleSenderTelemetry() {
|
|
141
|
+
const nowWall = Date.now();
|
|
142
|
+
let peerCount = 0;
|
|
143
|
+
let rttSum = 0;
|
|
144
|
+
let rttCount = 0;
|
|
145
|
+
let deltaFramesSent = 0;
|
|
146
|
+
let deltaFramesEncoded = 0;
|
|
147
|
+
let deltaBytesSent = 0;
|
|
148
|
+
let deltaPacketsSent = 0;
|
|
149
|
+
let deltaPacketSendDelay = 0;
|
|
150
|
+
let deltaEncodeTime = 0;
|
|
151
|
+
const qualityCounts = {};
|
|
152
|
+
|
|
153
|
+
for (const pc of activePeers) {
|
|
154
|
+
peerCount++;
|
|
155
|
+
try {
|
|
156
|
+
const report = await pc.getStats();
|
|
157
|
+
let selected = null;
|
|
158
|
+
let outboundVideo = null;
|
|
159
|
+
for (const stat of report.values()) {
|
|
160
|
+
if (stat.type === 'candidate-pair' && stat.nominated && (stat.state === 'succeeded' || stat.selected)) {
|
|
161
|
+
selected = stat;
|
|
162
|
+
}
|
|
163
|
+
if (stat.type === 'outbound-rtp' && stat.kind === 'video' && !stat.isRemote) {
|
|
164
|
+
outboundVideo = stat;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (selected && Number.isFinite(selected.currentRoundTripTime)) {
|
|
169
|
+
rttSum += selected.currentRoundTripTime * 1000;
|
|
170
|
+
rttCount++;
|
|
171
|
+
}
|
|
172
|
+
if (!outboundVideo) continue;
|
|
173
|
+
|
|
174
|
+
const reason = outboundVideo.qualityLimitationReason ?? 'none';
|
|
175
|
+
qualityCounts[reason] = (qualityCounts[reason] ?? 0) + 1;
|
|
176
|
+
|
|
177
|
+
const current = {
|
|
178
|
+
timestampMs: Number.isFinite(outboundVideo.timestamp) ? outboundVideo.timestamp : nowWall,
|
|
179
|
+
framesSent: Number.isFinite(outboundVideo.framesSent) ? outboundVideo.framesSent : null,
|
|
180
|
+
framesEncoded: Number.isFinite(outboundVideo.framesEncoded) ? outboundVideo.framesEncoded : null,
|
|
181
|
+
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,
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const prev = peerStatsPrev.get(pc);
|
|
188
|
+
peerStatsPrev.set(pc, current);
|
|
189
|
+
if (!prev) continue;
|
|
190
|
+
|
|
191
|
+
if (current.framesSent != null && prev.framesSent != null && current.framesSent >= prev.framesSent) {
|
|
192
|
+
deltaFramesSent += current.framesSent - prev.framesSent;
|
|
193
|
+
}
|
|
194
|
+
if (current.framesEncoded != null && prev.framesEncoded != null && current.framesEncoded >= prev.framesEncoded) {
|
|
195
|
+
deltaFramesEncoded += current.framesEncoded - prev.framesEncoded;
|
|
196
|
+
}
|
|
197
|
+
if (current.bytesSent != null && prev.bytesSent != null && current.bytesSent >= prev.bytesSent) {
|
|
198
|
+
deltaBytesSent += current.bytesSent - prev.bytesSent;
|
|
199
|
+
}
|
|
200
|
+
if (current.packetsSent != null && prev.packetsSent != null && current.packetsSent >= prev.packetsSent) {
|
|
201
|
+
deltaPacketsSent += current.packetsSent - prev.packetsSent;
|
|
202
|
+
}
|
|
203
|
+
if (current.totalPacketSendDelay != null && prev.totalPacketSendDelay != null && current.totalPacketSendDelay >= prev.totalPacketSendDelay) {
|
|
204
|
+
deltaPacketSendDelay += current.totalPacketSendDelay - prev.totalPacketSendDelay;
|
|
205
|
+
}
|
|
206
|
+
if (current.totalEncodeTime != null && prev.totalEncodeTime != null && current.totalEncodeTime >= prev.totalEncodeTime) {
|
|
207
|
+
deltaEncodeTime += current.totalEncodeTime - prev.totalEncodeTime;
|
|
208
|
+
}
|
|
209
|
+
} catch (_) {
|
|
210
|
+
// best effort only
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const sampleIntervalS = 5;
|
|
215
|
+
senderTelemetry.sampledAt = nowWall;
|
|
216
|
+
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;
|
|
220
|
+
senderTelemetry.framesSentPerSec = deltaFramesSent / sampleIntervalS;
|
|
221
|
+
senderTelemetry.framesEncodedPerSec = deltaFramesEncoded / sampleIntervalS;
|
|
222
|
+
senderTelemetry.bytesSentPerSec = deltaBytesSent / sampleIntervalS;
|
|
223
|
+
senderTelemetry.qualityLimitation = qualityCounts;
|
|
224
|
+
|
|
225
|
+
if (peerCount > 0) {
|
|
226
|
+
const avgRttMs = Number.isFinite(senderTelemetry.avgRttMs)
|
|
227
|
+
? senderTelemetry.avgRttMs.toFixed(1)
|
|
228
|
+
: '-';
|
|
229
|
+
const encodeMs = Number.isFinite(senderTelemetry.encodeMsPerFrame)
|
|
230
|
+
? senderTelemetry.encodeMsPerFrame.toFixed(2)
|
|
231
|
+
: '-';
|
|
232
|
+
const sendDelayMs = Number.isFinite(senderTelemetry.sendDelayMsPerPacket)
|
|
233
|
+
? senderTelemetry.sendDelayMsPerPacket.toFixed(2)
|
|
234
|
+
: '-';
|
|
235
|
+
const fpsOut = Number.isFinite(senderTelemetry.framesSentPerSec)
|
|
236
|
+
? senderTelemetry.framesSentPerSec.toFixed(1)
|
|
237
|
+
: '-';
|
|
238
|
+
const fpsEncoded = Number.isFinite(senderTelemetry.framesEncodedPerSec)
|
|
239
|
+
? senderTelemetry.framesEncodedPerSec.toFixed(1)
|
|
240
|
+
: '-';
|
|
241
|
+
const bitrateKbps = Number.isFinite(senderTelemetry.bytesSentPerSec)
|
|
242
|
+
? ((senderTelemetry.bytesSentPerSec * 8) / 1000).toFixed(0)
|
|
243
|
+
: '-';
|
|
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';
|
|
249
|
+
|
|
250
|
+
logEv('webrtc-sender-telemetry', {
|
|
251
|
+
peers: peerCount,
|
|
252
|
+
fpsOut,
|
|
253
|
+
fpsEncoded,
|
|
254
|
+
encodeMs,
|
|
255
|
+
sendDelayMs,
|
|
256
|
+
bitrateKbps,
|
|
257
|
+
rttMs: avgRttMs,
|
|
258
|
+
quality: qualitySummary,
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
const pressureReasons = [];
|
|
262
|
+
if (Number.isFinite(senderTelemetry.framesSentPerSec) && senderTelemetry.framesSentPerSec < 44) {
|
|
263
|
+
pressureReasons.push('low-fps-out');
|
|
264
|
+
}
|
|
265
|
+
if (Number.isFinite(senderTelemetry.encodeMsPerFrame) && senderTelemetry.encodeMsPerFrame > 12) {
|
|
266
|
+
pressureReasons.push('slow-encode');
|
|
267
|
+
}
|
|
268
|
+
if (Number.isFinite(senderTelemetry.sendDelayMsPerPacket) && senderTelemetry.sendDelayMsPerPacket > 4) {
|
|
269
|
+
pressureReasons.push('packet-send-delay');
|
|
270
|
+
}
|
|
271
|
+
if ((qualityCounts.cpu ?? 0) > 0) pressureReasons.push('quality-cpu');
|
|
272
|
+
if ((qualityCounts.bandwidth ?? 0) > 0) pressureReasons.push('quality-bandwidth');
|
|
273
|
+
|
|
274
|
+
if (pressureReasons.length > 0) {
|
|
275
|
+
const signature = pressureReasons.join('|');
|
|
276
|
+
const now = Date.now();
|
|
277
|
+
const shouldLogPressure = signature !== lastPressureSignature || (now - lastPressureLogAt) >= 30_000;
|
|
278
|
+
if (shouldLogPressure) {
|
|
279
|
+
lastPressureSignature = signature;
|
|
280
|
+
lastPressureLogAt = now;
|
|
281
|
+
logEv('webrtc-sender-pressure', {
|
|
282
|
+
reasons: signature,
|
|
283
|
+
peers: peerCount,
|
|
284
|
+
fpsOut,
|
|
285
|
+
encodeMs,
|
|
286
|
+
sendDelayMs,
|
|
287
|
+
bitrateKbps,
|
|
288
|
+
quality: qualitySummary,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function normalizeSessionKey(raw) {
|
|
296
|
+
if (raw == null) return null;
|
|
297
|
+
const value = String(raw).trim();
|
|
298
|
+
if (!value) return null;
|
|
299
|
+
// Avoid pathological/untrusted values bloating logs/maps.
|
|
300
|
+
return value.slice(0, 128);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function bindControllerSession(controller, rawSession, source = 'offer') {
|
|
304
|
+
const sessionKey = normalizeSessionKey(rawSession);
|
|
305
|
+
if (!sessionKey) return null;
|
|
306
|
+
if (controller.sessionKey === sessionKey) return sessionKey;
|
|
307
|
+
|
|
308
|
+
if (controller.sessionKey) {
|
|
309
|
+
const mapped = peerBySession.get(controller.sessionKey);
|
|
310
|
+
if (mapped === controller) peerBySession.delete(controller.sessionKey);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const previous = peerBySession.get(sessionKey);
|
|
314
|
+
if (previous && previous !== controller) {
|
|
315
|
+
logEv('webrtc-session-replaced', {
|
|
316
|
+
session: sessionKey,
|
|
317
|
+
oldAddr: previous.remoteAddr ?? '-',
|
|
318
|
+
newAddr: controller.remoteAddr ?? '-',
|
|
319
|
+
source,
|
|
320
|
+
});
|
|
321
|
+
try { previous.closePeer?.('session-replaced'); } catch (_) {}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
peerBySession.set(sessionKey, controller);
|
|
325
|
+
controller.sessionKey = sessionKey;
|
|
326
|
+
return sessionKey;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const senderTelemetryTimer = setInterval(() => {
|
|
330
|
+
sampleSenderTelemetry().catch(() => {});
|
|
331
|
+
}, 5000);
|
|
332
|
+
|
|
333
|
+
const httpServer = http.createServer((req, res) => {
|
|
334
|
+
if (req.method === 'GET' && (req.url === '/' || req.url === '/index.html')) {
|
|
335
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
336
|
+
res.end(buildBrowserHtml(inputPort, minBitrateKbpsSafe, maxBitrateKbpsSafe));
|
|
337
|
+
} else if (req.url === '/favicon.ico') {
|
|
338
|
+
// Return a minimal 1×1 transparent ICO so browsers don't log a 404
|
|
339
|
+
res.writeHead(204);
|
|
340
|
+
res.end();
|
|
341
|
+
} else {
|
|
342
|
+
res.writeHead(404);
|
|
343
|
+
res.end('Not found');
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
const wss = new WebSocketServer({ server: httpServer });
|
|
348
|
+
|
|
349
|
+
// ── Signalling WS keepalive ───────────────────────────────────────────────
|
|
350
|
+
// After ICE negotiation the signalling WebSocket carries no traffic.
|
|
351
|
+
// Cloud load balancers, Docker bridge NAT, and OS TCP stacks typically
|
|
352
|
+
// drop idle TCP connections after 60–90 s — exactly the symptom observed
|
|
353
|
+
// in production (ws-closed firing ~60 s after ICE connected with no prior
|
|
354
|
+
// ICE disconnect event).
|
|
355
|
+
//
|
|
356
|
+
// Fix: ping every 30 s. The ws library handles pong automatically; we mark
|
|
357
|
+
// each client as alive on pong and terminate any that miss a full interval.
|
|
358
|
+
const PING_INTERVAL_MS = 30_000;
|
|
359
|
+
const pingInterval = setInterval(() => {
|
|
360
|
+
wss.clients.forEach((ws) => {
|
|
361
|
+
if (ws._sigAlive === false) {
|
|
362
|
+
// Missed previous pong — connection is dead, terminate it.
|
|
363
|
+
console.error('[webrtc] signalling ws: missed pong, terminating');
|
|
364
|
+
logEv('webrtc-sig-timeout', {});
|
|
365
|
+
ws.terminate();
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
ws._sigAlive = false; // reset; set back to true on pong
|
|
369
|
+
ws.ping();
|
|
370
|
+
});
|
|
371
|
+
}, PING_INTERVAL_MS);
|
|
372
|
+
|
|
373
|
+
wss.on('connection', (ws, req) => {
|
|
374
|
+
ws._sigAlive = true; // initialise alive flag
|
|
375
|
+
ws.on('pong', () => { ws._sigAlive = true; });
|
|
376
|
+
const remoteAddr = req.socket.remoteAddress;
|
|
377
|
+
let initialSessionId = null;
|
|
378
|
+
try {
|
|
379
|
+
const reqUrl = new URL(req.url || '/', 'http://localhost');
|
|
380
|
+
initialSessionId = reqUrl.searchParams.get('sid')
|
|
381
|
+
|| reqUrl.searchParams.get('sessionId')
|
|
382
|
+
|| null;
|
|
383
|
+
} catch (_) {}
|
|
384
|
+
|
|
385
|
+
// ── Capacity gate ─────────────────────────────────────────────────────────
|
|
386
|
+
// Count active ICE-connected peers + in-flight (pending) connections.
|
|
387
|
+
// Players take 2 of the MAX_CONNECTIONS slots; remaining slots are spectators.
|
|
388
|
+
const currentTotal = activePeers.size + pendingPeers;
|
|
389
|
+
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 });
|
|
392
|
+
try {
|
|
393
|
+
ws.send(JSON.stringify({
|
|
394
|
+
type: 'capacity-full',
|
|
395
|
+
current: currentTotal,
|
|
396
|
+
max: MAX_CONNECTIONS,
|
|
397
|
+
maxSpectators,
|
|
398
|
+
}));
|
|
399
|
+
} catch (_) {}
|
|
400
|
+
ws.close();
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
pendingPeers++;
|
|
405
|
+
console.error(`[webrtc] peer connected from ${remoteAddr}`);
|
|
406
|
+
logEv('webrtc-peer-connected', { addr: remoteAddr });
|
|
407
|
+
logLoadSnapshot('webrtc-load-change', { reason: 'peer-connected' });
|
|
408
|
+
|
|
409
|
+
const pc = new RTCPeerConnection({
|
|
410
|
+
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
|
|
411
|
+
});
|
|
412
|
+
const controller = {
|
|
413
|
+
pc,
|
|
414
|
+
ws,
|
|
415
|
+
remoteAddr,
|
|
416
|
+
connected: false,
|
|
417
|
+
iceState: 'new',
|
|
418
|
+
sessionKey: null,
|
|
419
|
+
closePeer: null,
|
|
420
|
+
};
|
|
421
|
+
peerControllers.add(controller);
|
|
422
|
+
|
|
423
|
+
// Grace timer: if ICE goes 'disconnected' we wait up to 6s for self-
|
|
424
|
+
// recovery before treating it as fatal. Many transient causes (brief
|
|
425
|
+
// packet loss, NAT keepalive gap, Node GC pause) resolve within 1-2s.
|
|
426
|
+
// Closing immediately on 'disconnected' was the root cause of the
|
|
427
|
+
// periodic video freeze observed in production.
|
|
428
|
+
let disconnectTimer = null;
|
|
429
|
+
|
|
430
|
+
function clearDisconnectTimer() {
|
|
431
|
+
if (disconnectTimer) { clearTimeout(disconnectTimer); disconnectTimer = null; }
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// Track whether this peer has ever reached ICE connected (to manage pendingPeers correctly).
|
|
435
|
+
let everConnected = false;
|
|
436
|
+
const pendingRemoteCandidates = [];
|
|
437
|
+
|
|
438
|
+
async function addRemoteCandidate(candidate, source = 'live') {
|
|
439
|
+
try {
|
|
440
|
+
await pc.addIceCandidate(candidate);
|
|
441
|
+
} catch (err) {
|
|
442
|
+
const hasRemoteDescription = !!pc.remoteDescription;
|
|
443
|
+
const signalingState = pc.signalingState;
|
|
444
|
+
const errName = err?.name ?? 'Error';
|
|
445
|
+
const errMsg = err?.message ?? String(err);
|
|
446
|
+
console.error(
|
|
447
|
+
`[webrtc] addIceCandidate failed (${source}) addr=${remoteAddr} hasRemoteDescription=${hasRemoteDescription} signalingState=${signalingState} err=${errName}: ${errMsg}`
|
|
448
|
+
);
|
|
449
|
+
logEv('webrtc-ice-candidate-error', {
|
|
450
|
+
addr: remoteAddr,
|
|
451
|
+
source,
|
|
452
|
+
hasRemoteDescription,
|
|
453
|
+
signalingState,
|
|
454
|
+
err: errName,
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
async function flushRemoteCandidates(source = 'post-offer') {
|
|
460
|
+
if (!pc.remoteDescription || pendingRemoteCandidates.length === 0) return;
|
|
461
|
+
const queued = pendingRemoteCandidates.splice(0, pendingRemoteCandidates.length);
|
|
462
|
+
for (const candidate of queued) {
|
|
463
|
+
await addRemoteCandidate(candidate, source);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function closePeer(reason) {
|
|
468
|
+
clearDisconnectTimer();
|
|
469
|
+
const wasActive = activePeers.delete(pc);
|
|
470
|
+
peerStatsPrev.delete(pc);
|
|
471
|
+
if (controller.sessionKey) {
|
|
472
|
+
const mapped = peerBySession.get(controller.sessionKey);
|
|
473
|
+
if (mapped === controller) peerBySession.delete(controller.sessionKey);
|
|
474
|
+
}
|
|
475
|
+
peerControllers.delete(controller);
|
|
476
|
+
// Decrement pendingPeers only if this peer never made it to ICE connected.
|
|
477
|
+
if (!wasActive && !everConnected) { if (pendingPeers > 0) pendingPeers--; }
|
|
478
|
+
console.error(`[webrtc] closing peer (${remoteAddr}): ${reason}`);
|
|
479
|
+
logEv('webrtc-peer-closed', { addr: remoteAddr, reason });
|
|
480
|
+
logLoadSnapshot('webrtc-load-change', { reason: `peer-closed:${reason}` });
|
|
481
|
+
// Tell the browser the stream died so it can reconnect immediately
|
|
482
|
+
// rather than sitting on a frozen frame.
|
|
483
|
+
if (ws.readyState === ws.OPEN) {
|
|
484
|
+
try { ws.send(JSON.stringify({ type: 'peer-closed', reason })); } catch (_) {}
|
|
485
|
+
}
|
|
486
|
+
pc.close();
|
|
487
|
+
}
|
|
488
|
+
controller.closePeer = closePeer;
|
|
489
|
+
bindControllerSession(controller, initialSessionId, 'query');
|
|
490
|
+
|
|
491
|
+
// ── Trickle ICE: forward server-side candidates to the browser ───────
|
|
492
|
+
pc.onicecandidate = ({ candidate }) => {
|
|
493
|
+
if (candidate && ws.readyState === ws.OPEN) {
|
|
494
|
+
ws.send(JSON.stringify({ type: 'candidate', candidate }));
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
pc.oniceconnectionstatechange = () => {
|
|
499
|
+
const s = pc.iceConnectionState;
|
|
500
|
+
controller.iceState = s;
|
|
501
|
+
// Always log ICE state changes — they are infrequent and critical for
|
|
502
|
+
// diagnosing stream freezes. This fires regardless of --verbose.
|
|
503
|
+
console.error(`[webrtc] ICE state → ${s} (${remoteAddr})`);
|
|
504
|
+
|
|
505
|
+
if (s === 'connected' || s === 'completed') {
|
|
506
|
+
// Recovered from disconnected — cancel any pending close timer.
|
|
507
|
+
clearDisconnectTimer();
|
|
508
|
+
// First time reaching connected: move out of pending and into active.
|
|
509
|
+
// On recovery from 'disconnected' grace: re-add to active (pendingPeers already at 0 for this peer).
|
|
510
|
+
if (!everConnected) {
|
|
511
|
+
if (pendingPeers > 0) pendingPeers--;
|
|
512
|
+
everConnected = true;
|
|
513
|
+
}
|
|
514
|
+
controller.connected = true;
|
|
515
|
+
activePeers.add(pc);
|
|
516
|
+
logEv('webrtc-ice-connected', { addr: remoteAddr, state: s });
|
|
517
|
+
logLoadSnapshot('webrtc-load-change', { reason: `ice-${s}` });
|
|
518
|
+
logRouteSnapshot(pc, remoteAddr);
|
|
519
|
+
onPeerConnected?.(pc);
|
|
520
|
+
} else if (s === 'disconnected') {
|
|
521
|
+
// Transient — remove from active peers so we stop pushing frames to
|
|
522
|
+
// a peer that may not be receiving them, but do NOT close yet.
|
|
523
|
+
// Give ICE 6 seconds to self-recover before treating it as fatal.
|
|
524
|
+
activePeers.delete(pc);
|
|
525
|
+
controller.connected = false;
|
|
526
|
+
logEv('webrtc-ice-disconnected', { addr: remoteAddr, grace: 6000 });
|
|
527
|
+
logLoadSnapshot('webrtc-load-change', { reason: 'ice-disconnected' });
|
|
528
|
+
disconnectTimer = setTimeout(() => {
|
|
529
|
+
console.error(`[webrtc] ICE 'disconnected' grace expired (${remoteAddr}) — closing`);
|
|
530
|
+
logEv('webrtc-ice-grace-expired', { addr: remoteAddr });
|
|
531
|
+
closePeer('disconnected-timeout');
|
|
532
|
+
}, 6000);
|
|
533
|
+
} else if (s === 'failed' || s === 'closed') {
|
|
534
|
+
logEv('webrtc-ice-terminal', { addr: remoteAddr, state: s });
|
|
535
|
+
closePeer(s);
|
|
536
|
+
} else {
|
|
537
|
+
// checking / new — log but no action needed
|
|
538
|
+
logEv('webrtc-ice-state', { addr: remoteAddr, state: s });
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
ws.on('message', async (data) => {
|
|
543
|
+
let msg;
|
|
544
|
+
try {
|
|
545
|
+
msg = JSON.parse(typeof data === 'string' ? data : data.toString('utf8'));
|
|
546
|
+
} catch {
|
|
547
|
+
if (verbose) console.error('[webrtc] bad JSON from peer, ignoring');
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
try {
|
|
552
|
+
if (msg.type === 'offer') {
|
|
553
|
+
bindControllerSession(controller, msg.sessionId ?? msg.sid ?? msg.clientSessionId ?? null, 'offer');
|
|
554
|
+
await pc.setRemoteDescription(msg);
|
|
555
|
+
await flushRemoteCandidates('post-offer');
|
|
556
|
+
|
|
557
|
+
// ── CRITICAL: tracks must be added BEFORE createAnswer() ─────────
|
|
558
|
+
// onOffer is called synchronously here so the caller can addTrack().
|
|
559
|
+
onOffer?.(pc);
|
|
560
|
+
|
|
561
|
+
const answer = await pc.createAnswer();
|
|
562
|
+
|
|
563
|
+
// ── Low-latency SDP tweaks ────────────────────────────────────────
|
|
564
|
+
// Inject x-google-min/max-bitrate into the video m-section of the
|
|
565
|
+
// SDP answer. The VP8 encoder in @roamhq/wrtc respects these fmtp
|
|
566
|
+
// parameters: a tight bitrate ceiling (800 kbps for 384×272 @ 50fps
|
|
567
|
+
// is well above visually lossless) forces the encoder to produce
|
|
568
|
+
// smaller frames which reduces encode latency and queuing delay.
|
|
569
|
+
// x-google-min-bitrate prevents the encoder from dropping to 0 kbps
|
|
570
|
+
// (which causes I-frame-only bursts on reconnect).
|
|
571
|
+
let sdp = answer.sdp;
|
|
572
|
+
if (sdp) {
|
|
573
|
+
// 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
|
+
);
|
|
583
|
+
answer.sdp = sdp;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
await pc.setLocalDescription(answer);
|
|
587
|
+
|
|
588
|
+
if (ws.readyState === ws.OPEN) {
|
|
589
|
+
ws.send(JSON.stringify(pc.localDescription));
|
|
590
|
+
}
|
|
591
|
+
if (verbose) console.error(`[webrtc] answered offer from ${remoteAddr}`);
|
|
592
|
+
|
|
593
|
+
} else if (msg.type === 'candidate' && msg.candidate) {
|
|
594
|
+
if (!pc.remoteDescription) {
|
|
595
|
+
pendingRemoteCandidates.push(msg.candidate);
|
|
596
|
+
if (verbose) {
|
|
597
|
+
console.error(`[webrtc] queued remote candidate (${pendingRemoteCandidates.length}) pending offer (${remoteAddr})`);
|
|
598
|
+
}
|
|
599
|
+
} else {
|
|
600
|
+
await addRemoteCandidate(msg.candidate, 'live');
|
|
601
|
+
}
|
|
602
|
+
} else if (msg.type === 'ping') {
|
|
603
|
+
// Browser-side heartbeat — reply immediately so the browser knows
|
|
604
|
+
// the connection is alive and resets its own reconnect timer.
|
|
605
|
+
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify({ type: 'pong' }));
|
|
606
|
+
}
|
|
607
|
+
} catch (err) {
|
|
608
|
+
console.error('[webrtc] signalling error:', err.message);
|
|
609
|
+
}
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
ws.on('close', () => {
|
|
613
|
+
if (verbose) console.error(`[webrtc] peer ws closed (${remoteAddr})`);
|
|
614
|
+
closePeer('ws-closed');
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
ws.on('error', (err) => {
|
|
618
|
+
console.error(`[webrtc] ws error (${remoteAddr}):`, err.message);
|
|
619
|
+
});
|
|
620
|
+
});
|
|
621
|
+
|
|
622
|
+
httpServer.listen(port, '0.0.0.0', () => {
|
|
623
|
+
console.error(`[webrtc] player page → http://0.0.0.0:${port}/`);
|
|
624
|
+
console.error(`[webrtc] signalling ws → ws://0.0.0.0:${port}/`);
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
httpServer.on('error', (err) => {
|
|
628
|
+
console.error(`[webrtc] HTTP server error: ${err.message}`);
|
|
629
|
+
});
|
|
630
|
+
|
|
631
|
+
return {
|
|
632
|
+
/**
|
|
633
|
+
* Force an immediate VP8 keyframe (IDR) on all active peer connections.
|
|
634
|
+
*
|
|
635
|
+
* Why this fixes post-load lag:
|
|
636
|
+
* After c64_loadCartridge() the frame loop resumes but the VP8 encoder
|
|
637
|
+
* only emits an IDR at its normal interval (~2-3 seconds). The browser
|
|
638
|
+
* cannot decode any frame until it receives an IDR — so it shows a
|
|
639
|
+
* frozen/blank screen for up to 2-3 seconds after the load completes,
|
|
640
|
+
* even though the server is pushing live frames.
|
|
641
|
+
*
|
|
642
|
+
* Calling sender.replaceTrack(sameTrack) on the video sender triggers
|
|
643
|
+
* libwebrtc to immediately emit an IDR on the next encoded frame.
|
|
644
|
+
* The browser decoder gets a complete reference frame within one frame
|
|
645
|
+
* period (≤20ms @ 50fps) and resumes rendering immediately.
|
|
646
|
+
*
|
|
647
|
+
* @param {MediaStreamTrack} videoTrack The current video track.
|
|
648
|
+
*/
|
|
649
|
+
forceKeyframe(videoTrack) {
|
|
650
|
+
if (!videoTrack) return;
|
|
651
|
+
let count = 0;
|
|
652
|
+
for (const pc of activePeers) {
|
|
653
|
+
try {
|
|
654
|
+
for (const sender of pc.getSenders()) {
|
|
655
|
+
if (sender.track && sender.track.kind === 'video') {
|
|
656
|
+
sender.replaceTrack(videoTrack).catch(() => {});
|
|
657
|
+
count++;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
} catch (_) {}
|
|
661
|
+
}
|
|
662
|
+
if (verbose) console.error(`[webrtc] forceKeyframe: triggered on ${count} sender(s)`);
|
|
663
|
+
},
|
|
664
|
+
getTelemetrySnapshot() {
|
|
665
|
+
return { ...senderTelemetry };
|
|
666
|
+
},
|
|
667
|
+
getPeerSnapshot() {
|
|
668
|
+
const peers = [];
|
|
669
|
+
for (const c of peerControllers) {
|
|
670
|
+
peers.push({
|
|
671
|
+
addr: c.remoteAddr,
|
|
672
|
+
session: c.sessionKey,
|
|
673
|
+
iceState: c.iceState,
|
|
674
|
+
connected: c.connected,
|
|
675
|
+
wsOpen: c.ws && c.ws.readyState === c.ws.OPEN,
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
return {
|
|
679
|
+
active: activePeers.size,
|
|
680
|
+
pending: pendingPeers,
|
|
681
|
+
total: activePeers.size + pendingPeers,
|
|
682
|
+
max: MAX_CONNECTIONS,
|
|
683
|
+
peers,
|
|
684
|
+
};
|
|
685
|
+
},
|
|
686
|
+
disconnectPeersByAddr(addr, reason = 'admin-kick') {
|
|
687
|
+
if (!addr) return 0;
|
|
688
|
+
let closed = 0;
|
|
689
|
+
const addrNorm = String(addr).replace(/^::ffff:/, '');
|
|
690
|
+
for (const c of Array.from(peerControllers)) {
|
|
691
|
+
const peerAddrNorm = String(c.remoteAddr ?? '').replace(/^::ffff:/, '');
|
|
692
|
+
if (peerAddrNorm !== addrNorm) continue;
|
|
693
|
+
try {
|
|
694
|
+
c.closePeer?.(reason);
|
|
695
|
+
closed++;
|
|
696
|
+
} catch (_) {}
|
|
697
|
+
}
|
|
698
|
+
return closed;
|
|
699
|
+
},
|
|
700
|
+
disconnectAllPeers(reason = 'admin-kick-all') {
|
|
701
|
+
let closed = 0;
|
|
702
|
+
for (const c of Array.from(peerControllers)) {
|
|
703
|
+
try {
|
|
704
|
+
c.closePeer?.(reason);
|
|
705
|
+
closed++;
|
|
706
|
+
} catch (_) {}
|
|
707
|
+
}
|
|
708
|
+
return closed;
|
|
709
|
+
},
|
|
710
|
+
close: () =>
|
|
711
|
+
new Promise((resolve) => {
|
|
712
|
+
clearInterval(pingInterval);
|
|
713
|
+
clearInterval(senderTelemetryTimer);
|
|
714
|
+
wss.close(() => httpServer.close(() => resolve()));
|
|
715
|
+
}),
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// ─── Embedded browser-side player page ──────────────────────────────────────
|
|
720
|
+
function buildBrowserHtml(inputPort, minBitrateKbps = 200, maxBitrateKbps = 600) {
|
|
721
|
+
const minKbps = Math.max(50, Math.round(minBitrateKbps));
|
|
722
|
+
const maxKbps = Math.max(minKbps, Math.round(maxBitrateKbps));
|
|
723
|
+
return /* html */ `<!DOCTYPE html>
|
|
724
|
+
<html lang="en">
|
|
725
|
+
<head>
|
|
726
|
+
<meta charset="UTF-8">
|
|
727
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
728
|
+
<title>C64 Live</title>
|
|
729
|
+
<style>
|
|
730
|
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
|
731
|
+
body {
|
|
732
|
+
background: #0d0d0d;
|
|
733
|
+
display: flex;
|
|
734
|
+
flex-direction: column;
|
|
735
|
+
align-items: center;
|
|
736
|
+
justify-content: center;
|
|
737
|
+
min-height: 100vh;
|
|
738
|
+
font-family: 'Courier New', monospace;
|
|
739
|
+
color: #aaa;
|
|
740
|
+
gap: 10px;
|
|
741
|
+
padding: 16px;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
h1 { font-size: 13px; letter-spacing: 0.2em; color: #555; text-transform: uppercase; }
|
|
745
|
+
|
|
746
|
+
/* ── Screen ── */
|
|
747
|
+
#screen-wrap {
|
|
748
|
+
position: relative;
|
|
749
|
+
width: 768px; height: 544px;
|
|
750
|
+
flex-shrink: 0;
|
|
751
|
+
}
|
|
752
|
+
#screen {
|
|
753
|
+
width: 100%; height: 100%;
|
|
754
|
+
image-rendering: pixelated;
|
|
755
|
+
background: #000;
|
|
756
|
+
border: 2px solid #2a2a2a;
|
|
757
|
+
display: block;
|
|
758
|
+
cursor: pointer;
|
|
759
|
+
}
|
|
760
|
+
#screen-wrap.drag-over #screen { border-color: #55f; box-shadow: 0 0 0 2px #338; }
|
|
761
|
+
|
|
762
|
+
#mute-overlay {
|
|
763
|
+
position: absolute; inset: 0;
|
|
764
|
+
background: rgba(0,0,0,0.55);
|
|
765
|
+
display: flex; align-items: center; justify-content: center;
|
|
766
|
+
font-size: 14px; color: #ccc; letter-spacing: 0.1em;
|
|
767
|
+
pointer-events: none;
|
|
768
|
+
transition: opacity 0.3s;
|
|
769
|
+
}
|
|
770
|
+
#mute-overlay.hidden { opacity: 0; }
|
|
771
|
+
|
|
772
|
+
/* ── Status bar ── */
|
|
773
|
+
.status-row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; font-size: 11px; }
|
|
774
|
+
.badge {
|
|
775
|
+
padding: 2px 8px; border-radius: 3px; background: #1a1a1a;
|
|
776
|
+
border: 1px solid #2a2a2a; letter-spacing: 0.05em; white-space: nowrap;
|
|
777
|
+
}
|
|
778
|
+
.badge.ok { color: #4f4; border-color: #262; }
|
|
779
|
+
.badge.warn { color: #fa0; border-color: #540; }
|
|
780
|
+
.badge.err { color: #f44; border-color: #422; }
|
|
781
|
+
.badge.dim { color: #444; }
|
|
782
|
+
|
|
783
|
+
/* ── Controls bar ── */
|
|
784
|
+
.controls-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
|
785
|
+
button {
|
|
786
|
+
padding: 5px 12px; border-radius: 3px; border: 1px solid #333;
|
|
787
|
+
background: #1a1a1a; color: #aaa; font-family: inherit; font-size: 11px;
|
|
788
|
+
cursor: pointer; letter-spacing: 0.05em; transition: background 0.15s;
|
|
789
|
+
}
|
|
790
|
+
button:hover { background: #252525; border-color: #555; color: #ddd; }
|
|
791
|
+
button:disabled { opacity: 0.35; cursor: default; }
|
|
792
|
+
button.hidden { display: none; }
|
|
793
|
+
button.active { background: #1a2a1a; color: #8f8; border-color: #464; }
|
|
794
|
+
|
|
795
|
+
/* ── CRT drop zone hint ── */
|
|
796
|
+
#drop-hint {
|
|
797
|
+
font-size: 11px; color: #333; letter-spacing: 0.08em;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/* ── Load progress ── */
|
|
801
|
+
#load-status { font-size: 11px; min-width: 120px; }
|
|
802
|
+
|
|
803
|
+
/* ── Separator ── */
|
|
804
|
+
.sep { color: #2a2a2a; user-select: none; }
|
|
805
|
+
|
|
806
|
+
input[type=file] { display: none; }
|
|
807
|
+
</style>
|
|
808
|
+
</head>
|
|
809
|
+
<body>
|
|
810
|
+
<h1>C64 Live</h1>
|
|
811
|
+
|
|
812
|
+
<div id="screen-wrap">
|
|
813
|
+
<video id="screen" autoplay playsinline muted></video>
|
|
814
|
+
<div id="mute-overlay">🔇 click to unmute</div>
|
|
815
|
+
</div>
|
|
816
|
+
|
|
817
|
+
<div class="status-row">
|
|
818
|
+
<span id="video-status" class="badge dim">video: connecting…</span>
|
|
819
|
+
<span id="audio-status" class="badge dim">audio: muted</span>
|
|
820
|
+
<span id="input-status" class="badge dim">input: connecting…</span>
|
|
821
|
+
<span id="game-status" class="badge dim">no game</span>
|
|
822
|
+
</div>
|
|
823
|
+
|
|
824
|
+
<div class="controls-row">
|
|
825
|
+
<button id="load-btn" title="Load a .crt cartridge file">📂 load .crt</button>
|
|
826
|
+
<button id="detach-btn" title="Eject cartridge → BASIC prompt" disabled>⏏ detach</button>
|
|
827
|
+
<button id="reset-btn" title="Hard reset (BASIC prompt)" disabled>↺ reset</button>
|
|
828
|
+
<span class="sep">|</span>
|
|
829
|
+
<button id="sync-btn" title="Flush video to live edge — use if display feels laggy">⟳ sync</button>
|
|
830
|
+
<span class="sep">|</span>
|
|
831
|
+
<button id="mode-btn" title="Toggle input mode">🕹+⌨ mixed</button>
|
|
832
|
+
<span class="sep">|</span>
|
|
833
|
+
<span id="load-status" class="badge dim"></span>
|
|
834
|
+
<span id="drop-hint">or drop .crt onto screen</span>
|
|
835
|
+
<input type="file" id="file-input" accept=".crt">
|
|
836
|
+
</div>
|
|
837
|
+
|
|
838
|
+
<script>
|
|
839
|
+
// ── Element refs ─────────────────────────────────────────────────────────
|
|
840
|
+
const videoEl = document.getElementById('screen');
|
|
841
|
+
const screenWrap = document.getElementById('screen-wrap');
|
|
842
|
+
const muteOverlay = document.getElementById('mute-overlay');
|
|
843
|
+
const videoBadge = document.getElementById('video-status');
|
|
844
|
+
const audioBadge = document.getElementById('audio-status');
|
|
845
|
+
const inputBadge = document.getElementById('input-status');
|
|
846
|
+
const gameBadge = document.getElementById('game-status');
|
|
847
|
+
const loadStatus = document.getElementById('load-status');
|
|
848
|
+
const loadBtn = document.getElementById('load-btn');
|
|
849
|
+
const detachBtn = document.getElementById('detach-btn');
|
|
850
|
+
const resetBtn = document.getElementById('reset-btn');
|
|
851
|
+
const syncBtn = document.getElementById('sync-btn');
|
|
852
|
+
const modeBtn = document.getElementById('mode-btn');
|
|
853
|
+
const fileInput = document.getElementById('file-input');
|
|
854
|
+
|
|
855
|
+
function setBadge(el, text, cls) {
|
|
856
|
+
el.textContent = text;
|
|
857
|
+
el.className = 'badge ' + (cls || 'dim');
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// ── Audio ─────────────────────────────────────────────────────────────────
|
|
861
|
+
let audioCtx = null, analyserTimer = null, audioConfirmed = false;
|
|
862
|
+
let remoteStream = null;
|
|
863
|
+
|
|
864
|
+
function startAudioMonitor(stream) {
|
|
865
|
+
if (audioCtx || audioConfirmed) return;
|
|
866
|
+
try {
|
|
867
|
+
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
|
|
868
|
+
const src = audioCtx.createMediaStreamSource(stream);
|
|
869
|
+
const an = audioCtx.createAnalyser();
|
|
870
|
+
an.fftSize = 256;
|
|
871
|
+
src.connect(an);
|
|
872
|
+
const buf = new Float32Array(an.fftSize);
|
|
873
|
+
analyserTimer = setInterval(() => {
|
|
874
|
+
an.getFloatTimeDomainData(buf);
|
|
875
|
+
let sum = 0;
|
|
876
|
+
for (let i = 0; i < buf.length; i++) sum += buf[i] * buf[i];
|
|
877
|
+
if (Math.sqrt(sum / buf.length) > 0.001) {
|
|
878
|
+
audioConfirmed = true;
|
|
879
|
+
clearInterval(analyserTimer); analyserTimer = null;
|
|
880
|
+
setBadge(audioBadge, '🔊 audio on', 'ok');
|
|
881
|
+
}
|
|
882
|
+
}, 200);
|
|
883
|
+
setTimeout(() => {
|
|
884
|
+
if (!audioConfirmed && analyserTimer) {
|
|
885
|
+
clearInterval(analyserTimer); analyserTimer = null;
|
|
886
|
+
audioConfirmed = true;
|
|
887
|
+
setBadge(audioBadge, '🔊 on (silent)', 'ok');
|
|
888
|
+
}
|
|
889
|
+
}, 8000);
|
|
890
|
+
} catch (_) { setBadge(audioBadge, 'audio error', 'err'); }
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
videoEl.addEventListener('click', () => {
|
|
894
|
+
if (videoEl.muted) {
|
|
895
|
+
videoEl.muted = false;
|
|
896
|
+
muteOverlay.classList.add('hidden');
|
|
897
|
+
setBadge(audioBadge, 'starting…', 'warn');
|
|
898
|
+
if (remoteStream) startAudioMonitor(remoteStream);
|
|
899
|
+
else {
|
|
900
|
+
const t = setInterval(() => { if (remoteStream) { clearInterval(t); startAudioMonitor(remoteStream); } }, 300);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
});
|
|
904
|
+
|
|
905
|
+
// ── WebRTC ────────────────────────────────────────────────────────────────
|
|
906
|
+
// pc and sigWs are module-level so reconnectWebRTC() can tear them down.
|
|
907
|
+
let pc = null;
|
|
908
|
+
let sigWs = null;
|
|
909
|
+
let driftTimer = null;
|
|
910
|
+
let rtcReconnectTimer = null;
|
|
911
|
+
let sigPingTimer = null; // keepalive ping on the signalling WS
|
|
912
|
+
|
|
913
|
+
function scheduleRtcReconnect(delayMs) {
|
|
914
|
+
if (rtcReconnectTimer) return; // already scheduled
|
|
915
|
+
setBadge(videoBadge, 'video: reconnecting…', 'warn');
|
|
916
|
+
rtcReconnectTimer = setTimeout(() => {
|
|
917
|
+
rtcReconnectTimer = null;
|
|
918
|
+
connectWebRTC();
|
|
919
|
+
}, delayMs);
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
function applyMinLatency() {
|
|
923
|
+
if (!pc) return;
|
|
924
|
+
for (const r of pc.getReceivers()) {
|
|
925
|
+
if ('jitterBufferTarget' in r) r.jitterBufferTarget = 0;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
function startDriftMonitor() {
|
|
930
|
+
stopDriftMonitor();
|
|
931
|
+
driftTimer = setInterval(() => {
|
|
932
|
+
if (!videoEl || !remoteStream || videoEl.paused || videoEl.readyState < 2) return;
|
|
933
|
+
const buf = videoEl.buffered;
|
|
934
|
+
if (!buf || buf.length === 0) return;
|
|
935
|
+
const bufEnd = buf.end(buf.length - 1);
|
|
936
|
+
const drift = bufEnd - videoEl.currentTime;
|
|
937
|
+
if (drift > 0.3) {
|
|
938
|
+
console.warn('[WebRTC] drift ' + (drift*1000).toFixed(0) + 'ms — skipping to live edge');
|
|
939
|
+
videoEl.currentTime = bufEnd;
|
|
940
|
+
}
|
|
941
|
+
}, 200);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
function stopDriftMonitor() {
|
|
945
|
+
if (driftTimer) { clearInterval(driftTimer); driftTimer = null; }
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
function flushToLiveEdge() {
|
|
949
|
+
applyMinLatency();
|
|
950
|
+
if (!videoEl || !remoteStream) return;
|
|
951
|
+
const buf = videoEl.buffered;
|
|
952
|
+
if (buf && buf.length > 0) {
|
|
953
|
+
const bufEnd = buf.end(buf.length - 1);
|
|
954
|
+
const drift = bufEnd - videoEl.currentTime;
|
|
955
|
+
console.log('[WebRTC] flushToLiveEdge: drift=' + (drift*1000).toFixed(0) + 'ms → skip to live edge');
|
|
956
|
+
videoEl.currentTime = bufEnd;
|
|
957
|
+
}
|
|
958
|
+
videoEl.play().catch(() => {});
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
function connectWebRTC() {
|
|
962
|
+
// Cancel any pending auto-reconnect so we don't double-connect.
|
|
963
|
+
if (rtcReconnectTimer) { clearTimeout(rtcReconnectTimer); rtcReconnectTimer = null; }
|
|
964
|
+
if (sigPingTimer) { clearInterval(sigPingTimer); sigPingTimer = null; }
|
|
965
|
+
// Tear down any existing connection cleanly first.
|
|
966
|
+
stopDriftMonitor();
|
|
967
|
+
if (pc) { try { pc.close(); } catch (_) {} pc = null; }
|
|
968
|
+
if (sigWs && sigWs.readyState !== WebSocket.CLOSED) {
|
|
969
|
+
// Remove onclose so it doesn't update the badge during our intentional teardown
|
|
970
|
+
sigWs.onclose = null;
|
|
971
|
+
try { sigWs.close(); } catch (_) {}
|
|
972
|
+
sigWs = null;
|
|
973
|
+
}
|
|
974
|
+
remoteStream = null;
|
|
975
|
+
videoEl.srcObject = null;
|
|
976
|
+
|
|
977
|
+
setBadge(videoBadge, 'video: connecting…', 'dim');
|
|
978
|
+
|
|
979
|
+
function getOrCreateSessionId() {
|
|
980
|
+
try {
|
|
981
|
+
const key = 'c64live.webrtcSessionId';
|
|
982
|
+
const existing = localStorage.getItem(key);
|
|
983
|
+
if (existing) return existing;
|
|
984
|
+
const created = (globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function')
|
|
985
|
+
? globalThis.crypto.randomUUID()
|
|
986
|
+
: (Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10));
|
|
987
|
+
localStorage.setItem(key, created);
|
|
988
|
+
return created;
|
|
989
|
+
} catch (_) {
|
|
990
|
+
return Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
const rtcSessionId = getOrCreateSessionId();
|
|
994
|
+
const sigUrl = new URL('ws://' + location.host);
|
|
995
|
+
sigUrl.searchParams.set('sid', rtcSessionId);
|
|
996
|
+
sigWs = new WebSocket(sigUrl.toString());
|
|
997
|
+
pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] });
|
|
998
|
+
let offerSent = false;
|
|
999
|
+
const pendingLocalCandidates = [];
|
|
1000
|
+
const pendingRemoteCandidates = [];
|
|
1001
|
+
|
|
1002
|
+
function sendSignal(msg) {
|
|
1003
|
+
if (!sigWs || sigWs.readyState !== WebSocket.OPEN) return;
|
|
1004
|
+
sigWs.send(JSON.stringify(msg));
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
function flushLocalCandidates() {
|
|
1008
|
+
if (!offerSent || !sigWs || sigWs.readyState !== WebSocket.OPEN) return;
|
|
1009
|
+
while (pendingLocalCandidates.length > 0) {
|
|
1010
|
+
const candidate = pendingLocalCandidates.shift();
|
|
1011
|
+
if (!candidate) continue;
|
|
1012
|
+
sendSignal({ type: 'candidate', candidate });
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
async function addRemoteCandidate(candidate, source) {
|
|
1017
|
+
try {
|
|
1018
|
+
await pc.addIceCandidate(candidate);
|
|
1019
|
+
} catch (err) {
|
|
1020
|
+
const hasRemoteDescription = !!pc.remoteDescription;
|
|
1021
|
+
const signalingState = pc.signalingState;
|
|
1022
|
+
const errName = err && err.name ? err.name : 'Error';
|
|
1023
|
+
const errMsg = err && err.message ? err.message : String(err);
|
|
1024
|
+
console.warn('[WebRTC] addIceCandidate failed (' + source + ') hasRemoteDescription=' + hasRemoteDescription + ' signalingState=' + signalingState + ' err=' + errName + ': ' + errMsg);
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
async function flushRemoteCandidates() {
|
|
1029
|
+
if (!pc.remoteDescription || pendingRemoteCandidates.length === 0) return;
|
|
1030
|
+
const queued = pendingRemoteCandidates.splice(0, pendingRemoteCandidates.length);
|
|
1031
|
+
for (const candidate of queued) {
|
|
1032
|
+
await addRemoteCandidate(candidate, 'post-answer');
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
pc.ontrack = (e) => {
|
|
1037
|
+
if (e.streams && e.streams[0]) {
|
|
1038
|
+
remoteStream = e.streams[0];
|
|
1039
|
+
videoEl.srcObject = remoteStream;
|
|
1040
|
+
setBadge(videoBadge, 'video: live', 'ok');
|
|
1041
|
+
applyMinLatency();
|
|
1042
|
+
startDriftMonitor();
|
|
1043
|
+
}
|
|
1044
|
+
};
|
|
1045
|
+
|
|
1046
|
+
pc.onicecandidate = ({ candidate }) => {
|
|
1047
|
+
if (!candidate) return;
|
|
1048
|
+
if (!offerSent) {
|
|
1049
|
+
pendingLocalCandidates.push(candidate);
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
if (sigWs && sigWs.readyState === WebSocket.OPEN) {
|
|
1053
|
+
sendSignal({ type: 'candidate', candidate });
|
|
1054
|
+
}
|
|
1055
|
+
};
|
|
1056
|
+
|
|
1057
|
+
pc.oniceconnectionstatechange = () => {
|
|
1058
|
+
const s = pc.iceConnectionState;
|
|
1059
|
+
if (s === 'connected' || s === 'completed') {
|
|
1060
|
+
setBadge(videoBadge, 'video: live', 'ok');
|
|
1061
|
+
} else if (s === 'disconnected') {
|
|
1062
|
+
// Transient — server gives 6s grace, show warning but wait.
|
|
1063
|
+
setBadge(videoBadge, 'video: unstable…', 'warn');
|
|
1064
|
+
} else if (s === 'failed') {
|
|
1065
|
+
// ICE has fully given up — reconnect after a short delay.
|
|
1066
|
+
setBadge(videoBadge, 'video: reconnecting…', 'warn');
|
|
1067
|
+
scheduleRtcReconnect(1000);
|
|
1068
|
+
} else if (s === 'closed') {
|
|
1069
|
+
setBadge(videoBadge, 'video: closed', 'err');
|
|
1070
|
+
}
|
|
1071
|
+
};
|
|
1072
|
+
|
|
1073
|
+
sigWs.onopen = async () => {
|
|
1074
|
+
setBadge(videoBadge, 'video: negotiating…', 'warn');
|
|
1075
|
+
// Start keepalive ping — prevents the idle TCP connection from being
|
|
1076
|
+
// dropped by cloud NAT / load balancers (~60s timeout observed in prod).
|
|
1077
|
+
sigPingTimer = setInterval(() => {
|
|
1078
|
+
if (sigWs && sigWs.readyState === WebSocket.OPEN) {
|
|
1079
|
+
sigWs.send(JSON.stringify({ type: 'ping' }));
|
|
1080
|
+
}
|
|
1081
|
+
}, 30000);
|
|
1082
|
+
let transceiver = null;
|
|
1083
|
+
try {
|
|
1084
|
+
transceiver = pc.addTransceiver('video', { direction: 'recvonly' });
|
|
1085
|
+
pc.addTransceiver('audio', { direction: 'recvonly' });
|
|
1086
|
+
} catch (_) {}
|
|
1087
|
+
try {
|
|
1088
|
+
if (transceiver && typeof transceiver.setCodecPreferences === 'function') {
|
|
1089
|
+
const caps = RTCRtpReceiver.getCapabilities('video');
|
|
1090
|
+
if (caps) {
|
|
1091
|
+
const vp8 = caps.codecs.filter(c => c.mimeType === 'video/VP8');
|
|
1092
|
+
const rest = caps.codecs.filter(c => c.mimeType !== 'video/VP8');
|
|
1093
|
+
if (vp8.length) transceiver.setCodecPreferences([...vp8, ...rest]);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
} catch (_) {}
|
|
1097
|
+
const offer = await pc.createOffer();
|
|
1098
|
+
if (offer.sdp) {
|
|
1099
|
+
offer.sdp = offer.sdp.replace(
|
|
1100
|
+
/(a=rtpmap:(\\d+) VP8\\/\\d+\\r?\\n)/,
|
|
1101
|
+
function(m, line, pt) { return line + 'a=fmtp:' + pt + ' x-google-min-bitrate=${minKbps};x-google-max-bitrate=${maxKbps}\\r\\n'; }
|
|
1102
|
+
);
|
|
1103
|
+
}
|
|
1104
|
+
await pc.setLocalDescription(offer);
|
|
1105
|
+
const local = pc.localDescription;
|
|
1106
|
+
if (!local || !local.type || !local.sdp) {
|
|
1107
|
+
throw new Error('Local offer description missing type/sdp');
|
|
1108
|
+
}
|
|
1109
|
+
sendSignal({ type: local.type, sdp: local.sdp, sessionId: rtcSessionId });
|
|
1110
|
+
offerSent = true;
|
|
1111
|
+
flushLocalCandidates();
|
|
1112
|
+
};
|
|
1113
|
+
|
|
1114
|
+
sigWs.onmessage = async ({ data }) => {
|
|
1115
|
+
const msg = JSON.parse(data);
|
|
1116
|
+
if (msg.type === 'answer') {
|
|
1117
|
+
await pc.setRemoteDescription(msg);
|
|
1118
|
+
await flushRemoteCandidates();
|
|
1119
|
+
applyMinLatency();
|
|
1120
|
+
} else if (msg.type === 'candidate') {
|
|
1121
|
+
if (!msg.candidate) return;
|
|
1122
|
+
if (!pc.remoteDescription) {
|
|
1123
|
+
pendingRemoteCandidates.push(msg.candidate);
|
|
1124
|
+
return;
|
|
1125
|
+
}
|
|
1126
|
+
await addRemoteCandidate(msg.candidate, 'live');
|
|
1127
|
+
} else if (msg.type === 'pong') {
|
|
1128
|
+
// Server acknowledged our keepalive ping — connection is healthy.
|
|
1129
|
+
} else if (msg.type === 'peer-closed') {
|
|
1130
|
+
// Server closed the peer (e.g. after disconnect grace expired).
|
|
1131
|
+
// Reconnect immediately — this is the expected recovery path.
|
|
1132
|
+
console.warn('[WebRTC] server closed peer (' + (msg.reason || '?') + ') — reconnecting');
|
|
1133
|
+
scheduleRtcReconnect(500);
|
|
1134
|
+
} else if (msg.type === 'capacity-full') {
|
|
1135
|
+
// Server is at capacity — do not auto-reconnect; show a message instead.
|
|
1136
|
+
console.warn('[WebRTC] server at capacity (' + msg.current + '/' + msg.max + ' connections)');
|
|
1137
|
+
setBadge(videoBadge, 'server full — try later', 'err');
|
|
1138
|
+
setBadge(inputBadge, 'input: unavailable', 'err');
|
|
1139
|
+
// Cancel any pending reconnect so we don't spam the server.
|
|
1140
|
+
if (rtcReconnectTimer) { clearTimeout(rtcReconnectTimer); rtcReconnectTimer = null; }
|
|
1141
|
+
stopDriftMonitor();
|
|
1142
|
+
}
|
|
1143
|
+
};
|
|
1144
|
+
|
|
1145
|
+
sigWs.onerror = () => setBadge(videoBadge, 'video: sig error', 'err');
|
|
1146
|
+
sigWs.onclose = () => {
|
|
1147
|
+
if (sigPingTimer) { clearInterval(sigPingTimer); sigPingTimer = null; }
|
|
1148
|
+
// Signalling WS closed — could be server restart or network blip.
|
|
1149
|
+
// Reconnect after 2s so we don't spin.
|
|
1150
|
+
setBadge(videoBadge, 'video: reconnecting…', 'warn');
|
|
1151
|
+
scheduleRtcReconnect(2000);
|
|
1152
|
+
};
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// Initial connection
|
|
1156
|
+
connectWebRTC();
|
|
1157
|
+
|
|
1158
|
+
// ── Input server ──────────────────────────────────────────────────────────
|
|
1159
|
+
const INPUT_PORT = ${inputPort};
|
|
1160
|
+
let inputWs = null, inputBackoff = 1000, backoffTimer = null;
|
|
1161
|
+
|
|
1162
|
+
function connectInput() {
|
|
1163
|
+
if (backoffTimer) { clearTimeout(backoffTimer); backoffTimer = null; }
|
|
1164
|
+
setBadge(inputBadge, 'input: connecting…', 'warn');
|
|
1165
|
+
inputWs = new WebSocket('ws://' + location.hostname + ':' + INPUT_PORT);
|
|
1166
|
+
|
|
1167
|
+
inputWs.onopen = () => {
|
|
1168
|
+
inputBackoff = 1000;
|
|
1169
|
+
setBadge(inputBadge, 'input: connected', 'ok');
|
|
1170
|
+
// Claim host role — force:true evicts any stale previous session so
|
|
1171
|
+
// detach / reset always work even after a page reload or reconnect.
|
|
1172
|
+
inputWs.send(JSON.stringify({ type: 'host', username: 'player', force: true }));
|
|
1173
|
+
};
|
|
1174
|
+
|
|
1175
|
+
inputWs.onmessage = ({ data }) => {
|
|
1176
|
+
try {
|
|
1177
|
+
const msg = JSON.parse(data);
|
|
1178
|
+
// Cart lifecycle
|
|
1179
|
+
if (msg.type === 'cart-loaded' || msg.type === 'machine-reset' || msg.type === 'cart-detached') {
|
|
1180
|
+
blurAll();
|
|
1181
|
+
const cartName = msg.filename ? msg.filename.replace(/\\.crt$/i,'').replace(/[-_]/g,' ') : '';
|
|
1182
|
+
if (msg.type === 'cart-loaded') { setBadge(gameBadge, '🎮 ' + (cartName || 'game loaded'), 'ok'); setLoadStatus('loaded', 'ok'); detachBtn.disabled = false; resetBtn.disabled = false; }
|
|
1183
|
+
if (msg.type === 'cart-detached') { setBadge(gameBadge, 'no game', 'dim'); setLoadStatus('', ''); detachBtn.disabled = true; }
|
|
1184
|
+
if (msg.type === 'machine-reset') { setLoadStatus('reset', 'warn'); }
|
|
1185
|
+
// Reconnect the RTCPeerConnection entirely — this is the only
|
|
1186
|
+
// reliable way to clear the jitter buffer and decoder state that
|
|
1187
|
+
// accumulates during the ~1600ms cart-load gap. Anything less
|
|
1188
|
+
// (currentTime seek, srcObject null, jitterBufferTarget) leaves
|
|
1189
|
+
// stale decoded frames in the pipeline. A fresh pc + renegotiate
|
|
1190
|
+
// is equivalent to a browser refresh but without losing input WS.
|
|
1191
|
+
// Preserve mute state so the user doesn't lose audio they unmuted.
|
|
1192
|
+
const wasMuted = videoEl.muted;
|
|
1193
|
+
connectWebRTC();
|
|
1194
|
+
// Re-apply mute state after the new video element srcObject is set
|
|
1195
|
+
// (ontrack fires asynchronously, so check after a short delay)
|
|
1196
|
+
if (!wasMuted) {
|
|
1197
|
+
const t = setInterval(() => {
|
|
1198
|
+
if (remoteStream) {
|
|
1199
|
+
videoEl.muted = false;
|
|
1200
|
+
muteOverlay.classList.add('hidden');
|
|
1201
|
+
clearInterval(t);
|
|
1202
|
+
}
|
|
1203
|
+
}, 100);
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
if (msg.type === 'hello' && msg.cartFilename) {
|
|
1207
|
+
const cartName = msg.cartFilename.replace(/\\.crt$/i,'').replace(/[-_]/g,' ');
|
|
1208
|
+
setBadge(gameBadge, '🎮 ' + (cartName || 'game loaded'), 'ok');
|
|
1209
|
+
setLoadStatus('loaded', 'ok');
|
|
1210
|
+
detachBtn.disabled = false;
|
|
1211
|
+
resetBtn.disabled = false;
|
|
1212
|
+
}
|
|
1213
|
+
if (msg.type === 'cart-loading') setLoadStatus('loading…', 'warn');
|
|
1214
|
+
if (msg.type === 'cart-load-error') setLoadStatus('error: ' + (msg.reason || '?'), 'err');
|
|
1215
|
+
if (msg.type === 'host-confirmed') setBadge(inputBadge, 'input: host', 'ok');
|
|
1216
|
+
} catch (_) {}
|
|
1217
|
+
};
|
|
1218
|
+
inputWs.onclose = () => {
|
|
1219
|
+
setBadge(inputBadge, 'input: retrying ' + (inputBackoff/1000).toFixed(0) + 's…', 'warn');
|
|
1220
|
+
backoffTimer = setTimeout(() => { inputBackoff = Math.min(inputBackoff * 2, 30000); connectInput(); }, inputBackoff);
|
|
1221
|
+
};
|
|
1222
|
+
inputWs.onerror = () => setBadge(inputBadge, 'input: unavailable', 'err');
|
|
1223
|
+
}
|
|
1224
|
+
function sendInput(msg) {
|
|
1225
|
+
if (inputWs && inputWs.readyState === WebSocket.OPEN) inputWs.send(JSON.stringify(msg));
|
|
1226
|
+
}
|
|
1227
|
+
// Blur any focused UI element so keyboard events go to the emulator,
|
|
1228
|
+
// not to whichever button was last clicked.
|
|
1229
|
+
function blurAll() {
|
|
1230
|
+
if (document.activeElement && document.activeElement !== document.body)
|
|
1231
|
+
document.activeElement.blur();
|
|
1232
|
+
}
|
|
1233
|
+
connectInput();
|
|
1234
|
+
function setLoadStatus(text, cls) {
|
|
1235
|
+
loadStatus.textContent = text;
|
|
1236
|
+
loadStatus.className = 'badge ' + (cls || 'dim');
|
|
1237
|
+
}
|
|
1238
|
+
// ── CRT loading ───────────────────────────────────────────────────────────
|
|
1239
|
+
async function loadCrt(file) {
|
|
1240
|
+
if (!file) return;
|
|
1241
|
+
setLoadStatus('reading…', 'warn');
|
|
1242
|
+
try {
|
|
1243
|
+
const b64 = await new Promise((resolve, reject) => {
|
|
1244
|
+
const reader = new FileReader();
|
|
1245
|
+
reader.onload = () => { const r = reader.result; resolve(r.slice(r.indexOf(',') + 1)); };
|
|
1246
|
+
reader.onerror = () => reject(reader.error);
|
|
1247
|
+
reader.readAsDataURL(file);
|
|
1248
|
+
});
|
|
1249
|
+
setLoadStatus('sending…', 'warn');
|
|
1250
|
+
sendInput({ type: 'load-crt', filename: file.name, data: b64 });
|
|
1251
|
+
} catch (e) {
|
|
1252
|
+
setLoadStatus('read error', 'err');
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
loadBtn.addEventListener('click', () => fileInput.click());
|
|
1256
|
+
fileInput.addEventListener('change', (e) => { const f = e.target?.files?.[0]; if (f) loadCrt(f); fileInput.value = ''; blurAll(); });
|
|
1257
|
+
screenWrap.addEventListener('dragover', (e) => { e.preventDefault(); screenWrap.classList.add('drag-over'); });
|
|
1258
|
+
screenWrap.addEventListener('dragleave', () => screenWrap.classList.remove('drag-over'));
|
|
1259
|
+
screenWrap.addEventListener('drop', (e) => {
|
|
1260
|
+
e.preventDefault();
|
|
1261
|
+
screenWrap.classList.remove('drag-over');
|
|
1262
|
+
const f = e.dataTransfer?.files?.[0];
|
|
1263
|
+
if (f) loadCrt(f);
|
|
1264
|
+
});
|
|
1265
|
+
detachBtn.addEventListener('click', () => { sendInput({ type: 'detach-crt' }); setLoadStatus('detaching…', 'warn'); blurAll(); });
|
|
1266
|
+
resetBtn.addEventListener('click', () => { sendInput({ type: 'hard-reset' }); setLoadStatus('resetting…', 'warn'); blurAll(); });
|
|
1267
|
+
syncBtn.addEventListener('click', () => {
|
|
1268
|
+
const wasMuted = videoEl.muted;
|
|
1269
|
+
connectWebRTC();
|
|
1270
|
+
if (!wasMuted) {
|
|
1271
|
+
const t = setInterval(() => { if (remoteStream) { videoEl.muted = false; muteOverlay.classList.add('hidden'); clearInterval(t); } }, 100);
|
|
1272
|
+
}
|
|
1273
|
+
syncBtn.textContent = '✓ synced';
|
|
1274
|
+
setTimeout(() => { syncBtn.textContent = '⟳ sync'; }, 1500);
|
|
1275
|
+
blurAll();
|
|
1276
|
+
});
|
|
1277
|
+
// ── Input mode ────────────────────────────────────────────────────────────
|
|
1278
|
+
const MODES = ['mixed', 'joy', 'kb'];
|
|
1279
|
+
const MODE_LABELS = { mixed: '🕹+⌨ mixed', joy: '🕹 joystick', kb: '⌨ keyboard' };
|
|
1280
|
+
let modeIdx = 0;
|
|
1281
|
+
modeBtn.addEventListener('click', () => {
|
|
1282
|
+
modeIdx = (modeIdx + 1) % MODES.length;
|
|
1283
|
+
modeBtn.textContent = MODE_LABELS[MODES[modeIdx]];
|
|
1284
|
+
modeBtn.classList.toggle('active', MODES[modeIdx] === 'joy');
|
|
1285
|
+
});
|
|
1286
|
+
function getMode() { return MODES[modeIdx]; }
|
|
1287
|
+
const JOY_MAP = {
|
|
1288
|
+
ArrowUp: { direction: 'up' }, ArrowDown: { direction: 'down' },
|
|
1289
|
+
ArrowLeft: { direction: 'left' }, ArrowRight: { direction: 'right' },
|
|
1290
|
+
z: { fire: true }, Z: { fire: true }, x: { fire: true }, X: { fire: true },
|
|
1291
|
+
};
|
|
1292
|
+
const MIXED_JOY_KEYS = new Set(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight','z','Z','x','X']);
|
|
1293
|
+
const PREVENT_DEFAULTS = new Set(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight',' ','Tab']);
|
|
1294
|
+
document.addEventListener('keydown', (e) => {
|
|
1295
|
+
if (PREVENT_DEFAULTS.has(e.key)) e.preventDefault();
|
|
1296
|
+
if (e.repeat) return;
|
|
1297
|
+
const tag = e.target instanceof Element ? e.target.tagName : '';
|
|
1298
|
+
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
|
|
1299
|
+
const mode = getMode();
|
|
1300
|
+
const j = JOY_MAP[e.key];
|
|
1301
|
+
if (mode === 'joy') {
|
|
1302
|
+
if (j) sendInput({ type: 'joystick', joystickPort: 2, action: 'push', direction: j.direction, fire: j.fire ?? false });
|
|
1303
|
+
} else if (mode === 'mixed') {
|
|
1304
|
+
if (j) sendInput({ type: 'joystick', joystickPort: 2, action: 'push', direction: j.direction, fire: j.fire ?? false });
|
|
1305
|
+
if (!MIXED_JOY_KEYS.has(e.key)) sendInput({ type: 'key', key: e.key, shiftKey: e.shiftKey, action: 'down' });
|
|
1306
|
+
} else {
|
|
1307
|
+
sendInput({ type: 'key', key: e.key, shiftKey: e.shiftKey, action: 'down' });
|
|
1308
|
+
}
|
|
1309
|
+
});
|
|
1310
|
+
document.addEventListener('keyup', (e) => {
|
|
1311
|
+
const tag = e.target instanceof Element ? e.target.tagName : '';
|
|
1312
|
+
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return;
|
|
1313
|
+
const mode = getMode();
|
|
1314
|
+
const j = JOY_MAP[e.key];
|
|
1315
|
+
if (mode === 'joy') {
|
|
1316
|
+
if (j) sendInput({ type: 'joystick', joystickPort: 2, action: 'release', direction: j.direction, fire: j.fire ?? false });
|
|
1317
|
+
} else if (mode === 'mixed') {
|
|
1318
|
+
if (j) sendInput({ type: 'joystick', joystickPort: 2, action: 'release', direction: j.direction, fire: j.fire ?? false });
|
|
1319
|
+
if (!MIXED_JOY_KEYS.has(e.key)) sendInput({ type: 'key', key: e.key, shiftKey: e.shiftKey, action: 'up' });
|
|
1320
|
+
} else {
|
|
1321
|
+
sendInput({ type: 'key', key: e.key, shiftKey: e.shiftKey, action: 'up' });
|
|
1322
|
+
}
|
|
1323
|
+
});
|
|
1324
|
+
</script>
|
|
1325
|
+
</body>
|
|
1326
|
+
</html>`;
|
|
1327
|
+
}
|