c64-ready 2.1.0 → 2.4.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.
Files changed (61) hide show
  1. package/README.md +4 -1
  2. package/bin/admin.mjs +0 -0
  3. package/bin/headless.mjs +1 -0
  4. package/dist/assets/index-Dxuihfdi.js +177 -0
  5. package/dist/index.html +1 -1
  6. package/dist-ts/emulator/c64-emulator.d.ts +1 -1
  7. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  8. package/dist-ts/emulator/c64-emulator.js +1 -0
  9. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  10. package/dist-ts/emulator/c64-wasm.d.ts +4 -4
  11. package/dist-ts/emulator/c64-wasm.d.ts.map +1 -1
  12. package/dist-ts/emulator/c64-wasm.js.map +1 -1
  13. package/dist-ts/emulator/input.d.ts +9 -2
  14. package/dist-ts/emulator/input.d.ts.map +1 -1
  15. package/dist-ts/emulator/input.js +40 -10
  16. package/dist-ts/emulator/input.js.map +1 -1
  17. package/dist-ts/player/audio-engine.d.ts.map +1 -1
  18. package/dist-ts/player/audio-engine.js +4 -0
  19. package/dist-ts/player/audio-engine.js.map +1 -1
  20. package/dist-ts/player/c64-player.d.ts +10 -2
  21. package/dist-ts/player/c64-player.d.ts.map +1 -1
  22. package/dist-ts/player/c64-player.js +109 -30
  23. package/dist-ts/player/c64-player.js.map +1 -1
  24. package/dist-ts/player/index.d.ts +1 -1
  25. package/dist-ts/player/index.d.ts.map +1 -1
  26. package/dist-ts/player/input-handler.d.ts +4 -1
  27. package/dist-ts/player/input-handler.d.ts.map +1 -1
  28. package/dist-ts/player/input-handler.js +10 -11
  29. package/dist-ts/player/input-handler.js.map +1 -1
  30. package/dist-ts/player/load-formats.js +1 -1
  31. package/dist-ts/player/load-formats.js.map +1 -1
  32. package/dist-ts/player/ui-controller.d.ts.map +1 -1
  33. package/dist-ts/player/ui-controller.js +8 -1
  34. package/dist-ts/player/ui-controller.js.map +1 -1
  35. package/package.json +5 -4
  36. package/src/emulator/c64-emulator.ts +2 -1
  37. package/src/emulator/c64-wasm.ts +4 -4
  38. package/src/emulator/input.ts +50 -16
  39. package/src/headless/c64-key-map.mjs +357 -165
  40. package/src/headless/c64-wasm.mjs +2 -2
  41. package/src/headless/ffmpeg-runner.mjs +214 -75
  42. package/src/headless/headless-cli.d.ts +1 -1
  43. package/src/headless/headless-cli.mjs +137 -19
  44. package/src/headless/headless-cli.mjs.d.ts +1 -1
  45. package/src/headless/input-server.mjs +511 -67
  46. package/src/headless/webrtc-encoder.mjs +49 -25
  47. package/src/headless/webrtc-server.mjs +21 -20
  48. package/src/main.ts +3 -2
  49. package/src/player/audio-engine.ts +4 -0
  50. package/src/player/c64-player.ts +115 -34
  51. package/src/player/index.ts +8 -1
  52. package/src/player/input-handler.ts +13 -12
  53. package/src/player/load-formats.ts +1 -1
  54. package/src/player/styles/canvas-renderer.css +10 -5
  55. package/src/player/ui-controller.ts +25 -14
  56. package/dist/assets/index-Df2-qP_u.js +0 -169
  57. package/dist-ts/emulator/memory.d.ts +0 -2
  58. package/dist-ts/emulator/memory.d.ts.map +0 -1
  59. package/dist-ts/emulator/memory.js +0 -9
  60. package/dist-ts/emulator/memory.js.map +0 -1
  61. package/src/emulator/memory.ts +0 -9
@@ -17,7 +17,7 @@ import { randomBytes } from 'crypto';
17
17
  * @param {number} [opts.port=9001]
18
18
  * @param {Function} opts.onInput
19
19
  * @param {Function} [opts.onCommand] Called with emulator commands from the host:
20
- * { type: 'load-crt'|'detach-crt'|'hard-reset'|'reboot', ... }
20
+ * { type: 'load-crt'|'load-file'|'detach-crt'|'hard-reset'|'reboot', ... }
21
21
  * @param {boolean} [opts.verbose]
22
22
  * @param {number} [opts.hostTimeoutMs=300000]
23
23
  * @param {Function} [opts.validateKickToken]
@@ -28,6 +28,12 @@ import { randomBytes } from 'crypto';
28
28
  * @param {Function} [opts.getWebrtcPeerSnapshot]
29
29
  * @param {Function} [opts.disconnectWebrtcPeersByAddr]
30
30
  * @param {Function} [opts.disconnectAllWebrtcPeers]
31
+ * @param {Object} [opts.attractMode]
32
+ * @param {boolean} [opts.attractMode.enabled]
33
+ * @param {boolean} [opts.attractMode.autostart]
34
+ * @param {string} [opts.attractMode.baseUrl]
35
+ * @param {string} [opts.attractMode.manifest]
36
+ * @param {number} [opts.diskAutoloadDelayMs]
31
37
  * @param {string} [opts.serverVersion] Package version string, e.g. '0.7.0'
32
38
  * @param {string} [opts.serverGitHash] Abbreviated git commit hash, e.g. '16e86cd'
33
39
  * @returns {{ wss: WebSocketServer, close: () => Promise<void> }}
@@ -130,6 +136,9 @@ export function createInputServer(opts = {}) {
130
136
  const wss = new WebSocketServer({ port });
131
137
  const HOST_RECONNECT_GRACE = opts.hostReconnectGraceMs ?? 8_000;
132
138
  const P2_RECONNECT_GRACE = opts.p2ReconnectGraceMs ?? HOST_RECONNECT_GRACE;
139
+ const DISK_AUTOLOAD_AFTER_LOAD_DELAY_MS = Number.isFinite(opts.diskAutoloadDelayMs)
140
+ ? Math.max(0, Number(opts.diskAutoloadDelayMs))
141
+ : 2_000;
133
142
 
134
143
  // ── Room state ────────────────────────────────────────────────────────────
135
144
  let hostClient = null;
@@ -157,6 +166,155 @@ export function createInputServer(opts = {}) {
157
166
  // Seeded from opts.initialCartFilename when a default game is pre-loaded.
158
167
  let currentCartFilename = opts.initialCartFilename ?? null;
159
168
 
169
+ // ── Attract mode ──────────────────────────────────────────────────────────
170
+ const attractConfig = opts.attractMode ?? {};
171
+ const attractEnabled = !!attractConfig.enabled && !!String(attractConfig.baseUrl ?? '').trim();
172
+ const attractBaseUrl = String(attractConfig.baseUrl ?? '').replace(/\/+$/, '');
173
+ const attractManifest = String(attractConfig.manifest ?? 'playlists.json').replace(/^\/+/, '');
174
+ let attractTimer = null;
175
+ let emptyRoomAttractTimer = null;
176
+ let attractStatus = { active: false };
177
+ let attractPlaylist = null;
178
+ let attractCursor = null;
179
+ let attractGeneration = 0;
180
+
181
+ function clearAttractTimer() {
182
+ if (attractTimer) clearTimeout(attractTimer);
183
+ attractTimer = null;
184
+ }
185
+
186
+ function clearEmptyRoomAttractTimer() {
187
+ if (emptyRoomAttractTimer) clearTimeout(emptyRoomAttractTimer);
188
+ emptyRoomAttractTimer = null;
189
+ }
190
+
191
+ function sleepMs(ms) {
192
+ return new Promise((resolve) => setTimeout(resolve, ms));
193
+ }
194
+
195
+ function attractStatusPayload() {
196
+ return { ...attractStatus };
197
+ }
198
+
199
+ function broadcastAttractMode() {
200
+ broadcastAll({ type: 'attract-mode-status', attractMode: attractStatusPayload() });
201
+ }
202
+
203
+ function resolveAttractUrl(...parts) {
204
+ const suffix = parts
205
+ .filter(Boolean)
206
+ .map((part) => String(part).replace(/^\/+|\/+$/g, ''))
207
+ .filter(Boolean)
208
+ .map((part) => part.split('/').filter(Boolean).map(encodeURIComponent).join('/'))
209
+ .join('/');
210
+ return `${attractBaseUrl}/${suffix}`;
211
+ }
212
+
213
+ function joinEncodedPath(...parts) {
214
+ return parts
215
+ .filter(Boolean)
216
+ .map((part) => String(part).replace(/^\/+|\/+$/g, ''))
217
+ .filter(Boolean)
218
+ .map((part) => part.split('/').filter(Boolean).map(encodeURIComponent).join('/'))
219
+ .join('/');
220
+ }
221
+
222
+ function resolveAttractRootUrl(...parts) {
223
+ const base = new URL(attractBaseUrl);
224
+ return `${base.origin}/${joinEncodedPath(...parts)}`;
225
+ }
226
+
227
+ async function fetchAttractJson(url) {
228
+ logEv('attract-fetch-json-start', { url });
229
+ const res = await fetch(url, { headers: { Accept: 'application/json' } });
230
+ logEv('attract-fetch-json-done', {
231
+ url,
232
+ status: res.status,
233
+ contentType: res.headers?.get?.('content-type') ?? '-',
234
+ contentLength: res.headers?.get?.('content-length') ?? '-',
235
+ });
236
+ if (!res.ok) throw new Error(`Failed to fetch ${url}: HTTP ${res.status}`);
237
+ return res.json();
238
+ }
239
+
240
+ async function fetchAttractFileBase64(url) {
241
+ logEv('attract-fetch-file-start', { url });
242
+ const res = await fetch(url);
243
+ const contentType = res.headers?.get?.('content-type') ?? '-';
244
+ const contentLength = res.headers?.get?.('content-length') ?? '-';
245
+ if (!res.ok) throw new Error(`Failed to fetch ${url}: HTTP ${res.status}`);
246
+ const buf = Buffer.from(await res.arrayBuffer());
247
+ logEv('attract-fetch-file-done', {
248
+ url,
249
+ status: res.status,
250
+ contentType,
251
+ contentLength,
252
+ bytes: buf.length,
253
+ });
254
+ return buf.toString('base64');
255
+ }
256
+
257
+ function chooseRandom(items) {
258
+ return items[Math.floor(Math.random() * items.length)];
259
+ }
260
+
261
+ function getAttractItem(itemIndex) {
262
+ const item = attractPlaylist?.items?.[itemIndex];
263
+ if (!item?.name) throw new Error('Attract Mode demo is missing a name');
264
+ if (!Array.isArray(item.files) || item.files.length === 0) {
265
+ throw new Error(`${item.name} has no files`);
266
+ }
267
+ return item;
268
+ }
269
+
270
+ function getAttractFile(item, fileIndex) {
271
+ const file = item.files?.[fileIndex];
272
+ if (!file?.filename && !file?.url) throw new Error(`${item.name} has an invalid file entry`);
273
+ return file;
274
+ }
275
+
276
+ function resolveAttractFileUrl(item, file) {
277
+ if (file.url) return file.url;
278
+ const basePath = attractPlaylist.basePath ?? '';
279
+ if (String(basePath).startsWith('/')) {
280
+ return resolveAttractRootUrl(basePath, item.path, file.path, file.filename);
281
+ }
282
+ return resolveAttractUrl(basePath, item.path, file.path, file.filename);
283
+ }
284
+
285
+ function setAttractStatus({ item, file, itemIndex, fileIndex, filename }) {
286
+ const duration = Number(file.duration) > 0 ? Number(file.duration) : 300;
287
+ attractCursor = { itemIndex, fileIndex, filename, duration };
288
+ attractStatus = {
289
+ active: true,
290
+ playlistName: attractPlaylist.name,
291
+ demoTitle: item.name,
292
+ demoName: item.group ? `${item.name} - ${item.group}` : item.name,
293
+ demoGroup: item.group ?? null,
294
+ csdbUrl: item.url ?? null,
295
+ rating: item.rating ?? null,
296
+ playlistPath: attractPlaylist._playlistPath ?? null,
297
+ itemIndex,
298
+ fileIndex,
299
+ filename,
300
+ duration,
301
+ startedAt: Date.now(),
302
+ nextAdvanceAt: Date.now() + duration * 1000,
303
+ };
304
+ }
305
+
306
+ function stopAttractMode({ broadcast = true, reason = 'stopped' } = {}) {
307
+ const wasActive = !!attractStatus.active;
308
+ attractGeneration += 1;
309
+ clearAttractTimer();
310
+ clearEmptyRoomAttractTimer();
311
+ attractStatus = { active: false, reason, updatedAt: Date.now() };
312
+ attractPlaylist = null;
313
+ attractCursor = null;
314
+ if (broadcast && wasActive) broadcastAttractMode();
315
+ return wasActive;
316
+ }
317
+
160
318
  function hostPort() {
161
319
  return portOverrideEnabled ? overrideHostPort : portsSwapped ? 1 : 2;
162
320
  }
@@ -211,6 +369,7 @@ export function createInputServer(opts = {}) {
211
369
  clearP2Timeout();
212
370
  broadcastAll({ type: 'player2-left', username: leaving, reason: 'timeout' });
213
371
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
372
+ startAttractModeIfRoomEmpty('p2-timeout');
214
373
  }
215
374
 
216
375
  // ── Host reconnect grace period helpers ───────────────────────────────────
@@ -239,6 +398,7 @@ export function createInputServer(opts = {}) {
239
398
  logEv('host-grace-expired', { username: leaving });
240
399
  broadcastAll({ type: 'host-left', username: leaving, reason: 'disconnect' });
241
400
  broadcastAll({ type: 'p2-slot-status', open: false });
401
+ scheduleAttractModeIfRoomEmpty('host-disconnect');
242
402
  }
243
403
 
244
404
  // Called on host WS close — starts grace period, notifies clients.
@@ -263,6 +423,7 @@ export function createInputServer(opts = {}) {
263
423
  logEv('p2-grace-expired', { username: leaving });
264
424
  broadcastAll({ type: 'player2-left', username: leaving, reason: 'disconnect' });
265
425
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
426
+ scheduleAttractModeIfRoomEmpty('p2-disconnect');
266
427
  }
267
428
 
268
429
  function onP2Disconnect(leaving) {
@@ -297,6 +458,7 @@ export function createInputServer(opts = {}) {
297
458
  // Broadcast host-left with reason so clients can show a contextual notice
298
459
  broadcastAll({ type: 'host-left', username: leaving, reason: 'timeout' });
299
460
  broadcastAll({ type: 'p2-slot-status', open: false });
461
+ startAttractModeIfRoomEmpty('host-timeout');
300
462
  }
301
463
 
302
464
  function kickHostByReason(reason = 'admin-kick') {
@@ -323,6 +485,7 @@ export function createInputServer(opts = {}) {
323
485
  broadcastAll({ type: 'host-left', username: leaving, reason });
324
486
  broadcastAll({ type: 'p2-slot-status', open: false });
325
487
  if (addr) disconnectWebrtcPeersByAddr(addr, reason);
488
+ scheduleAttractModeIfRoomEmpty(`host-${reason}`);
326
489
  return { kicked: true, username: leaving, addr };
327
490
  }
328
491
 
@@ -345,6 +508,7 @@ export function createInputServer(opts = {}) {
345
508
  broadcastAll({ type: 'player2-left', username: leaving, reason });
346
509
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
347
510
  if (addr) disconnectWebrtcPeersByAddr(addr, reason);
511
+ scheduleAttractModeIfRoomEmpty(`p2-${reason}`);
348
512
  return { kicked: true, username: leaving, addr };
349
513
  }
350
514
 
@@ -371,6 +535,220 @@ export function createInputServer(opts = {}) {
371
535
  );
372
536
  }
373
537
 
538
+ async function runLoadFileCommand({ filename, fileType, data, autoLoadDisk, source = 'host' }) {
539
+ const loadFilename = filename ?? '';
540
+ const loadType = fileType ?? 'crt';
541
+ const generation = attractGeneration;
542
+ broadcastAll({ type: 'cart-loading', filename: loadFilename });
543
+ try {
544
+ if (source === 'attract-mode' && generation !== attractGeneration) return false;
545
+ if (source === 'attract-mode') {
546
+ logEv('attract-load-file-start', {
547
+ filename: loadFilename,
548
+ fileType: loadType,
549
+ autoLoadDisk: autoLoadDisk ?? '-',
550
+ base64Len: (data ?? '').length,
551
+ });
552
+ }
553
+ await onCommand({
554
+ type: 'load-file',
555
+ filename: loadFilename,
556
+ fileType: loadType,
557
+ autoLoadDisk,
558
+ data: data ?? '',
559
+ });
560
+ if (source === 'attract-mode' && generation !== attractGeneration) return false;
561
+ currentCartFilename = loadFilename || null;
562
+ broadcastAll({ type: 'cart-loaded', filename: loadFilename, fileType: loadType, source });
563
+ if (source === 'attract-mode') {
564
+ logEv('attract-cart-loaded-broadcast', {
565
+ filename: loadFilename,
566
+ fileType: loadType,
567
+ autoLoadDisk: autoLoadDisk ?? '-',
568
+ });
569
+ }
570
+ if (loadType === 'd64' && autoLoadDisk) {
571
+ if (source === 'attract-mode') {
572
+ logEv('attract-autoload-delay-start', {
573
+ filename: loadFilename,
574
+ delayMs: DISK_AUTOLOAD_AFTER_LOAD_DELAY_MS,
575
+ });
576
+ }
577
+ await sleepMs(DISK_AUTOLOAD_AFTER_LOAD_DELAY_MS);
578
+ if (source === 'attract-mode' && generation !== attractGeneration) return false;
579
+ if (source === 'attract-mode') logEv('attract-autoload-command-send', { filename: loadFilename });
580
+ await onCommand({ type: 'auto-load-disk' });
581
+ if (source === 'attract-mode') logEv('attract-autoload-command-done', { filename: loadFilename });
582
+ }
583
+ return true;
584
+ } catch (e) {
585
+ broadcastAll({ type: 'cart-load-error', reason: String(e?.message ?? e), source });
586
+ if (verbose) console.error('[input-server] load-file error:', e);
587
+ logEv('error', {
588
+ kind: 'load-file-failed',
589
+ filename: loadFilename,
590
+ fileType: loadType,
591
+ source,
592
+ err: String(e?.message ?? e),
593
+ });
594
+ throw e;
595
+ }
596
+ }
597
+
598
+ async function runHardResetCommand({ source = 'host' } = {}) {
599
+ await onCommand({ type: 'hard-reset' });
600
+ broadcastAll({ type: 'machine-reset', source });
601
+ }
602
+
603
+ async function runRebootCommand({ source = 'host', stopAttract = true } = {}) {
604
+ if (stopAttract) stopAttractMode({ reason: 'reboot' });
605
+ await onCommand({ type: 'reboot' });
606
+ currentCartFilename = null;
607
+ broadcastAll({ type: 'machine-rebooted', source });
608
+ }
609
+
610
+ function scheduleAttractAdvance() {
611
+ clearAttractTimer();
612
+ if (!attractStatus.active || !attractCursor) return;
613
+ attractTimer = setTimeout(() => {
614
+ advanceAttractMode().catch((err) => {
615
+ console.error('[input-server] attract mode advance failed:', err?.message ?? err);
616
+ stopAttractMode({ reason: 'error' });
617
+ });
618
+ }, attractCursor.duration * 1000);
619
+ if (typeof attractTimer.unref === 'function') attractTimer.unref();
620
+ }
621
+
622
+ async function loadAttractEntry(itemIndex, fileIndex, { mountOnly = false, rebootBeforeLoad = false } = {}) {
623
+ const generation = attractGeneration;
624
+ const item = getAttractItem(itemIndex);
625
+ const file = getAttractFile(item, fileIndex);
626
+ const filename = file.filename ?? file.url.split('/').pop();
627
+ const fileType = String(filename).toLowerCase().endsWith('.d64')
628
+ ? 'd64'
629
+ : String(filename).toLowerCase().endsWith('.prg')
630
+ ? 'prg'
631
+ : String(filename).toLowerCase().endsWith('.crt')
632
+ ? 'crt'
633
+ : 'crt';
634
+ const url = resolveAttractFileUrl(item, file);
635
+ logEv('attract-entry-selected', {
636
+ playlist: attractPlaylist?.name ?? '-',
637
+ demo: item.group ? `${item.name} - ${item.group}` : item.name,
638
+ itemIndex,
639
+ fileIndex,
640
+ filename,
641
+ fileType,
642
+ url,
643
+ mountOnly,
644
+ rebootBeforeLoad,
645
+ rebootFileBeforeLoad: file.reboot === true,
646
+ });
647
+ if (rebootBeforeLoad) {
648
+ await runRebootCommand({ source: 'attract-mode', stopAttract: false });
649
+ if (generation !== attractGeneration) return;
650
+ }
651
+ if (file.reboot === true) {
652
+ logEv('attract-reboot-before-disk', { filename, itemIndex, fileIndex });
653
+ await runRebootCommand({ source: 'attract-mode', stopAttract: false });
654
+ if (generation !== attractGeneration) return;
655
+ await sleepMs(1000);
656
+ if (generation !== attractGeneration) return;
657
+ }
658
+ const data = await fetchAttractFileBase64(url);
659
+ if (generation !== attractGeneration) return;
660
+ setAttractStatus({ item, file, itemIndex, fileIndex, filename });
661
+ broadcastAttractMode();
662
+ await runLoadFileCommand({
663
+ filename,
664
+ fileType,
665
+ data,
666
+ autoLoadDisk: fileType === 'd64' ? (!mountOnly || file.reboot === true) : undefined,
667
+ source: 'attract-mode',
668
+ });
669
+ if (generation !== attractGeneration) return;
670
+ scheduleAttractAdvance();
671
+ }
672
+
673
+ async function startAttractMode(demoIndex = 0) {
674
+ if (!attractEnabled) throw new Error('Attract Mode is not configured');
675
+ attractGeneration += 1;
676
+ clearAttractTimer();
677
+ const manifest = await fetchAttractJson(resolveAttractUrl(attractManifest));
678
+ logEv('attract-manifest-loaded', { count: Array.isArray(manifest) ? manifest.length : '-' });
679
+ if (!Array.isArray(manifest) || manifest.length === 0) {
680
+ throw new Error('No Attract Mode playlists configured');
681
+ }
682
+ const playlistEntry = chooseRandom(manifest);
683
+ const playlistPath = typeof playlistEntry === 'string' ? playlistEntry : playlistEntry?.filename;
684
+ if (!playlistPath) throw new Error('Invalid Attract Mode playlist entry');
685
+ logEv('attract-playlist-selected', { playlistPath });
686
+ const playlist = await fetchAttractJson(resolveAttractUrl(playlistPath));
687
+ if (!playlist?.name) throw new Error('Attract Mode playlist is missing a name');
688
+ if (!Array.isArray(playlist.items) || playlist.items.length === 0) {
689
+ throw new Error('Attract Mode playlist has no demos');
690
+ }
691
+ if (demoIndex < 0 || demoIndex >= playlist.items.length) {
692
+ throw new Error(`Demo index ${demoIndex} is out of bounds (playlist has ${playlist.items.length} demos)`);
693
+ }
694
+ attractPlaylist = { ...playlist, _playlistPath: playlistPath };
695
+ await loadAttractEntry(demoIndex, 0, { rebootBeforeLoad: true });
696
+ }
697
+
698
+ function startAttractModeIfRoomEmpty(reason = 'empty-room') {
699
+ if (!attractEnabled || attractStatus.active || hostClient || p2Client) {
700
+ logEv('attract-empty-room-start-skipped', {
701
+ reason,
702
+ attractEnabled,
703
+ active: !!attractStatus.active,
704
+ hasHost: !!hostClient,
705
+ hasP2: !!p2Client,
706
+ });
707
+ return;
708
+ }
709
+ clearEmptyRoomAttractTimer();
710
+ logEv('attract-empty-room-start', { reason });
711
+ startAttractMode().catch((err) => {
712
+ console.error(`[input-server] attract mode ${reason} start failed:`, err?.message ?? err);
713
+ stopAttractMode({ reason: 'error' });
714
+ });
715
+ }
716
+
717
+ function scheduleAttractModeIfRoomEmpty(reason = 'empty-room') {
718
+ clearEmptyRoomAttractTimer();
719
+ if (!attractEnabled || attractStatus.active || hostClient || p2Client) {
720
+ logEv('attract-empty-room-schedule-skipped', {
721
+ reason,
722
+ attractEnabled,
723
+ active: !!attractStatus.active,
724
+ hasHost: !!hostClient,
725
+ hasP2: !!p2Client,
726
+ });
727
+ return;
728
+ }
729
+ logEv('attract-empty-room-scheduled', { reason, delayMs: HOST_TIMEOUT });
730
+ emptyRoomAttractTimer = setTimeout(() => {
731
+ emptyRoomAttractTimer = null;
732
+ startAttractModeIfRoomEmpty(reason);
733
+ }, HOST_TIMEOUT);
734
+ if (typeof emptyRoomAttractTimer.unref === 'function') emptyRoomAttractTimer.unref();
735
+ }
736
+
737
+ async function advanceAttractMode() {
738
+ const generation = attractGeneration;
739
+ if (!attractStatus.active || !attractPlaylist || !attractCursor) return;
740
+ const item = getAttractItem(attractCursor.itemIndex);
741
+ const nextFileIndex = attractCursor.fileIndex + 1;
742
+ if (nextFileIndex < item.files.length) {
743
+ if (generation !== attractGeneration) return;
744
+ await loadAttractEntry(attractCursor.itemIndex, nextFileIndex, { mountOnly: true });
745
+ return;
746
+ }
747
+ const nextItemIndex = (attractCursor.itemIndex + 1) % attractPlaylist.items.length;
748
+ if (generation !== attractGeneration) return;
749
+ await loadAttractEntry(nextItemIndex, 0, { rebootBeforeLoad: true });
750
+ }
751
+
374
752
  let clientCount = 0;
375
753
  const clientMeta = new Map(); // Map<WebSocket, { addr: string, role: string, username: string|null, sessionId: string|null }>
376
754
 
@@ -380,7 +758,9 @@ export function createInputServer(opts = {}) {
380
758
  }
381
759
 
382
760
  function normalizeUsername(value) {
383
- const username = String(value ?? '').trim().toLowerCase();
761
+ const username = String(value ?? '')
762
+ .trim()
763
+ .toLowerCase();
384
764
  return username || null;
385
765
  }
386
766
 
@@ -421,7 +801,8 @@ export function createInputServer(opts = {}) {
421
801
  }
422
802
 
423
803
  function handleInputTransportMessage({ msg, role, respond = null } = {}) {
424
- if (!msg || (msg.type !== 'joystick' && msg.type !== 'key' && msg.type !== 'ping')) return false;
804
+ if (!msg || (msg.type !== 'joystick' && msg.type !== 'key' && msg.type !== 'ping'))
805
+ return false;
425
806
 
426
807
  if (msg.type === 'ping') {
427
808
  const now = Date.now();
@@ -463,9 +844,7 @@ export function createInputServer(opts = {}) {
463
844
  const hostLabel = hostAvg != null ? `${hostAvg}` : '--';
464
845
  const p2Label = p2Avg != null ? `${p2Avg}` : '--';
465
846
  if (logEvents || verbose) {
466
- console.error(
467
- `[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`,
468
- );
847
+ console.error(`[event] input-latency host-avg=${hostLabel}ms p2-avg=${p2Label}ms`);
469
848
  }
470
849
  _networkStats.host.avgLatency = hostAvg;
471
850
  _networkStats.p2.avgLatency = p2Avg;
@@ -519,7 +898,13 @@ export function createInputServer(opts = {}) {
519
898
  function handlePeerDataMessage({ addr = null, sessionId = null, msg, send = null } = {}) {
520
899
  const identity = getRoleByPeer({ addr, sessionId });
521
900
  if (!identity || (identity.role !== 'host' && identity.role !== 'p2')) return false;
522
- return handleInputTransportMessage({ msg, role: identity.role, respond: send, isWebSocket: false, ws: identity.ws });
901
+ return handleInputTransportMessage({
902
+ msg,
903
+ role: identity.role,
904
+ respond: send,
905
+ isWebSocket: false,
906
+ ws: identity.ws,
907
+ });
523
908
  }
524
909
 
525
910
  function getWebrtcPeerCountByAddr() {
@@ -549,7 +934,11 @@ export function createInputServer(opts = {}) {
549
934
  const hostMeta = hostClient ? clientMeta.get(hostClient) : null;
550
935
  const p2Meta = p2Client ? clientMeta.get(p2Client) : null;
551
936
  const spectators = [];
552
- const { snapshot: webrtcSnapshot, byAddr: webrtcByAddr, bySession: webrtcBySession } = getWebrtcPeerCountByAddr();
937
+ const {
938
+ snapshot: webrtcSnapshot,
939
+ byAddr: webrtcByAddr,
940
+ bySession: webrtcBySession,
941
+ } = getWebrtcPeerCountByAddr();
553
942
  const matchedPeerSlots = new Set();
554
943
  const webrtcPeers = Array.isArray(webrtcSnapshot?.peers) ? webrtcSnapshot.peers : [];
555
944
 
@@ -630,6 +1019,7 @@ export function createInputServer(opts = {}) {
630
1019
  },
631
1020
  webrtc: webrtcSnapshot,
632
1021
  runtime: getRuntimeStats?.() ?? null,
1022
+ attractMode: attractStatusPayload(),
633
1023
  sampledAt: Date.now(),
634
1024
  };
635
1025
  }
@@ -640,6 +1030,12 @@ export function createInputServer(opts = {}) {
640
1030
  // Start input flood logging
641
1031
  _startInputLog();
642
1032
  _startNetworkStatsTicker();
1033
+ if (attractEnabled && attractConfig.autostart) {
1034
+ startAttractMode().catch((err) => {
1035
+ console.error('[input-server] attract mode autostart failed:', err?.message ?? err);
1036
+ stopAttractMode({ reason: 'error' });
1037
+ });
1038
+ }
643
1039
  });
644
1040
 
645
1041
  wss.on('connection', (ws, req) => {
@@ -706,6 +1102,7 @@ export function createInputServer(opts = {}) {
706
1102
  }
707
1103
  const isRejoin = graceTimer && pendingHostUsername === (msg.username ?? 'player');
708
1104
  if (graceTimer) clearGrace(); // cancel grace regardless of who's claiming
1105
+ clearEmptyRoomAttractTimer();
709
1106
  hostClient = ws;
710
1107
  hostUsername = msg.username ?? 'player';
711
1108
  setWsIdentity(ws, 'host', hostUsername);
@@ -811,6 +1208,7 @@ export function createInputServer(opts = {}) {
811
1208
  ws.send(JSON.stringify({ type: 'player2-left', username: leaving, voluntary: true }));
812
1209
  broadcastExcept(ws, { type: 'player2-left', username: leaving, voluntary: true });
813
1210
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
1211
+ scheduleAttractModeIfRoomEmpty('p2-voluntary');
814
1212
  }
815
1213
  return;
816
1214
  }
@@ -834,6 +1232,7 @@ export function createInputServer(opts = {}) {
834
1232
  ws.send(JSON.stringify({ type: 'host-left', username: leaving, voluntary: true }));
835
1233
  broadcastExcept(ws, { type: 'host-left', username: leaving, voluntary: true });
836
1234
  broadcastAll({ type: 'p2-slot-status', open: false });
1235
+ scheduleAttractModeIfRoomEmpty('host-voluntary');
837
1236
  }
838
1237
  return;
839
1238
  }
@@ -877,6 +1276,7 @@ export function createInputServer(opts = {}) {
877
1276
  return;
878
1277
  }
879
1278
  if (isRejoin) clearP2Grace();
1279
+ clearEmptyRoomAttractTimer();
880
1280
  if (ws === hostClient) {
881
1281
  ws.send(JSON.stringify({ type: 'join-p2-error', reason: 'already-host' }));
882
1282
  return;
@@ -939,6 +1339,7 @@ export function createInputServer(opts = {}) {
939
1339
  return;
940
1340
  }
941
1341
  if (isRejoin) clearP2Grace();
1342
+ clearEmptyRoomAttractTimer();
942
1343
  p2Client = ws;
943
1344
  p2Username = requestedUsername;
944
1345
  inviteToken = null;
@@ -994,6 +1395,7 @@ export function createInputServer(opts = {}) {
994
1395
  broadcastAll({ type: 'p2-slot-status', open: isP2SlotOpen() });
995
1396
  if (verbose) console.error(`[input-server] p2 revoked by host`);
996
1397
  logEv('p2-kicked', { username: leaving ?? '?', by: 'host' });
1398
+ scheduleAttractModeIfRoomEmpty('p2-revoked');
997
1399
  return;
998
1400
  }
999
1401
 
@@ -1088,7 +1490,11 @@ export function createInputServer(opts = {}) {
1088
1490
  const active = role === 'host' ? !!hostClient : !!p2Client;
1089
1491
  if (!active) {
1090
1492
  ws.send(
1091
- JSON.stringify({ type: 'admin-error', command: 'activity', reason: 'role-not-present' }),
1493
+ JSON.stringify({
1494
+ type: 'admin-error',
1495
+ command: 'activity',
1496
+ reason: 'role-not-present',
1497
+ }),
1092
1498
  );
1093
1499
  return;
1094
1500
  }
@@ -1103,6 +1509,35 @@ export function createInputServer(opts = {}) {
1103
1509
  return;
1104
1510
  }
1105
1511
 
1512
+ if (msg.type === 'admin-attract-mode') {
1513
+ const valid = validateAdminToken(msg.token ?? '');
1514
+ if (!valid) {
1515
+ ws.send(
1516
+ JSON.stringify({ type: 'admin-error', command: 'attract-mode', reason: 'invalid-token' }),
1517
+ );
1518
+ return;
1519
+ }
1520
+ setWsIdentity(ws, 'admin', null);
1521
+ const action = String(msg.action ?? '').toLowerCase();
1522
+ const demoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1523
+ if (action === 'on') {
1524
+ startAttractMode(demoIndex)
1525
+ .then(() => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ type: 'admin-attract-mode-ok', action, attractMode: attractStatusPayload() })))
1526
+ .catch((e) => {
1527
+ stopAttractMode({ reason: 'error' });
1528
+ if (ws.readyState === ws.OPEN) {
1529
+ ws.send(JSON.stringify({ type: 'admin-error', command: 'attract-mode', reason: String(e?.message ?? e) }));
1530
+ }
1531
+ });
1532
+ return;
1533
+ }
1534
+ if (action === 'off') {
1535
+ stopAttractMode({ reason: 'admin' });
1536
+ ws.send(JSON.stringify({ type: 'admin-attract-mode-ok', action, attractMode: attractStatusPayload() }));
1537
+ }
1538
+ return;
1539
+ }
1540
+
1106
1541
  if (msg.type === 'admin-kick-all') {
1107
1542
  const valid = validateAdminToken(msg.token ?? '');
1108
1543
  if (!valid) {
@@ -1170,6 +1605,47 @@ export function createInputServer(opts = {}) {
1170
1605
  }
1171
1606
 
1172
1607
  // ── Emulator commands (host only) ─────────────────────────────────────
1608
+ if (msg.type === 'attract-mode') {
1609
+ if (ws !== hostClient) {
1610
+ logEv('attract-mode-rejected', { reason: 'host-required' });
1611
+ if (ws.readyState === ws.OPEN) {
1612
+ ws.send(JSON.stringify({ type: 'attract-mode-error', reason: 'host-required' }));
1613
+ }
1614
+ return;
1615
+ }
1616
+ const action = String(msg.action ?? '').toLowerCase();
1617
+ const demoIndex = msg.demoIndex != null ? Number(msg.demoIndex) : undefined;
1618
+ logEv('cmd-attract-mode', { action, host: hostUsername ?? '-', demoIndex: demoIndex ?? '-' });
1619
+ if (action === 'on') {
1620
+ startAttractMode(demoIndex)
1621
+ .then(() => {
1622
+ if (ws.readyState === ws.OPEN) {
1623
+ ws.send(JSON.stringify({ type: 'attract-mode-ok', action, attractMode: attractStatusPayload() }));
1624
+ }
1625
+ })
1626
+ .catch((e) => {
1627
+ const reason = String(e?.message ?? e);
1628
+ logEv('attract-mode-error', { action, reason });
1629
+ stopAttractMode({ reason: 'error' });
1630
+ if (ws.readyState === ws.OPEN) {
1631
+ ws.send(JSON.stringify({ type: 'attract-mode-error', action, reason }));
1632
+ }
1633
+ });
1634
+ return;
1635
+ }
1636
+ if (action === 'off') {
1637
+ stopAttractMode({ reason: 'manual' });
1638
+ if (ws.readyState === ws.OPEN) {
1639
+ ws.send(JSON.stringify({ type: 'attract-mode-ok', action, attractMode: attractStatusPayload() }));
1640
+ }
1641
+ return;
1642
+ }
1643
+ if (ws.readyState === ws.OPEN) {
1644
+ ws.send(JSON.stringify({ type: 'attract-mode-error', action, reason: 'invalid-action' }));
1645
+ }
1646
+ return;
1647
+ }
1648
+
1173
1649
  if (msg.type === 'load-file') {
1174
1650
  if (ws !== hostClient) return;
1175
1651
  const loadFilename = msg.filename ?? '';
@@ -1179,32 +1655,16 @@ export function createInputServer(opts = {}) {
1179
1655
  logEv('cmd-load-file', {
1180
1656
  filename: loadFilename || '?',
1181
1657
  fileType,
1658
+ autoLoadDisk: msg.autoLoadDisk ?? '-',
1182
1659
  dataLen: (msg.data ?? '').length,
1183
1660
  });
1184
- broadcastAll({ type: 'cart-loading', filename: loadFilename });
1185
- Promise.resolve()
1186
- .then(() =>
1187
- onCommand({
1188
- type: 'load-file',
1189
- filename: loadFilename,
1190
- fileType,
1191
- data: msg.data ?? '',
1192
- }),
1193
- )
1194
- .then(() => {
1195
- currentCartFilename = loadFilename || null;
1196
- broadcastAll({ type: 'cart-loaded', filename: loadFilename });
1197
- })
1198
- .catch((e) => {
1199
- broadcastAll({ type: 'cart-load-error', reason: String(e?.message ?? e) });
1200
- if (verbose) console.error('[input-server] load-file error:', e);
1201
- logEv('error', {
1202
- kind: 'load-file-failed',
1203
- filename: loadFilename,
1204
- fileType,
1205
- err: String(e?.message ?? e),
1206
- });
1207
- });
1661
+ if (attractStatus.active) stopAttractMode({ reason: 'manual-load' });
1662
+ runLoadFileCommand({
1663
+ filename: loadFilename,
1664
+ fileType,
1665
+ autoLoadDisk: msg.autoLoadDisk,
1666
+ data: msg.data ?? '',
1667
+ }).catch(() => {});
1208
1668
  return;
1209
1669
  }
1210
1670
 
@@ -1213,29 +1673,12 @@ export function createInputServer(opts = {}) {
1213
1673
  if (verbose) console.error(`[input-server] load-crt: ${msg.filename ?? '?'}`);
1214
1674
  logEv('cmd-load-crt', { filename: msg.filename ?? '?', dataLen: (msg.data ?? '').length });
1215
1675
  const loadFilename = msg.filename ?? '';
1216
- broadcastAll({ type: 'cart-loading', filename: loadFilename });
1217
- Promise.resolve()
1218
- .then(() =>
1219
- onCommand({
1220
- type: 'load-file',
1221
- filename: loadFilename,
1222
- fileType: 'crt',
1223
- data: msg.data ?? '',
1224
- }),
1225
- )
1226
- .then(() => {
1227
- currentCartFilename = loadFilename || null;
1228
- broadcastAll({ type: 'cart-loaded', filename: loadFilename });
1229
- })
1230
- .catch((e) => {
1231
- broadcastAll({ type: 'cart-load-error', reason: String(e?.message ?? e) });
1232
- if (verbose) console.error('[input-server] load-crt error:', e);
1233
- logEv('error', {
1234
- kind: 'load-crt-failed',
1235
- filename: loadFilename,
1236
- err: String(e?.message ?? e),
1237
- });
1238
- });
1676
+ if (attractStatus.active) stopAttractMode({ reason: 'manual-load' });
1677
+ runLoadFileCommand({
1678
+ filename: loadFilename,
1679
+ fileType: 'crt',
1680
+ data: msg.data ?? '',
1681
+ }).catch(() => {});
1239
1682
  return;
1240
1683
  }
1241
1684
 
@@ -1260,11 +1703,9 @@ export function createInputServer(opts = {}) {
1260
1703
  if (ws !== hostClient) return;
1261
1704
  if (verbose) console.error('[input-server] hard-reset');
1262
1705
  logEv('cmd-hard-reset', { host: hostUsername });
1706
+ stopAttractMode({ reason: 'manual-reset' });
1263
1707
  Promise.resolve()
1264
- .then(() => onCommand({ type: 'hard-reset' }))
1265
- .then(() => {
1266
- broadcastAll({ type: 'machine-reset' });
1267
- })
1708
+ .then(() => runHardResetCommand())
1268
1709
  .catch((e) => {
1269
1710
  if (verbose) console.error('[input-server] hard-reset error:', e);
1270
1711
  logEv('error', { kind: 'hard-reset-failed', err: String(e?.message ?? e) });
@@ -1277,11 +1718,7 @@ export function createInputServer(opts = {}) {
1277
1718
  if (verbose) console.error('[input-server] reboot');
1278
1719
  logEv('cmd-reboot', { host: hostUsername });
1279
1720
  Promise.resolve()
1280
- .then(() => onCommand({ type: 'reboot' }))
1281
- .then(() => {
1282
- currentCartFilename = null;
1283
- broadcastAll({ type: 'machine-rebooted' });
1284
- })
1721
+ .then(() => runRebootCommand())
1285
1722
  .catch((e) => {
1286
1723
  if (verbose) console.error('[input-server] reboot error:', e);
1287
1724
  logEv('error', { kind: 'reboot-failed', err: String(e?.message ?? e) });
@@ -1307,7 +1744,9 @@ export function createInputServer(opts = {}) {
1307
1744
  })
1308
1745
  .catch((e) => {
1309
1746
  if (ws.readyState === ws.OPEN) {
1310
- ws.send(JSON.stringify({ type: 'snapshot-save-error', reason: String(e?.message ?? e) }));
1747
+ ws.send(
1748
+ JSON.stringify({ type: 'snapshot-save-error', reason: String(e?.message ?? e) }),
1749
+ );
1311
1750
  }
1312
1751
  if (verbose) console.error('[input-server] save-snapshot error:', e);
1313
1752
  logEv('error', { kind: 'save-snapshot-failed', err: String(e?.message ?? e) });
@@ -1407,6 +1846,7 @@ export function createInputServer(opts = {}) {
1407
1846
  effectiveHostPort: hostPort(),
1408
1847
  effectiveP2Port: p2Port(),
1409
1848
  },
1849
+ attractMode: attractStatusPayload(),
1410
1850
  ...(currentCartFilename ? { cartFilename: currentCartFilename } : {}),
1411
1851
  joystickBitmask: { up: 0x1, down: 0x2, left: 0x4, right: 0x8, fire: 0x10 },
1412
1852
  ...(serverVersion ? { serverVersion } : {}),
@@ -1426,6 +1866,8 @@ export function createInputServer(opts = {}) {
1426
1866
  clearP2Timeout();
1427
1867
  clearGrace();
1428
1868
  clearP2Grace();
1869
+ clearAttractTimer();
1870
+ clearEmptyRoomAttractTimer();
1429
1871
  if (_inputLogTimer) {
1430
1872
  clearInterval(_inputLogTimer);
1431
1873
  _inputLogTimer = null;
@@ -1439,7 +1881,9 @@ export function createInputServer(opts = {}) {
1439
1881
  _networkStatsTimer = null;
1440
1882
  }
1441
1883
  for (const client of wss.clients) {
1442
- try { client.terminate(); } catch (_) {}
1884
+ try {
1885
+ client.terminate();
1886
+ } catch (_) {}
1443
1887
  }
1444
1888
  wss.close(() => resolve());
1445
1889
  });