c64-ready 1.0.1 → 1.1.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/dist/index.html CHANGED
@@ -29,7 +29,7 @@
29
29
  font-size: 13px;
30
30
  }
31
31
  </style>
32
- <script type="module" crossorigin src="/c64-ready/assets/index-fUdEY2R7.js"></script>
32
+ <script type="module" crossorigin src="/c64-ready/assets/index-BESofQoh.js"></script>
33
33
  </head>
34
34
  <body>
35
35
  <canvas id="c64-screen" width="384" height="272"></canvas>
package/package.json CHANGED
@@ -10,7 +10,7 @@
10
10
  "retro"
11
11
  ],
12
12
  "license": "MIT",
13
- "version": "1.0.1",
13
+ "version": "1.1.0",
14
14
  "type": "module",
15
15
  "engines": {
16
16
  "node": ">=24.14"
@@ -318,17 +318,15 @@ export class C64Emulator {
318
318
  getSnapshot(): Uint8Array {
319
319
  const x = this.wasm.exports;
320
320
  if (!x || !this.wasm.heap) throw new Error('WASM not ready');
321
+ const ptr = x.c64_getSnapshot();
321
322
  const size = x.c64_getSnapshotSize();
322
- const ptr = x.malloc(size);
323
- x.c64_getSnapshot(ptr);
324
- const snap = this.wasm.heap.heapU8.slice(ptr, ptr + size);
325
- x.free(ptr);
326
- return snap;
323
+ return this.wasm.heap.heapU8.slice(ptr, ptr + size);
327
324
  }
328
325
 
329
326
  private loadSnapshotData(ptr: number, len: number): void {
330
327
  const x = this.wasm.exports;
331
328
  if (!x) throw new Error('WASM not ready');
329
+ x.c64_reset();
332
330
  x.c64_loadSnapshot(ptr, len);
333
331
  this.frameCount = 0;
334
332
  }
@@ -1,6 +1,6 @@
1
- import type { C64Emulator } from './c64-emulator';
2
- import { JOYSTICK_DIRECTION, JOYSTICK_FIRE_1, JOYSTICK_PORT_2 } from './constants';
3
- import type { JoystickPort } from './constants';
1
+ import type {C64Emulator} from './c64-emulator';
2
+ import {JOYSTICK_DIRECTION, JOYSTICK_FIRE_1, JOYSTICK_PORT_2, type JoystickInput} from './constants'
3
+ import type {JoystickPort} from './constants';
4
4
 
5
5
  export const KEY_TO_JOYSTICK = {
6
6
  ArrowUp: JOYSTICK_DIRECTION.UP,
@@ -132,9 +132,9 @@ export function domKeyToC64Actions(
132
132
  const isDown = eventType === 'keydown';
133
133
  const actions: C64KeyAction[] = [];
134
134
 
135
- const press = (idx: number) => actions.push({ key: idx, action: 'press' });
136
- const release = (idx: number) => actions.push({ key: idx, action: 'release' });
137
- const main = (idx: number) => actions.push({ key: idx, action: isDown ? 'press' : 'release' });
135
+ const press = (idx: number) => actions.push({key: idx, action: 'press'});
136
+ const release = (idx: number) => actions.push({key: idx, action: 'release'});
137
+ const main = (idx: number) => actions.push({key: idx, action: isDown ? 'press' : 'release'});
138
138
 
139
139
  // Handle host shift state first for plain alpha/numeric keys
140
140
  if (isDown) {
@@ -474,7 +474,6 @@ export function domKeyToC64Actions(
474
474
  default:
475
475
  break;
476
476
  }
477
-
478
477
  return actions;
479
478
  }
480
479
 
@@ -484,8 +483,12 @@ export class EmulatorInput {
484
483
  private readonly emulator: C64Emulator;
485
484
  private readonly target: EventTarget;
486
485
  // Which joystick port keyboard events map to (1 or 2). Default is port 2.
487
- private keyboardJoystickPort: JoystickPort;
486
+ private joystickPort: JoystickPort;
488
487
  private inputMode: InputMode = 'mixed';
488
+ private updateFrame: number = -1;
489
+ private gamepadIndex: number = -1;
490
+ private gamepadPresses: Array<boolean> = [];
491
+ private gamepadAxes: Array<boolean> = [false, false, false, false];
489
492
  private readonly pressedControls = new Set<MappedControl>();
490
493
  private readonly keyDownHandler = (event: KeyboardEvent): void => {
491
494
  this.handleKeyDown(event);
@@ -493,6 +496,12 @@ export class EmulatorInput {
493
496
  private readonly keyUpHandler = (event: KeyboardEvent): void => {
494
497
  this.handleKeyUp(event);
495
498
  };
499
+ private readonly gamepadConnectedHandler = (event: Event): void => {
500
+ this.handleGamepadConnected(event as GamepadEvent);
501
+ };
502
+ private readonly gamepadDisconnectedHandler = (event: Event): void => {
503
+ this.handleGamepadDisconnected(event as GamepadEvent);
504
+ };
496
505
 
497
506
  constructor(
498
507
  emulator: C64Emulator,
@@ -501,18 +510,207 @@ export class EmulatorInput {
501
510
  ) {
502
511
  this.emulator = emulator;
503
512
  this.target = target;
504
- this.keyboardJoystickPort = defaultPort;
513
+ this.joystickPort = defaultPort;
505
514
  }
506
515
 
507
516
  attach(): void {
517
+ this.target.addEventListener('gamepadconnected', this.gamepadConnectedHandler as EventListener);
518
+ this.target.addEventListener('gamepaddisconnected', this.gamepadDisconnectedHandler as EventListener);
508
519
  this.target.addEventListener('keydown', this.keyDownHandler as EventListener);
509
520
  this.target.addEventListener('keyup', this.keyUpHandler as EventListener);
510
521
  }
511
522
 
512
523
  detach(): void {
524
+ this.target.removeEventListener('gamepadconnected', this.gamepadConnectedHandler as EventListener);
525
+ this.target.removeEventListener('gamepaddisconnected', this.gamepadDisconnectedHandler as EventListener);
513
526
  this.target.removeEventListener('keydown', this.keyDownHandler as EventListener);
514
527
  this.target.removeEventListener('keyup', this.keyUpHandler as EventListener);
515
528
  this.releaseAll();
529
+ this.releaseAllGamepadButtons();
530
+ this.cancelUpdate();
531
+ }
532
+
533
+ private step(): void {
534
+ const gamepads = navigator.getGamepads();
535
+ if (!gamepads) {
536
+ return;
537
+ }
538
+ const gp = gamepads[this.gamepadIndex];
539
+ if (!gp) {
540
+ this.cancelUpdate();
541
+ return;
542
+ }
543
+ if (gp.buttons) {
544
+ for (let b = 0; b < gp.buttons.length; b++) {
545
+ if (gp.buttons[b].pressed) {
546
+ this.gamepadPresses[b] = true;
547
+ // console.log('Buttons Pressed', b, gp.buttons[b]);
548
+ switch (b) {
549
+ case 0:
550
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_FIRE_1);
551
+ break;
552
+ case 14:
553
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
554
+ break;
555
+ case 15:
556
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
557
+ break;
558
+ case 12:
559
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
560
+ break;
561
+ case 13:
562
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
563
+ break;
564
+ }
565
+ // this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
566
+ } else if (!gp.buttons[b].pressed && this.gamepadPresses[b] === true) {
567
+ this.gamepadPresses[b] = false;
568
+ switch (b) {
569
+ case 0:
570
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_FIRE_1);
571
+ break;
572
+ case 14:
573
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
574
+ break;
575
+ case 15:
576
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
577
+ break;
578
+ case 12:
579
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
580
+ break;
581
+ case 13:
582
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
583
+ break;
584
+ }
585
+ // this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
586
+ }
587
+ }
588
+ }
589
+
590
+ if (gp.axes[0] <= -0.5) {
591
+ this.gamepadAxes[0] = true;
592
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
593
+ } else if (this.gamepadAxes[0] === true) {
594
+ this.gamepadAxes[0] = false;
595
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.LEFT);
596
+ }
597
+
598
+ if (gp.axes[0] >= 0.5) {
599
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
600
+ this.gamepadAxes[1] = true;
601
+ } else if (this.gamepadAxes[1] === true) {
602
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.RIGHT);
603
+ this.gamepadAxes[1] = false;
604
+
605
+ }
606
+
607
+ if (gp.axes[1] <= -0.5) {
608
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.UP);
609
+ this.gamepadAxes[2] = true
610
+ } else if (this.gamepadAxes[2] === true) {
611
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.UP);
612
+ this.gamepadAxes[2] = false
613
+ }
614
+
615
+ if (gp.axes[1] >= 0.5) {
616
+ this.emulator.joystickPush(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
617
+ this.gamepadAxes[3] = true;
618
+ } else if (this.gamepadAxes[3] === true) {
619
+ this.emulator.joystickRelease(this.joystickPort, JOYSTICK_DIRECTION.DOWN);
620
+ this.gamepadAxes[3] = false;
621
+ }
622
+
623
+ this.updateFrame = requestAnimationFrame(this.step.bind(this));
624
+ }
625
+
626
+ private cancelUpdate(): void {
627
+ cancelAnimationFrame(this.updateFrame);
628
+ this.updateFrame = -1;
629
+ this.gamepadIndex = -1;
630
+ }
631
+
632
+ private releaseAllGamepadButtons(): void {
633
+ if (!this.gamepadPresses.some(Boolean)) return;
634
+
635
+ const buttonToInput: Partial<Record<number, JoystickInput>> = {
636
+ 0: JOYSTICK_FIRE_1,
637
+ 12: JOYSTICK_DIRECTION.UP,
638
+ 13: JOYSTICK_DIRECTION.DOWN,
639
+ 14: JOYSTICK_DIRECTION.LEFT,
640
+ 15: JOYSTICK_DIRECTION.RIGHT,
641
+ };
642
+
643
+ for (const [button, input] of Object.entries(buttonToInput)) {
644
+ if (!input) continue;
645
+ if (this.gamepadPresses[Number(button)] === true) {
646
+ this.emulator.joystickRelease(this.joystickPort, input);
647
+ }
648
+ }
649
+
650
+ this.gamepadPresses = [];
651
+ }
652
+
653
+ private findConnectedGamepadIndex(excludeIndex?: number): number {
654
+ const gamepads = navigator.getGamepads?.() ?? [];
655
+ for (const gamepad of gamepads) {
656
+ if (!gamepad) continue;
657
+ if (gamepad.index === excludeIndex) continue;
658
+ return gamepad.index;
659
+ }
660
+ return -1;
661
+ }
662
+
663
+ private handleGamepadDisconnected(event: GamepadEvent): void {
664
+ console.log(
665
+ "Gamepad disconnected from index %d: %s",
666
+ event.gamepad.index,
667
+ event.gamepad.id,
668
+ );
669
+ const wasActive = this.gamepadIndex === event.gamepad.index;
670
+ if (wasActive) {
671
+ this.releaseAllGamepadButtons();
672
+ const fallbackIndex = this.findConnectedGamepadIndex(event.gamepad.index);
673
+ if (fallbackIndex >= 0) {
674
+ this.gamepadIndex = fallbackIndex;
675
+ if (this.updateFrame < 0) {
676
+ this.step();
677
+ }
678
+ } else {
679
+ this.cancelUpdate();
680
+ }
681
+ }
682
+
683
+ const gamepadDisconnected = new CustomEvent('c64-controller-disconnected', {
684
+ detail: {
685
+ name: event.gamepad.id,
686
+ index: event.gamepad.index,
687
+ }
688
+ });
689
+ this.target.dispatchEvent(gamepadDisconnected);
690
+ }
691
+
692
+ private handleGamepadConnected(event: GamepadEvent): void {
693
+ console.log(
694
+ "Gamepad connected at index %d: %s. %d buttons, %d axes.",
695
+ event.gamepad.index,
696
+ event.gamepad.id,
697
+ event.gamepad.buttons.length,
698
+ event.gamepad.axes.length,
699
+ );
700
+ if (this.gamepadIndex < 0) {
701
+ this.gamepadIndex = event.gamepad.index;
702
+ }
703
+ const gamepadConnected = new CustomEvent('c64-controller-connected', {
704
+ detail: {
705
+ name: event.gamepad.id,
706
+ index: event.gamepad.index,
707
+ }
708
+ });
709
+
710
+ this.target.dispatchEvent(gamepadConnected);
711
+ if (this.updateFrame < 0) {
712
+ this.step();
713
+ }
516
714
  }
517
715
 
518
716
  private handleKeyDown(event: KeyboardEvent): void {
@@ -534,10 +732,10 @@ export class EmulatorInput {
534
732
  // all other keys route to the C64 keyboard matrix.
535
733
  if (event.code in MIXED_JOYSTICK_KEYS) {
536
734
  // Joystick path
537
- const dir = MIXED_JOYSTICK_KEYS[event.code];
735
+ const dir = MIXED_JOYSTICK_KEYS[event.code] as JoystickInput;
538
736
  this.emulator.joystickPush(
539
- this.keyboardJoystickPort,
540
- dir as import('./constants').JoystickInput,
737
+ this.joystickPort,
738
+ dir,
541
739
  );
542
740
  event.preventDefault();
543
741
  } else {
@@ -561,7 +759,7 @@ export class EmulatorInput {
561
759
  return;
562
760
  }
563
761
  this.pressedControls.add(control);
564
- this.emulator.joystickPush(this.keyboardJoystickPort, KEY_TO_JOYSTICK[control]);
762
+ this.emulator.joystickPush(this.joystickPort, KEY_TO_JOYSTICK[control]);
565
763
  event.preventDefault();
566
764
  }
567
765
 
@@ -582,8 +780,8 @@ export class EmulatorInput {
582
780
  if (event.code in MIXED_JOYSTICK_KEYS) {
583
781
  const dir = MIXED_JOYSTICK_KEYS[event.code];
584
782
  this.emulator.joystickRelease(
585
- this.keyboardJoystickPort,
586
- dir as import('./constants').JoystickInput,
783
+ this.joystickPort,
784
+ dir as JoystickInput,
587
785
  );
588
786
  event.preventDefault();
589
787
  } else {
@@ -605,7 +803,7 @@ export class EmulatorInput {
605
803
  return;
606
804
  }
607
805
  this.pressedControls.delete(control);
608
- this.emulator.joystickRelease(this.keyboardJoystickPort, KEY_TO_JOYSTICK[control]);
806
+ this.emulator.joystickRelease(this.joystickPort, KEY_TO_JOYSTICK[control]);
609
807
  event.preventDefault();
610
808
  }
611
809
 
@@ -618,26 +816,48 @@ export class EmulatorInput {
618
816
 
619
817
  private releaseAll(): void {
620
818
  for (const control of this.pressedControls) {
621
- this.emulator.joystickRelease(this.keyboardJoystickPort, KEY_TO_JOYSTICK[control]);
819
+ this.emulator.joystickRelease(this.joystickPort, KEY_TO_JOYSTICK[control]);
622
820
  }
623
821
  this.pressedControls.clear();
624
822
  }
625
823
 
626
824
  /** Set which joystick port keyboard controls should target (1 or 2). */
627
825
  setKeyboardPort(port: JoystickPort): void {
628
- if (this.keyboardJoystickPort === port) return;
826
+ if (this.joystickPort === port) return;
629
827
  this.releaseAll();
630
- this.keyboardJoystickPort = port;
828
+ this.releaseAllGamepadButtons();
829
+ this.joystickPort = port;
631
830
  }
632
831
 
633
832
  /** Set the input mode. Releases any held joystick buttons on mode change. */
634
833
  setInputMode(mode: InputMode): void {
635
834
  if (this.inputMode === mode) return;
636
835
  this.releaseAll();
836
+ this.releaseAllGamepadButtons();
637
837
  this.inputMode = mode;
638
838
  }
639
839
 
640
840
  getInputMode(): InputMode {
641
841
  return this.inputMode;
642
842
  }
843
+
844
+ setActiveGamepadIndex(index: number): void {
845
+ if (this.gamepadIndex === index) return;
846
+
847
+ const gamepads = navigator.getGamepads?.() ?? [];
848
+ const nextGamepad = gamepads[index];
849
+ if (!nextGamepad) {
850
+ throw new Error(`Gamepad ${index} is not connected`);
851
+ }
852
+
853
+ this.releaseAllGamepadButtons();
854
+ this.gamepadIndex = index;
855
+ if (this.updateFrame < 0) {
856
+ this.step();
857
+ }
858
+ }
859
+
860
+ getActiveGamepadIndex(): number {
861
+ return this.gamepadIndex;
862
+ }
643
863
  }
@@ -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();