c64-ready 3.1.0 → 3.3.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 +44 -2
- package/bin/agent.mjs +18 -0
- package/bin/serve.mjs +41 -133
- package/dist/assets/ActionBiker-CWiKt9dn.js +1 -0
- package/dist/assets/Panther-D558qV3B.js +1 -0
- package/dist/assets/RainbowIslands-CgoxK_qP.js +1 -0
- package/dist/assets/RoadRunner-DR_cGZ-h.js +1 -0
- package/dist/assets/RocnRope-DrUGJ0pW.js +1 -0
- package/dist/assets/Thrust-rDKv3Thu.js +1 -0
- package/dist/assets/index-C84W-vN0.js +318 -0
- package/dist/assets/src-CNh6UV6R.js +2 -0
- package/dist/index.html +19 -4
- package/dist-ts/player/c64-player.d.ts +8 -0
- package/dist-ts/player/c64-player.d.ts.map +1 -1
- package/dist-ts/player/c64-player.js +14 -1
- package/dist-ts/player/c64-player.js.map +1 -1
- package/dist-ts/player/canvas-renderer.js +1 -1
- package/dist-ts/player/display-layout.d.ts +40 -0
- package/dist-ts/player/display-layout.d.ts.map +1 -0
- package/dist-ts/player/display-layout.js +76 -0
- package/dist-ts/player/display-layout.js.map +1 -0
- package/dist-ts/player/ui-controller.d.ts +15 -2
- package/dist-ts/player/ui-controller.d.ts.map +1 -1
- package/dist-ts/player/ui-controller.js +209 -93
- package/dist-ts/player/ui-controller.js.map +1 -1
- package/dist-ts/player/ultimate-bridge.d.ts +41 -0
- package/dist-ts/player/ultimate-bridge.d.ts.map +1 -0
- package/dist-ts/player/ultimate-bridge.js +117 -0
- package/dist-ts/player/ultimate-bridge.js.map +1 -0
- package/dist-ts/player/ultimate-panel.d.ts +32 -0
- package/dist-ts/player/ultimate-panel.d.ts.map +1 -0
- package/dist-ts/player/ultimate-panel.js +258 -0
- package/dist-ts/player/ultimate-panel.js.map +1 -0
- package/package.json +10 -4
- package/src/headless/agent-cli.mjs +825 -0
- package/src/headless/player-server.mjs +197 -0
- package/src/headless/png.mjs +72 -0
- package/src/headless/webrtc-server.mjs +115 -13
- package/src/main.ts +25 -1
- package/src/player/c64-player.ts +22 -1
- package/src/player/canvas-renderer.ts +1 -1
- package/src/player/display-layout.ts +109 -0
- package/src/player/ui-controller.ts +237 -93
- package/src/player/ultimate-bridge.ts +161 -0
- package/src/player/ultimate-panel.ts +315 -0
- package/dist/assets/RainbowIslands-BjfmJB8z.js +0 -1
- package/dist/assets/index-B8DSjPqI.js +0 -243
- package/dist/assets/src-_trgwTvp.js +0 -2
- /package/dist/assets/{BeachHead-CuSwFD4k.js → BeachHead-BLcSLEEh.js} +0 -0
- /package/dist/assets/{ChuckieEgg-CPqBnAOF.js → ChuckieEgg-Bv2nxhYv.js} +0 -0
- /package/dist/assets/{ForbiddenForest-DsQ9jsc8.js → ForbiddenForest-CWEFgjVq.js} +0 -0
- /package/dist/assets/{Galaga-Cutc3p9s.js → Galaga-DknmKlo5.js} +0 -0
- /package/dist/assets/{Gribbly-DdZ_hHFt.js → Gribbly-nFVwULpF.js} +0 -0
- /package/dist/assets/{Hercules-vZYKm7GG.js → Hercules-Dbx_KaEi.js} +0 -0
- /package/dist/assets/{LegendOfWilf-CxSMOjsj.js → LegendOfWilf-BBW1Y7LQ.js} +0 -0
- /package/dist/assets/{MariosCementFactory-z0IZ0q30.js → MariosCementFactory-DtpgUfFO.js} +0 -0
- /package/dist/assets/{MoleAttack-buC6ChYy.js → MoleAttack-D_2aAX2V.js} +0 -0
- /package/dist/assets/{MunchyWorm-D2Zv7i0Q.js → MunchyWorm-BqWD5x4j.js} +0 -0
- /package/dist/assets/{ParkPatrol-CVj7hyoB.js → ParkPatrol-9pwc_jcb.js} +0 -0
- /package/dist/assets/{PottyPigeon-0SYpIUBa.js → PottyPigeon-CZnjIrGr.js} +0 -0
- /package/dist/assets/{Stix-BU-qUCeC.js → Stix-o2hS_Ekr.js} +0 -0
- /package/dist/assets/{Tilt-C5KtKisF.js → Tilt-BKb_k_R2.js} +0 -0
- /package/dist/assets/{UpNDown-CATRO7Mz.js → UpNDown-BQXEmKfk.js} +0 -0
- /package/dist/assets/{Uridium-DanS2KoH.js → Uridium-9u86vh1V.js} +0 -0
- /package/dist/assets/{VegetablesDeluxe-C41ViimS.js → VegetablesDeluxe-DbmngV50.js} +0 -0
- /package/dist/assets/{marked.esm-fTuuvbcB.js → marked.esm-DhpYx7TE.js} +0 -0
- /package/dist/assets/{purify.es-CRM-GE0Y.js → purify.es-CWuqV7zK.js} +0 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 hayesmaker
|
|
3
|
+
// See LICENSE in the project root for full license information.
|
|
4
|
+
/**
|
|
5
|
+
* player-server.mjs — static HTTP server for the built browser player (`c64-ready` CLI).
|
|
6
|
+
*
|
|
7
|
+
* Optionally serves one local game file (.prg/.d64/.crt/.c64/…) next to the player so the
|
|
8
|
+
* player can boot straight into it via `?game=`. The file is read from disk on every
|
|
9
|
+
* request, so reloading the page picks up a fresh build.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { createServer } from 'node:http';
|
|
13
|
+
import { createReadStream, existsSync, statSync } from 'node:fs';
|
|
14
|
+
import { basename, extname, join, resolve, normalize, sep } from 'node:path';
|
|
15
|
+
import { spawn } from 'node:child_process';
|
|
16
|
+
|
|
17
|
+
export const BASE_PATH = '/c64-ready/';
|
|
18
|
+
export const LOCAL_GAME_PREFIX = `${BASE_PATH}local/`;
|
|
19
|
+
export const GAME_EXTENSIONS = ['.prg', '.d64', '.crt', '.c64', '.s64', '.snapshot'];
|
|
20
|
+
|
|
21
|
+
const MIME = {
|
|
22
|
+
'.html': 'text/html; charset=utf-8',
|
|
23
|
+
'.js': 'application/javascript',
|
|
24
|
+
'.mjs': 'application/javascript',
|
|
25
|
+
'.ts': 'application/javascript',
|
|
26
|
+
'.css': 'text/css',
|
|
27
|
+
'.wasm': 'application/wasm',
|
|
28
|
+
'.svg': 'image/svg+xml',
|
|
29
|
+
'.png': 'image/png',
|
|
30
|
+
'.gif': 'image/gif',
|
|
31
|
+
'.ico': 'image/x-icon',
|
|
32
|
+
'.json': 'application/json',
|
|
33
|
+
'.ttf': 'font/ttf',
|
|
34
|
+
'.map': 'application/json',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export const HELP = `
|
|
38
|
+
c64-ready — serve the C64 browser player
|
|
39
|
+
|
|
40
|
+
Usage:
|
|
41
|
+
c64-ready [game-file] [--port <n>] [--host] [--open] [--help]
|
|
42
|
+
|
|
43
|
+
Arguments:
|
|
44
|
+
game-file A .prg, .d64, .crt or .c64 snapshot to boot straight into. It is
|
|
45
|
+
re-read on every page load, so rebuild and refresh to see changes.
|
|
46
|
+
|
|
47
|
+
Options:
|
|
48
|
+
--port <n> HTTP port (default: 5173, 0 = any free port)
|
|
49
|
+
--host Bind to 0.0.0.0 so the player is reachable on your LAN
|
|
50
|
+
--open Open the player in your default browser
|
|
51
|
+
--help Show this help
|
|
52
|
+
|
|
53
|
+
Examples:
|
|
54
|
+
npx c64-ready
|
|
55
|
+
npx c64-ready build/main.prg --open
|
|
56
|
+
npx c64-ready --port 8080 --host
|
|
57
|
+
`.trim();
|
|
58
|
+
|
|
59
|
+
/** Parse CLI arguments. Throws on invalid input. */
|
|
60
|
+
export function parseServeArgs(argv) {
|
|
61
|
+
const o = { help: false, port: 5173, host: false, open: false, file: null };
|
|
62
|
+
for (let i = 0; i < argv.length; i++) {
|
|
63
|
+
const a = argv[i];
|
|
64
|
+
if (a === '--help' || a === '-h') o.help = true;
|
|
65
|
+
else if (a === '--host') o.host = true;
|
|
66
|
+
else if (a === '--open') o.open = true;
|
|
67
|
+
else if (a === '--port') {
|
|
68
|
+
const v = argv[++i];
|
|
69
|
+
const n = Number(v);
|
|
70
|
+
if (v === undefined || !Number.isInteger(n) || n < 0 || n > 65535) {
|
|
71
|
+
throw new Error(`--port needs a number between 0 and 65535`);
|
|
72
|
+
}
|
|
73
|
+
o.port = n;
|
|
74
|
+
} else if (a.startsWith('-')) throw new Error(`Unknown option: ${a}`);
|
|
75
|
+
else if (o.file) throw new Error(`Only one game file can be served (got ${o.file} and ${a})`);
|
|
76
|
+
else o.file = a;
|
|
77
|
+
}
|
|
78
|
+
if (o.file) {
|
|
79
|
+
const abs = resolve(o.file);
|
|
80
|
+
if (!existsSync(abs) || !statSync(abs).isFile()) throw new Error(`File not found: ${o.file}`);
|
|
81
|
+
const ext = extname(abs).toLowerCase();
|
|
82
|
+
if (!GAME_EXTENSIONS.includes(ext)) {
|
|
83
|
+
throw new Error(
|
|
84
|
+
`Unsupported file type ${ext || '(none)'}: expected ${GAME_EXTENSIONS.join(', ')}`,
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
o.file = abs;
|
|
88
|
+
}
|
|
89
|
+
return o;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The URL path that serves the local game file. */
|
|
93
|
+
export function localGamePath(file) {
|
|
94
|
+
return `${LOCAL_GAME_PREFIX}${encodeURIComponent(basename(file))}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The player URL (path + query) that boots into the local game file. */
|
|
98
|
+
export function playerPath(file) {
|
|
99
|
+
// '/' is legal in a query string, and the file name is already escaped by localGamePath().
|
|
100
|
+
return file ? `${BASE_PATH}?game=${localGamePath(file)}` : BASE_PATH;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Create (but do not start) the player HTTP server.
|
|
105
|
+
* @param {{ distDir: string, gameFile?: string | null }} opts
|
|
106
|
+
*/
|
|
107
|
+
export function createPlayerServer({ distDir, gameFile = null }) {
|
|
108
|
+
const DIST_DIR = resolve(distDir);
|
|
109
|
+
const APP_ENTRY = join(DIST_DIR, 'index.html');
|
|
110
|
+
// Compared after decoding, so it matches however the browser escapes the name.
|
|
111
|
+
const gamePath = gameFile ? `${LOCAL_GAME_PREFIX}${basename(gameFile)}` : null;
|
|
112
|
+
|
|
113
|
+
const sendEntry = (res) => {
|
|
114
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
115
|
+
createReadStream(APP_ENTRY).pipe(res);
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
return createServer((req, res) => {
|
|
119
|
+
const rawPath = (req.url ?? '/').split('?')[0];
|
|
120
|
+
let urlPath;
|
|
121
|
+
try {
|
|
122
|
+
urlPath = decodeURIComponent(rawPath);
|
|
123
|
+
} catch {
|
|
124
|
+
res.writeHead(400);
|
|
125
|
+
res.end('Bad request');
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// The one local game file, if any. Always re-read; never cached.
|
|
130
|
+
if (gamePath && urlPath === gamePath) {
|
|
131
|
+
if (!existsSync(gameFile)) {
|
|
132
|
+
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
|
133
|
+
res.end(`Game file no longer exists: ${gameFile}`);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
res.writeHead(200, {
|
|
137
|
+
'Content-Type': 'application/octet-stream',
|
|
138
|
+
'Content-Length': statSync(gameFile).size,
|
|
139
|
+
'Cache-Control': 'no-store',
|
|
140
|
+
});
|
|
141
|
+
createReadStream(gameFile).pipe(res);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Anything else under /local/ is a game the player asked for that we don't have.
|
|
146
|
+
// A 404 makes the player report it, instead of trying to boot the HTML fallback.
|
|
147
|
+
if (urlPath.startsWith(LOCAL_GAME_PREFIX)) {
|
|
148
|
+
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
|
149
|
+
res.end('Not found');
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// App root: /, /c64-ready, /c64-ready/ → dist/index.html
|
|
154
|
+
if (urlPath === '/' || urlPath === '/c64-ready' || urlPath === BASE_PATH) {
|
|
155
|
+
sendEntry(res);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Everything else resolves against dist/. Vite bakes base='/c64-ready/' into asset
|
|
160
|
+
// URLs, so strip it: /c64-ready/assets/x.js → dist/assets/x.js.
|
|
161
|
+
const stripped = urlPath.startsWith(BASE_PATH) ? urlPath.slice(BASE_PATH.length) : urlPath;
|
|
162
|
+
const relative = stripped.startsWith('/') ? stripped.slice(1) : stripped;
|
|
163
|
+
const filePath = resolve(DIST_DIR, normalize(relative));
|
|
164
|
+
|
|
165
|
+
if (filePath !== DIST_DIR && !filePath.startsWith(DIST_DIR + sep)) {
|
|
166
|
+
res.writeHead(403);
|
|
167
|
+
res.end('Forbidden');
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (!existsSync(filePath) || !statSync(filePath).isFile()) {
|
|
172
|
+
sendEntry(res); // SPA fallback
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const mime = MIME[extname(filePath).toLowerCase()] ?? 'application/octet-stream';
|
|
177
|
+
res.writeHead(200, { 'Content-Type': mime });
|
|
178
|
+
createReadStream(filePath).pipe(res);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Open a URL in the default browser. Best effort: failures are reported, never thrown. */
|
|
183
|
+
export function openInBrowser(url, { platform = process.platform, spawnFn = spawn } = {}) {
|
|
184
|
+
const [cmd, args] =
|
|
185
|
+
platform === 'darwin'
|
|
186
|
+
? ['open', [url]]
|
|
187
|
+
: platform === 'win32'
|
|
188
|
+
? ['cmd', ['/c', 'start', '""', url]]
|
|
189
|
+
: ['xdg-open', [url]];
|
|
190
|
+
try {
|
|
191
|
+
const child = spawnFn(cmd, args, { stdio: 'ignore', detached: true });
|
|
192
|
+
child.on?.('error', () => console.error(` (could not open a browser: open ${url} manually)`));
|
|
193
|
+
child.unref?.();
|
|
194
|
+
} catch {
|
|
195
|
+
console.error(` (could not open a browser: open ${url} manually)`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
// Copyright (c) 2026 hayesmaker
|
|
3
|
+
// See LICENSE in the project root for full license information.
|
|
4
|
+
/**
|
|
5
|
+
* png.mjs — dependency-free PNG encoder for raw RGBA frame buffers.
|
|
6
|
+
*
|
|
7
|
+
* Used by the agent CLI (`c64-agent --screenshot`) to write emulator frames
|
|
8
|
+
* to disk. Relies only on node:zlib (deflateSync + crc32).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { deflateSync, crc32 } from 'node:zlib';
|
|
12
|
+
|
|
13
|
+
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
14
|
+
|
|
15
|
+
function chunk(type, data) {
|
|
16
|
+
const len = Buffer.alloc(4);
|
|
17
|
+
len.writeUInt32BE(data.length, 0);
|
|
18
|
+
const typeAndData = Buffer.concat([Buffer.from(type, 'ascii'), data]);
|
|
19
|
+
const crc = Buffer.alloc(4);
|
|
20
|
+
crc.writeUInt32BE(crc32(typeAndData) >>> 0, 0);
|
|
21
|
+
return Buffer.concat([len, typeAndData, crc]);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Encode an RGBA buffer as an 8-bit truecolour PNG (alpha dropped — C64 frames are opaque).
|
|
26
|
+
*
|
|
27
|
+
* @param {Uint8Array} rgba width*height*4 bytes
|
|
28
|
+
* @param {number} width
|
|
29
|
+
* @param {number} height
|
|
30
|
+
* @param {{ scale?: number }} [opts] integer nearest-neighbour upscale (default 1)
|
|
31
|
+
* @returns {Buffer}
|
|
32
|
+
*/
|
|
33
|
+
export function encodePng(rgba, width, height, opts = {}) {
|
|
34
|
+
const scale = Math.max(1, Math.floor(opts.scale ?? 1));
|
|
35
|
+
if (rgba.length < width * height * 4) {
|
|
36
|
+
throw new Error(`encodePng: buffer too small (${rgba.length} < ${width * height * 4})`);
|
|
37
|
+
}
|
|
38
|
+
const outW = width * scale;
|
|
39
|
+
const outH = height * scale;
|
|
40
|
+
const stride = outW * 3 + 1;
|
|
41
|
+
const raw = Buffer.alloc(stride * outH);
|
|
42
|
+
|
|
43
|
+
for (let y = 0; y < outH; y++) {
|
|
44
|
+
const srcRow = Math.floor(y / scale) * width * 4;
|
|
45
|
+
let o = y * stride;
|
|
46
|
+
raw[o++] = 0; // filter: none
|
|
47
|
+
for (let x = 0; x < outW; x++) {
|
|
48
|
+
const s = srcRow + Math.floor(x / scale) * 4;
|
|
49
|
+
raw[o++] = rgba[s];
|
|
50
|
+
raw[o++] = rgba[s + 1];
|
|
51
|
+
raw[o++] = rgba[s + 2];
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const ihdr = Buffer.alloc(13);
|
|
56
|
+
ihdr.writeUInt32BE(outW, 0);
|
|
57
|
+
ihdr.writeUInt32BE(outH, 4);
|
|
58
|
+
ihdr[8] = 8; // bit depth
|
|
59
|
+
ihdr[9] = 2; // colour type: truecolour RGB
|
|
60
|
+
ihdr[10] = 0; // compression
|
|
61
|
+
ihdr[11] = 0; // filter
|
|
62
|
+
ihdr[12] = 0; // interlace
|
|
63
|
+
|
|
64
|
+
return Buffer.concat([
|
|
65
|
+
PNG_SIGNATURE,
|
|
66
|
+
chunk('IHDR', ihdr),
|
|
67
|
+
chunk('IDAT', deflateSync(raw, { level: 6 })),
|
|
68
|
+
chunk('IEND', Buffer.alloc(0)),
|
|
69
|
+
]);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export default encodePng;
|
|
@@ -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 (_) {
|
|
@@ -632,7 +734,7 @@ export function createWebRTCServer({
|
|
|
632
734
|
const remoteAddr = req.socket.remoteAddress;
|
|
633
735
|
const sessionId = crypto.randomUUID();
|
|
634
736
|
pendingPeers++;
|
|
635
|
-
const pc = new RTCPeerConnection(
|
|
737
|
+
const pc = new RTCPeerConnection(buildPeerConnectionConfig());
|
|
636
738
|
const controller = {
|
|
637
739
|
pc,
|
|
638
740
|
ws: null,
|
|
@@ -860,7 +962,7 @@ export function createWebRTCServer({
|
|
|
860
962
|
logEv('webrtc-peer-connected', { addr: remoteAddr });
|
|
861
963
|
logLoadSnapshot('webrtc-load-change', { reason: 'peer-connected' });
|
|
862
964
|
|
|
863
|
-
const pc = new RTCPeerConnection(
|
|
965
|
+
const pc = new RTCPeerConnection(buildPeerConnectionConfig());
|
|
864
966
|
const controller = {
|
|
865
967
|
pc,
|
|
866
968
|
ws,
|
package/src/main.ts
CHANGED
|
@@ -40,7 +40,11 @@ const cheevosTrackerPanel = new CheevosTrackerPanel();
|
|
|
40
40
|
cheevosTrackerPanel.init();
|
|
41
41
|
|
|
42
42
|
// Initialise UI with reference to the player (for audio controls)
|
|
43
|
-
new UIController({
|
|
43
|
+
new UIController({
|
|
44
|
+
assetBaseUrl: base,
|
|
45
|
+
appVersion: import.meta.env.VITE_APP_VERSION,
|
|
46
|
+
gitHash: import.meta.env.VITE_GIT_HASH,
|
|
47
|
+
}).init(player);
|
|
44
48
|
|
|
45
49
|
player
|
|
46
50
|
.start()
|
|
@@ -193,16 +197,36 @@ window.addEventListener('c64-load-error', (e: Event) => {
|
|
|
193
197
|
| undefined;
|
|
194
198
|
const msg = normalizeErrorMessage(detail?.error ?? 'Unknown load error');
|
|
195
199
|
console.error('C64 load error event:', detail);
|
|
200
|
+
loadWarningShown = false;
|
|
196
201
|
renderer.setError('LOAD ERROR');
|
|
197
202
|
status.textContent = `Load error: ${msg}`;
|
|
198
203
|
status.style.color = '#f44';
|
|
199
204
|
});
|
|
200
205
|
|
|
206
|
+
// Set while a load-time warning is on screen so the success message doesn't hide it
|
|
207
|
+
let loadWarningShown = false;
|
|
208
|
+
|
|
209
|
+
window.addEventListener('c64-load-success', (e: Event) => {
|
|
210
|
+
const detail = (e as CustomEvent<{ name?: string }>).detail;
|
|
211
|
+
if (loadWarningShown) {
|
|
212
|
+
loadWarningShown = false;
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
status.textContent = `Loaded: ${detail?.name ?? 'game'}`;
|
|
216
|
+
status.style.color = '#9ecbff';
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
window.addEventListener('c64-detach', () => {
|
|
220
|
+
status.textContent = 'Cartridge detached (no game loaded)';
|
|
221
|
+
status.style.color = '#9ecbff';
|
|
222
|
+
});
|
|
223
|
+
|
|
201
224
|
window.addEventListener('c64-load-info', (e: Event) => {
|
|
202
225
|
const detail = (e as CustomEvent).detail as
|
|
203
226
|
| { mode?: string; source?: string; message?: string }
|
|
204
227
|
| undefined;
|
|
205
228
|
if (!detail?.message) return;
|
|
229
|
+
loadWarningShown = detail.mode === 'warning';
|
|
206
230
|
status.textContent = detail.message;
|
|
207
231
|
status.style.color = detail.mode === 'warning' ? '#f9c74f' : '#9ecbff';
|
|
208
232
|
console.info('C64 load info event:', detail);
|
package/src/player/c64-player.ts
CHANGED
|
@@ -38,6 +38,12 @@ export interface C64PlayerOptions {
|
|
|
38
38
|
audio?: AudioEngineOptions;
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
+
export interface LoadedGame {
|
|
42
|
+
name: string;
|
|
43
|
+
type: GameLoadOptions['type'];
|
|
44
|
+
data: Uint8Array<ArrayBufferLike>;
|
|
45
|
+
}
|
|
46
|
+
|
|
41
47
|
export class C64Player {
|
|
42
48
|
private emulator: C64Emulator | null = null;
|
|
43
49
|
private inputHandler: InputHandler | null = null;
|
|
@@ -49,6 +55,7 @@ export class C64Player {
|
|
|
49
55
|
private startupLoadInProgress: boolean = false;
|
|
50
56
|
private startupDiskAutoloadPending: boolean = false;
|
|
51
57
|
private debugSpeed: number = NORMAL_DEBUG_SPEED;
|
|
58
|
+
private currentGame: LoadedGame | null = null;
|
|
52
59
|
readonly audio: AudioEngine;
|
|
53
60
|
private readonly options: Required<Pick<C64PlayerOptions, 'wasmUrl' | 'gameUrl' | 'gameType'>> &
|
|
54
61
|
C64PlayerOptions;
|
|
@@ -227,6 +234,11 @@ export class C64Player {
|
|
|
227
234
|
await this.loadGame(url, resolvedType, onProgress);
|
|
228
235
|
}
|
|
229
236
|
|
|
237
|
+
/** The most recently loaded game, or null after a detach/reboot. */
|
|
238
|
+
getCurrentGame(): LoadedGame | null {
|
|
239
|
+
return this.currentGame;
|
|
240
|
+
}
|
|
241
|
+
|
|
230
242
|
// Expose cartridge / reset controls for UI
|
|
231
243
|
detachCartridge(): void {
|
|
232
244
|
if (!this.emulator) return;
|
|
@@ -234,6 +246,7 @@ export class C64Player {
|
|
|
234
246
|
this.emulator.removeCartridge();
|
|
235
247
|
this.diskSessionActive = false;
|
|
236
248
|
this.startupDiskAutoloadPending = false;
|
|
249
|
+
this.currentGame = null;
|
|
237
250
|
window.dispatchEvent(new CustomEvent('c64-detach', { detail: {} }));
|
|
238
251
|
window.dispatchEvent(new CustomEvent('c64-close-menu'));
|
|
239
252
|
} catch (e) {
|
|
@@ -262,6 +275,7 @@ export class C64Player {
|
|
|
262
275
|
this.emulator.start();
|
|
263
276
|
this.diskSessionActive = false;
|
|
264
277
|
this.startupDiskAutoloadPending = false;
|
|
278
|
+
this.currentGame = null;
|
|
265
279
|
this.emulator.setSampleRate(this.audio.sampleRate);
|
|
266
280
|
this.applyDebugSpeed();
|
|
267
281
|
this.audio.setSidBufferReader(() => this.emulator?.getSidBuffer() ?? null);
|
|
@@ -488,9 +502,11 @@ export class C64Player {
|
|
|
488
502
|
} else {
|
|
489
503
|
this.diskSessionActive = false;
|
|
490
504
|
}
|
|
505
|
+
const name = getSourceName(source);
|
|
506
|
+
this.currentGame = { name, type, data };
|
|
491
507
|
onProgress?.(100, 'READY!');
|
|
492
508
|
window.dispatchEvent(
|
|
493
|
-
new CustomEvent('c64-load-success', { detail: { ...eventDetail, type } }),
|
|
509
|
+
new CustomEvent('c64-load-success', { detail: { ...eventDetail, name, type } }),
|
|
494
510
|
);
|
|
495
511
|
} catch (err) {
|
|
496
512
|
onProgress?.(0, 'FAILED');
|
|
@@ -694,3 +710,8 @@ function hasViceSnapshotMagic(data: Uint8Array<ArrayBufferLike>): boolean {
|
|
|
694
710
|
}
|
|
695
711
|
return true;
|
|
696
712
|
}
|
|
713
|
+
|
|
714
|
+
function getSourceName(source: string): string {
|
|
715
|
+
const path = source.split(/[?#]/)[0];
|
|
716
|
+
return path.split('/').filter(Boolean).pop() || source;
|
|
717
|
+
}
|