c64-ready 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +70 -62
  2. package/bin/headless.mjs +1 -1
  3. package/dist/assets/CHANGELOG-0a7A8Ekq.js +391 -0
  4. package/dist/assets/index-BESofQoh.js +627 -0
  5. package/dist/games/cartridges/goat-beat.crt +0 -0
  6. package/dist/index.html +1 -1
  7. package/dist-ts/emulator/c64-emulator.d.ts +7 -0
  8. package/dist-ts/emulator/c64-emulator.d.ts.map +1 -1
  9. package/dist-ts/emulator/c64-emulator.js +50 -6
  10. package/dist-ts/emulator/c64-emulator.js.map +1 -1
  11. package/dist-ts/emulator/constants.d.ts +3 -1
  12. package/dist-ts/emulator/constants.d.ts.map +1 -1
  13. package/dist-ts/emulator/constants.js +2 -0
  14. package/dist-ts/emulator/constants.js.map +1 -1
  15. package/dist-ts/emulator/input.d.ts +21 -1
  16. package/dist-ts/emulator/input.d.ts.map +1 -1
  17. package/dist-ts/emulator/input.js +295 -10
  18. package/dist-ts/emulator/input.js.map +1 -1
  19. package/dist-ts/types/emulator.d.ts +1 -1
  20. package/dist-ts/types/emulator.d.ts.map +1 -1
  21. package/package.json +1 -1
  22. package/public/games/cartridges/goat-beat.crt +0 -0
  23. package/src/emulator/c64-emulator.ts +6 -5
  24. package/src/emulator/constants.ts +5 -1
  25. package/src/emulator/input.ts +331 -19
  26. package/src/headless/headless-cli.mjs +73 -37
  27. package/src/headless/input-server.mjs +276 -102
  28. package/src/headless/webrtc-server.mjs +123 -12
  29. package/src/main.ts +12 -0
  30. package/src/player/c64-player.ts +21 -6
  31. package/src/player/input-handler.ts +8 -0
  32. package/src/player/styles/ui-controller.css +13 -0
  33. package/src/player/ui-controller.ts +128 -12
  34. package/src/types/emulator.ts +1 -1
  35. package/dist/assets/CHANGELOG-B12WeYEc.js +0 -116
  36. package/dist/assets/index-fUdEY2R7.js +0 -610
@@ -1,5 +1,12 @@
1
1
  import type { C64Emulator } from './c64-emulator';
2
- import { JOYSTICK_DIRECTION, JOYSTICK_FIRE_1, JOYSTICK_PORT_2 } from './constants';
2
+ import {
3
+ JOYSTICK_DIRECTION,
4
+ JOYSTICK_FIRE_1,
5
+ JOYSTICK_FIRE_2,
6
+ JOYSTICK_FIRE_3,
7
+ JOYSTICK_PORT_2,
8
+ type JoystickInput,
9
+ } from './constants';
3
10
  import type { JoystickPort } from './constants';
4
11
 
5
12
  export const KEY_TO_JOYSTICK = {
@@ -39,6 +46,8 @@ export const MIXED_JOYSTICK_KEYS: Record<string, number> = {
39
46
  ArrowLeft: JOYSTICK_DIRECTION.LEFT,
40
47
  ArrowRight: JOYSTICK_DIRECTION.RIGHT,
41
48
  KeyZ: JOYSTICK_FIRE_1,
49
+ KeyX: JOYSTICK_FIRE_2,
50
+ KeyC: JOYSTICK_FIRE_3,
42
51
  ControlLeft: JOYSTICK_FIRE_1,
43
52
  };
44
53
 
@@ -474,18 +483,31 @@ export function domKeyToC64Actions(
474
483
  default:
475
484
  break;
476
485
  }
477
-
478
486
  return actions;
479
487
  }
480
488
 
481
489
  type MappedControl = keyof typeof KEY_TO_JOYSTICK;
482
490
 
491
+ const POT_INACTIVE = 128;
492
+ const POT_ACTIVE = 0;
493
+
483
494
  export class EmulatorInput {
484
495
  private readonly emulator: C64Emulator;
485
496
  private readonly target: EventTarget;
486
497
  // Which joystick port keyboard events map to (1 or 2). Default is port 2.
487
- private keyboardJoystickPort: JoystickPort;
498
+ private joystickPort: JoystickPort;
488
499
  private inputMode: InputMode = 'mixed';
500
+ private updateFrame: number = -1;
501
+ private gamepadIndex: number = -1;
502
+ private gamepadPresses: Array<boolean> = [];
503
+ /**
504
+ * Ultimate 8bitdo axes:
505
+ * [LeftX, LeftX, LeftUp, LeftDown, L2, RightX, RightX, RightUp, RightDown, R2, DpadX, DpadX, DpadY, DpadY]
506
+ **/
507
+ private gamepadAxes: Array<boolean> =
508
+ [false, false, false, false, false, false, false, false, false, false, false, false, false, false];
509
+ private potFire2Pressed = false;
510
+ private potFire3Pressed = false;
489
511
  private readonly pressedControls = new Set<MappedControl>();
490
512
  private readonly keyDownHandler = (event: KeyboardEvent): void => {
491
513
  this.handleKeyDown(event);
@@ -493,6 +515,12 @@ export class EmulatorInput {
493
515
  private readonly keyUpHandler = (event: KeyboardEvent): void => {
494
516
  this.handleKeyUp(event);
495
517
  };
518
+ private readonly gamepadConnectedHandler = (event: Event): void => {
519
+ this.handleGamepadConnected(event as GamepadEvent);
520
+ };
521
+ private readonly gamepadDisconnectedHandler = (event: Event): void => {
522
+ this.handleGamepadDisconnected(event as GamepadEvent);
523
+ };
496
524
 
497
525
  constructor(
498
526
  emulator: C64Emulator,
@@ -501,18 +529,240 @@ export class EmulatorInput {
501
529
  ) {
502
530
  this.emulator = emulator;
503
531
  this.target = target;
504
- this.keyboardJoystickPort = defaultPort;
532
+ this.joystickPort = defaultPort;
505
533
  }
506
534
 
507
535
  attach(): void {
536
+ this.target.addEventListener('gamepadconnected', this.gamepadConnectedHandler as EventListener);
537
+ this.target.addEventListener(
538
+ 'gamepaddisconnected',
539
+ this.gamepadDisconnectedHandler as EventListener,
540
+ );
508
541
  this.target.addEventListener('keydown', this.keyDownHandler as EventListener);
509
542
  this.target.addEventListener('keyup', this.keyUpHandler as EventListener);
510
543
  }
511
544
 
512
545
  detach(): void {
546
+ this.target.removeEventListener(
547
+ 'gamepadconnected',
548
+ this.gamepadConnectedHandler as EventListener,
549
+ );
550
+ this.target.removeEventListener(
551
+ 'gamepaddisconnected',
552
+ this.gamepadDisconnectedHandler as EventListener,
553
+ );
513
554
  this.target.removeEventListener('keydown', this.keyDownHandler as EventListener);
514
555
  this.target.removeEventListener('keyup', this.keyUpHandler as EventListener);
515
556
  this.releaseAll();
557
+ this.releaseAllGamepadButtons();
558
+ this.cancelUpdate();
559
+ }
560
+
561
+ private step(): void {
562
+ const gamepads = navigator.getGamepads();
563
+ if (!gamepads) {
564
+ return;
565
+ }
566
+ const gp = gamepads[this.gamepadIndex];
567
+ if (!gp) {
568
+ this.cancelUpdate();
569
+ return;
570
+ }
571
+ if (gp.buttons) {
572
+ for (let b = 0; b < gp.buttons.length; b++) {
573
+ if (gp.buttons[b].pressed) {
574
+ this.gamepadPresses[b] = true;
575
+ console.log('Buttons Pressed', b, gp.buttons[b]);
576
+ switch (b) {
577
+ case 0:
578
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_FIRE_1);
579
+ break;
580
+ case 1:
581
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
582
+ break;
583
+ case 2:
584
+ this.emulator.keyDown(C64_KEY.SPACE);
585
+ break;
586
+ case 3:
587
+ //this.pushJoystickInput(JOYSTICK_FIRE_3);
588
+ break;
589
+ case 7:
590
+ case 9:
591
+ this.emulator.keyDown(C64_KEY.RUN_STOP);
592
+ break;
593
+ case 14:
594
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
595
+ break;
596
+ case 15:
597
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
598
+ break;
599
+ case 12:
600
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
601
+ break;
602
+ case 13:
603
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
604
+ break;
605
+ }
606
+ // this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
607
+ } else if (!gp.buttons[b].pressed && this.gamepadPresses[b] === true) {
608
+ this.gamepadPresses[b] = false;
609
+ switch (b) {
610
+ case 0:
611
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_FIRE_1);
612
+ break;
613
+ case 1:
614
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
615
+ break;
616
+ case 2:
617
+ this.emulator.keyUp(C64_KEY.SPACE);
618
+ //this.releaseJoystickInput(JOYSTICK_FIRE_2);
619
+ break;
620
+ case 3:
621
+ //this.releaseJoystickInput(JOYSTICK_FIRE_3);
622
+ break;
623
+ case 7:
624
+ case 9:
625
+ this.emulator.keyUp(C64_KEY.RUN_STOP);
626
+ break;
627
+ case 14:
628
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
629
+ break;
630
+ case 15:
631
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
632
+ break;
633
+ case 12:
634
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
635
+ break;
636
+ case 13:
637
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
638
+ break;
639
+ }
640
+ // this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
641
+ }
642
+ }
643
+ }
644
+
645
+ if (gp.axes[0] <= -0.5 || gp.axes[6] <= -0.5) {
646
+ this.gamepadAxes[0] = true;
647
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
648
+ } else if (this.gamepadAxes[0] === true) {
649
+ this.gamepadAxes[0] = false;
650
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
651
+ }
652
+
653
+ if (gp.axes[0] >= 0.5 || gp.axes[6] >= 0.5) {
654
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
655
+ this.gamepadAxes[1] = true;
656
+ } else if (this.gamepadAxes[1] === true) {
657
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
658
+ this.gamepadAxes[1] = false;
659
+ }
660
+
661
+ if (gp.axes[1] <= -0.5 || gp.axes[7] <= -0.5) {
662
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
663
+ this.gamepadAxes[2] = true;
664
+ } else if (this.gamepadAxes[2] === true) {
665
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
666
+ this.gamepadAxes[2] = false;
667
+ }
668
+
669
+ if (gp.axes[1] >= 0.5 || gp.axes[7] >= 0.5) {
670
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
671
+ this.gamepadAxes[3] = true;
672
+ } else if (this.gamepadAxes[3] === true) {
673
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
674
+ this.gamepadAxes[3] = false;
675
+ }
676
+
677
+ this.updateFrame = requestAnimationFrame(this.step.bind(this));
678
+ }
679
+
680
+ private cancelUpdate(): void {
681
+ cancelAnimationFrame(this.updateFrame);
682
+ this.updateFrame = -1;
683
+ this.gamepadIndex = -1;
684
+ }
685
+
686
+ private releaseAllGamepadButtons(): void {
687
+ if (!this.gamepadPresses.some(Boolean)) return;
688
+
689
+ const buttonToInput: Partial<Record<number, JoystickInput>> = {
690
+ 0: JOYSTICK_FIRE_1,
691
+ 2: JOYSTICK_FIRE_2,
692
+ 3: JOYSTICK_FIRE_3,
693
+ 12: JOYSTICK_DIRECTION.UP,
694
+ 13: JOYSTICK_DIRECTION.DOWN,
695
+ 14: JOYSTICK_DIRECTION.LEFT,
696
+ 15: JOYSTICK_DIRECTION.RIGHT,
697
+ };
698
+
699
+ for (const [button, input] of Object.entries(buttonToInput)) {
700
+ if (!input) continue;
701
+ if (this.gamepadPresses[Number(button)] === true) {
702
+ this.releaseJoystickInput(input);
703
+ }
704
+ }
705
+
706
+ this.gamepadPresses = [];
707
+ }
708
+
709
+ private findConnectedGamepadIndex(excludeIndex?: number): number {
710
+ const gamepads = navigator.getGamepads?.() ?? [];
711
+ for (const gamepad of gamepads) {
712
+ if (!gamepad) continue;
713
+ if (gamepad.index === excludeIndex) continue;
714
+ return gamepad.index;
715
+ }
716
+ return -1;
717
+ }
718
+
719
+ private handleGamepadDisconnected(event: GamepadEvent): void {
720
+ console.log('Gamepad disconnected from index %d: %s', event.gamepad.index, event.gamepad.id);
721
+ const wasActive = this.gamepadIndex === event.gamepad.index;
722
+ if (wasActive) {
723
+ this.releaseAllGamepadButtons();
724
+ const fallbackIndex = this.findConnectedGamepadIndex(event.gamepad.index);
725
+ if (fallbackIndex >= 0) {
726
+ this.gamepadIndex = fallbackIndex;
727
+ if (this.updateFrame < 0) {
728
+ this.step();
729
+ }
730
+ } else {
731
+ this.cancelUpdate();
732
+ }
733
+ }
734
+
735
+ const gamepadDisconnected = new CustomEvent('c64-controller-disconnected', {
736
+ detail: {
737
+ name: event.gamepad.id,
738
+ index: event.gamepad.index,
739
+ },
740
+ });
741
+ this.target.dispatchEvent(gamepadDisconnected);
742
+ }
743
+
744
+ private handleGamepadConnected(event: GamepadEvent): void {
745
+ console.log(
746
+ 'Gamepad connected at index %d: %s. %d buttons, %d axes.',
747
+ event.gamepad.index,
748
+ event.gamepad.id,
749
+ event.gamepad.buttons.length,
750
+ event.gamepad.axes.length,
751
+ );
752
+ if (this.gamepadIndex < 0) {
753
+ this.gamepadIndex = event.gamepad.index;
754
+ }
755
+ const gamepadConnected = new CustomEvent('c64-controller-connected', {
756
+ detail: {
757
+ name: event.gamepad.id,
758
+ index: event.gamepad.index,
759
+ },
760
+ });
761
+
762
+ this.target.dispatchEvent(gamepadConnected);
763
+ if (this.updateFrame < 0) {
764
+ this.step();
765
+ }
516
766
  }
517
767
 
518
768
  private handleKeyDown(event: KeyboardEvent): void {
@@ -534,11 +784,8 @@ export class EmulatorInput {
534
784
  // all other keys route to the C64 keyboard matrix.
535
785
  if (event.code in MIXED_JOYSTICK_KEYS) {
536
786
  // Joystick path
537
- const dir = MIXED_JOYSTICK_KEYS[event.code];
538
- this.emulator.joystickPush(
539
- this.keyboardJoystickPort,
540
- dir as import('./constants').JoystickInput,
541
- );
787
+ const dir = MIXED_JOYSTICK_KEYS[event.code] as JoystickInput;
788
+ this.pushJoystickInput(dir);
542
789
  event.preventDefault();
543
790
  } else {
544
791
  // Keyboard path — but exclude the joystick codes from matrix so
@@ -561,7 +808,7 @@ export class EmulatorInput {
561
808
  return;
562
809
  }
563
810
  this.pressedControls.add(control);
564
- this.emulator.joystickPush(this.keyboardJoystickPort, KEY_TO_JOYSTICK[control]);
811
+ this.pushJoystickInput(KEY_TO_JOYSTICK[control]);
565
812
  event.preventDefault();
566
813
  }
567
814
 
@@ -581,10 +828,7 @@ export class EmulatorInput {
581
828
  if (this.inputMode === 'mixed') {
582
829
  if (event.code in MIXED_JOYSTICK_KEYS) {
583
830
  const dir = MIXED_JOYSTICK_KEYS[event.code];
584
- this.emulator.joystickRelease(
585
- this.keyboardJoystickPort,
586
- dir as import('./constants').JoystickInput,
587
- );
831
+ this.releaseJoystickInput(dir as JoystickInput);
588
832
  event.preventDefault();
589
833
  } else {
590
834
  const acts = domKeyToC64Actions(event.key, event.shiftKey, 'keyup');
@@ -605,7 +849,7 @@ export class EmulatorInput {
605
849
  return;
606
850
  }
607
851
  this.pressedControls.delete(control);
608
- this.emulator.joystickRelease(this.keyboardJoystickPort, KEY_TO_JOYSTICK[control]);
852
+ this.releaseJoystickInput(KEY_TO_JOYSTICK[control]);
609
853
  event.preventDefault();
610
854
  }
611
855
 
@@ -616,28 +860,96 @@ export class EmulatorInput {
616
860
  return null;
617
861
  }
618
862
 
619
- private releaseAll(): void {
863
+ private pushJoystickInput(input: JoystickInput): void {
864
+ if (input === JOYSTICK_FIRE_2) {
865
+ this.potFire2Pressed = true;
866
+ this.syncPotFireButtons();
867
+ return;
868
+ }
869
+ if (input === JOYSTICK_FIRE_3) {
870
+ this.potFire3Pressed = true;
871
+ this.syncPotFireButtons();
872
+ return;
873
+ }
874
+
875
+ this.emulator.joystickPush(this.joystickPort, input);
876
+ }
877
+
878
+ private releaseJoystickInput(input: JoystickInput): void {
879
+ if (input === JOYSTICK_FIRE_2) {
880
+ this.potFire2Pressed = false;
881
+ this.syncPotFireButtons();
882
+ return;
883
+ }
884
+ if (input === JOYSTICK_FIRE_3) {
885
+ this.potFire3Pressed = false;
886
+ this.syncPotFireButtons();
887
+ return;
888
+ }
889
+
890
+ this.emulator.joystickRelease(this.joystickPort, input);
891
+ }
892
+
893
+ private releaseAll(): void {
620
894
  for (const control of this.pressedControls) {
621
- this.emulator.joystickRelease(this.keyboardJoystickPort, KEY_TO_JOYSTICK[control]);
895
+ this.releaseJoystickInput(KEY_TO_JOYSTICK[control]);
622
896
  }
623
897
  this.pressedControls.clear();
898
+ this.potFire2Pressed = false;
899
+ this.potFire3Pressed = false;
900
+ this.syncPotFireButtons();
901
+ }
902
+
903
+ private syncPotFireButtons(): void {
904
+ if (!this.potFire2Pressed && !this.potFire3Pressed) {
905
+ this.emulator.setMousePortEnabled?.(this.joystickPort, false);
906
+ return;
907
+ }
908
+
909
+ this.emulator.setMousePortEnabled?.(this.joystickPort, true);
910
+ this.emulator.mousePosition?.(
911
+ this.potFire2Pressed ? POT_ACTIVE : POT_INACTIVE,
912
+ this.potFire3Pressed ? POT_ACTIVE : POT_INACTIVE,
913
+ );
624
914
  }
625
915
 
626
916
  /** Set which joystick port keyboard controls should target (1 or 2). */
627
917
  setKeyboardPort(port: JoystickPort): void {
628
- if (this.keyboardJoystickPort === port) return;
918
+ if (this.joystickPort === port) return;
629
919
  this.releaseAll();
630
- this.keyboardJoystickPort = port;
920
+ this.releaseAllGamepadButtons();
921
+ this.joystickPort = port;
631
922
  }
632
923
 
633
924
  /** Set the input mode. Releases any held joystick buttons on mode change. */
634
925
  setInputMode(mode: InputMode): void {
635
926
  if (this.inputMode === mode) return;
636
927
  this.releaseAll();
928
+ this.releaseAllGamepadButtons();
637
929
  this.inputMode = mode;
638
930
  }
639
931
 
640
932
  getInputMode(): InputMode {
641
933
  return this.inputMode;
642
934
  }
935
+
936
+ setActiveGamepadIndex(index: number): void {
937
+ if (this.gamepadIndex === index) return;
938
+
939
+ const gamepads = navigator.getGamepads?.() ?? [];
940
+ const nextGamepad = gamepads[index];
941
+ if (!nextGamepad) {
942
+ throw new Error(`Gamepad ${index} is not connected`);
943
+ }
944
+
945
+ this.releaseAllGamepadButtons();
946
+ this.gamepadIndex = index;
947
+ if (this.updateFrame < 0) {
948
+ this.step();
949
+ }
950
+ }
951
+
952
+ getActiveGamepadIndex(): number {
953
+ return this.gamepadIndex;
954
+ }
643
955
  }
@@ -179,6 +179,11 @@ function inferLoadType(filename = '') {
179
179
  return 'crt';
180
180
  }
181
181
 
182
+ function formatSnapshotFilename(now = new Date()) {
183
+ const pad = (value) => String(value).padStart(2, '0');
184
+ return `snapshot-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.c64`;
185
+ }
186
+
182
187
  function sleepMs(ms) {
183
188
  return new Promise((resolve) => setTimeout(resolve, ms));
184
189
  }
@@ -270,7 +275,7 @@ export async function runHeadless(options = {}) {
270
275
  let webrtc = false;
271
276
  let webrtcPort = 9002;
272
277
  let logEvents = false;
273
- let maxSpectators = 3;
278
+ let maxSpectators = 10;
274
279
  let webrtcMinBitrateKbps = 200;
275
280
  let webrtcMaxBitrateKbps = 600;
276
281
  let webrtcOutputFps = 40;
@@ -630,6 +635,43 @@ export async function runHeadless(options = {}) {
630
635
  sidFrameView = sidFrameBufMax.subarray(0, 1);
631
636
  }
632
637
 
638
+ function handleInputEvent(event) {
639
+ if (!exports) return;
640
+ if (event.type === 'joystick') {
641
+ const port = (event.joystickPort ?? 2) - 1; // 1-based → 0-based
642
+ const dir = event.direction ? (dirMap[event.direction] ?? 0) : 0;
643
+ const fire = event.fire || event.fire1 ? 0x10 : 0;
644
+ if (event.action === 'release') {
645
+ if (dir) exports.c64_joystick_release(port, dir);
646
+ if (fire) exports.c64_joystick_release(port, fire);
647
+ } else {
648
+ if (dir) exports.c64_joystick_push(port, dir);
649
+ if (fire) exports.c64_joystick_push(port, fire);
650
+ }
651
+ if (verbose) {
652
+ const role = event._role ?? 'unknown';
653
+ console.error(
654
+ `[event] input joystick role=${role} port=${event.joystickPort ?? 2} action=${event.action ?? 'press'} dir=${event.direction ?? '-'} fire=${!!(event.fire || event.fire1)}`,
655
+ );
656
+ }
657
+ } else if (event.type === 'key') {
658
+ const domKey = String(event.key ?? '');
659
+ const shiftKey = !!event.shiftKey;
660
+ const evType = event.action === 'up' ? 'keyup' : 'keydown';
661
+ const c64acts = domKeyToC64Actions(domKey, shiftKey, evType);
662
+ for (const act of c64acts) {
663
+ if (act.action === 'press') exports.keyboard_keyPressed(act.key);
664
+ else exports.keyboard_keyReleased(act.key);
665
+ }
666
+ if (verbose && c64acts.length > 0) {
667
+ const role = event._role ?? 'unknown';
668
+ console.error(
669
+ `[input] input key role=${role} ${evType} "${domKey}" → ${JSON.stringify(c64acts)}`,
670
+ );
671
+ }
672
+ }
673
+ }
674
+
633
675
  inputServer = createInputServer({
634
676
  port: wsPort,
635
677
  verbose,
@@ -698,6 +740,7 @@ export async function runHeadless(options = {}) {
698
740
  exports.c64_setDriveEnabled(1);
699
741
  exports.c64_insertDisk(ptr, byteLen);
700
742
  } else if (loadType === 'snapshot') {
743
+ exports.c64_reset();
701
744
  exports.c64_loadSnapshot(ptr, byteLen);
702
745
  } else {
703
746
  throw new Error(`Unsupported load-file type: ${loadType}`);
@@ -747,6 +790,17 @@ export async function runHeadless(options = {}) {
747
790
  }
748
791
  });
749
792
  });
793
+ } else if (cmd.type === 'save-snapshot') {
794
+ const ptr = exports.c64_getSnapshot();
795
+ const byteLen = exports.c64_getSnapshotSize();
796
+ c64wasm.updateHeapViews();
797
+ heap = c64wasm.heap;
798
+ if (!heap) throw new Error('WASM heap unavailable');
799
+ const snapshot = heap.heapU8.slice(ptr, ptr + byteLen);
800
+ return {
801
+ filename: formatSnapshotFilename(),
802
+ data: Buffer.from(snapshot).toString('base64'),
803
+ };
750
804
  } else if (cmd.type === 'detach-crt') {
751
805
  const gapStart = Date.now();
752
806
  exports.c64_removeCartridge();
@@ -797,42 +851,7 @@ export async function runHeadless(options = {}) {
797
851
  else if (logEvents) console.error(`[event] machine-rebooted gap=${gapMs}ms`);
798
852
  }
799
853
  },
800
- onInput: (event) => {
801
- if (!exports) return;
802
- if (event.type === 'joystick') {
803
- const port = (event.joystickPort ?? 2) - 1; // 1-based → 0-based
804
- const dir = event.direction ? (dirMap[event.direction] ?? 0) : 0;
805
- const fire = event.fire || event.fire1 ? 0x10 : 0;
806
- if (event.action === 'release') {
807
- if (dir) exports.c64_joystick_release(port, dir);
808
- if (fire) exports.c64_joystick_release(port, fire);
809
- } else {
810
- if (dir) exports.c64_joystick_push(port, dir);
811
- if (fire) exports.c64_joystick_push(port, fire);
812
- }
813
- if (verbose) {
814
- const role = event._role ?? 'unknown';
815
- console.error(
816
- `[event] input joystick role=${role} port=${event.joystickPort ?? 2} action=${event.action ?? 'press'} dir=${event.direction ?? '-'} fire=${!!(event.fire || event.fire1)}`,
817
- );
818
- }
819
- } else if (event.type === 'key') {
820
- const domKey = String(event.key ?? '');
821
- const shiftKey = !!event.shiftKey;
822
- const evType = event.action === 'up' ? 'keyup' : 'keydown';
823
- const c64acts = domKeyToC64Actions(domKey, shiftKey, evType);
824
- for (const act of c64acts) {
825
- if (act.action === 'press') exports.keyboard_keyPressed(act.key);
826
- else exports.keyboard_keyReleased(act.key);
827
- }
828
- if (verbose && c64acts.length > 0) {
829
- const role = event._role ?? 'unknown';
830
- console.error(
831
- `[input] input key role=${role} ${evType} "${domKey}" → ${JSON.stringify(c64acts)}`,
832
- );
833
- }
834
- }
835
- },
854
+ onInput: handleInputEvent,
836
855
  });
837
856
  out.push(`Input server listening on ws://0.0.0.0:${wsPort}`);
838
857
  } catch (e) {
@@ -881,6 +900,15 @@ export async function runHeadless(options = {}) {
881
900
  },
882
901
  onPeerConnected(pc) {
883
902
  if (verbose) console.error('[webrtc] peer ICE connected');
903
+ if (webrtcServer) {
904
+ // New peers can attach mid-GOP and sit on a black frame until the
905
+ // next natural keyframe arrives. Force one on join so the decoder
906
+ // gets a decodable frame immediately.
907
+ webrtcServer.forceKeyframe(videoTrack);
908
+ setTimeout(() => {
909
+ webrtcServer?.forceKeyframe(videoTrack);
910
+ }, 300);
911
+ }
884
912
  // Reduce video sender bitrate after connection to minimise encode
885
913
  // latency. A tight ceiling keeps frame sizes small and predictable,
886
914
  // reducing the encoder's internal queue and decode buffer on the
@@ -905,6 +933,14 @@ export async function runHeadless(options = {}) {
905
933
  }
906
934
  } catch (_) {}
907
935
  },
936
+ onDataChannelInput: ({ msg, remoteAddr, sessionId, send }) => {
937
+ inputServer?.handlePeerDataMessage?.({
938
+ addr: remoteAddr,
939
+ sessionId,
940
+ msg,
941
+ send,
942
+ });
943
+ },
908
944
  });
909
945
  if (typeof webrtcServer.getTelemetrySnapshot === 'function') {
910
946
  getWebrtcTelemetry = () => webrtcServer.getTelemetrySnapshot();