-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
2541 lines (2233 loc) · 108 KB
/
Program.cs
File metadata and controls
2541 lines (2233 loc) · 108 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
// =============================================================================
// CHEAPOverlay - Input Service (C#)
// Reads Instruments, broadcasts over WebSocket
// =============================================================================
class GHService
{
// ── WebSocket server ──────────────────────────────────────────────────────
static readonly List<WebSocket> Clients = new();
static readonly Dictionary<WebSocket, SemaphoreSlim> SendLocks = new();
static readonly object ClientLock = new();
// ── Per-player state (slots 0–3) ──────────────────────────────────────────
static GuitarState[] PlayerStates = new GuitarState[4] {
new GuitarState { Player = 0 }, new GuitarState { Player = 1 },
new GuitarState { Player = 2 }, new GuitarState { Player = 3 },
};
static readonly object[] StateLocks = new object[4] { new(), new(), new(), new() };
static bool[] EverConnected = new bool[4];
static async Task Main(string[] args)
{
Console.WriteLine("[CHEAPO] Starting on ws://localhost:2828");
Console.WriteLine("[CHEAPO] Reading XInput + HID instruments");
Console.WriteLine("[CHEAPO] Keep this window open while using the overlay.");
// Start WebSocket server
var wsTask = RunWebSocketServer();
// Start guitar polling
var xinputTask = Task.Run(PollXInput);
var hidTask = Task.Run(PollHID);
var soloTask = Task.Run(PollSoloFrets);
var micTask = Task.Run(PollMic);
var midiTask = Task.Run(PollMIDI);
var ghwtdeTask = Task.Run(PollGHWTDE);
var rb3dxTask = Task.Run(PollRB3DX);
var yargTask = Task.Run(PollYARG);
var ps2Task = Task.Run(PollPS2);
await Task.WhenAll(wsTask, xinputTask, hidTask, soloTask, micTask, midiTask, ghwtdeTask, rb3dxTask, yargTask, ps2Task);
}
// =========================================================================
// WEBSOCKET SERVER
// =========================================================================
static async Task RunWebSocketServer()
{
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:2828/");
listener.Start();
while (true)
{
var ctx = await listener.GetContextAsync();
if (ctx.Request.IsWebSocketRequest)
{
_ = HandleClient(ctx);
}
else
{
ctx.Response.StatusCode = 400;
ctx.Response.Close();
}
}
}
static async Task HandleClient(HttpListenerContext ctx)
{
var wsCtx = await ctx.AcceptWebSocketAsync(null);
var ws = wsCtx.WebSocket;
lock (ClientLock) { Clients.Add(ws); SendLocks[ws] = new SemaphoreSlim(1, 1); }
Console.WriteLine("[CHEAPO] Overlay connected");
// Send current state for all players immediately
for (int p = 0; p < 4; p++) await SendState(ws, PlayerStates[p]);
// Keep alive until disconnected
var buf = new byte[1024];
try
{
while (ws.State == WebSocketState.Open)
{
var result = await ws.ReceiveAsync(new ArraySegment<byte>(buf), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
break;
}
}
catch { }
finally
{
lock (ClientLock) { Clients.Remove(ws); SendLocks.Remove(ws); }
try { ws.Dispose(); } catch { }
}
}
static async Task SendState(WebSocket ws, GuitarState state)
{
if (ws.State != WebSocketState.Open) return;
var json = JsonSerializer.Serialize(state);
var bytes = Encoding.UTF8.GetBytes(json);
try
{
await ws.SendAsync(new ArraySegment<byte>(bytes),
WebSocketMessageType.Text, true, CancellationToken.None);
}
catch { }
}
static void BroadcastPlayerState(int player, GuitarState state)
{
state.Player = player;
BroadcastState(state);
}
static void BroadcastState(GuitarState state)
{
List<WebSocket> snapshot;
lock (ClientLock) snapshot = new List<WebSocket>(Clients);
var json = JsonSerializer.Serialize(state);
var bytes = Encoding.UTF8.GetBytes(json);
foreach (var ws in snapshot)
{
if (ws.State != WebSocketState.Open) continue;
SemaphoreSlim sem;
lock (ClientLock) { if (!SendLocks.TryGetValue(ws, out sem)) continue; }
ThreadPool.QueueUserWorkItem(_ =>
{
sem.Wait();
try
{
if (ws.State == WebSocketState.Open)
ws.SendAsync(new ArraySegment<byte>(bytes),
WebSocketMessageType.Text, true,
CancellationToken.None).GetAwaiter().GetResult();
}
catch { }
finally { sem.Release(); }
});
}
}
// Sends a raw JSON string to all connected overlay clients (used for
// non-GuitarState messages such as calibration state).
static void BroadcastRaw(string json)
{
var bytes = Encoding.UTF8.GetBytes(json);
List<WebSocket> snapshot;
lock (ClientLock) snapshot = new List<WebSocket>(Clients);
foreach (var ws in snapshot)
{
if (ws.State != WebSocketState.Open) continue;
SemaphoreSlim sem;
lock (ClientLock) { if (!SendLocks.TryGetValue(ws, out sem)) continue; }
ThreadPool.QueueUserWorkItem(_ =>
{
sem.Wait();
try
{
if (ws.State == WebSocketState.Open)
ws.SendAsync(new ArraySegment<byte>(bytes),
WebSocketMessageType.Text, true,
CancellationToken.None).GetAwaiter().GetResult();
}
catch { }
finally { sem.Release(); }
});
}
}
static void UpdatePlayerState(int player, GuitarState newState)
{
newState.Player = player;
// Once connected, never go back to disconnected
if (EverConnected[player] && !newState.Connected) return;
if (newState.Connected) EverConnected[player] = true;
lock (StateLocks[player])
{
var cur = PlayerStates[player];
newState.MouthOpen = cur.MouthOpen;
newState.Kick = cur.Kick;
newState.DrumR = cur.DrumR;
newState.DrumY = cur.DrumY;
newState.DrumB = cur.DrumB;
newState.DrumG = cur.DrumG;
// Drum extras — managed by MIDI polling, always preserve here
newState.DrumO = cur.DrumO;
newState.DrumYCym = cur.DrumYCym;
newState.DrumBCym = cur.DrumBCym;
newState.DrumGCym = cur.DrumGCym;
newState.DrumMode = cur.DrumMode;
// Solo frets are managed by UpdatePlayerSoloFrets — always preserve them here.
newState.SoloG = cur.SoloG;
newState.SoloR = cur.SoloR;
newState.SoloY = cur.SoloY;
newState.SoloB = cur.SoloB;
newState.SoloO = cur.SoloO;
// Star power is managed by PollGHWTDE — always preserve here.
newState.StarPower = cur.StarPower;
if (newState.Equals(cur)) return;
PlayerStates[player] = newState;
}
BroadcastPlayerState(player, newState);
}
// Solo fret state is maintained independently and never overwritten by UpdatePlayerState.
// Both PollHID (non-IG_ hasSolo devices) and PollSoloFrets (IG_ hasSolo devices)
// call this to push changes.
static void UpdatePlayerSoloFrets(int player, bool sg, bool sr, bool sy, bool sb, bool so)
{
lock (StateLocks[player])
{
var cur = PlayerStates[player];
if (cur.SoloG == sg && cur.SoloR == sr &&
cur.SoloY == sy && cur.SoloB == sb &&
cur.SoloO == so) return;
cur.SoloG = sg;
cur.SoloR = sr;
cur.SoloY = sy;
cur.SoloB = sb;
cur.SoloO = so;
BroadcastPlayerState(player, cur);
}
}
// =========================================================================
// XINPUT PATH - reads Xbox 360 style instruments (Xplorer, Les Paul, etc.)
// =========================================================================
[StructLayout(LayoutKind.Sequential)]
struct XINPUT_GAMEPAD
{
public ushort wButtons;
public byte bLeftTrigger;
public byte bRightTrigger;
public short sThumbLX;
public short sThumbLY;
public short sThumbRX;
public short sThumbRY;
}
[StructLayout(LayoutKind.Sequential)]
struct XINPUT_STATE
{
public uint dwPacketNumber;
public XINPUT_GAMEPAD Gamepad;
}
[StructLayout(LayoutKind.Sequential)]
struct XINPUT_VIBRATION
{
public ushort wLeftMotorSpeed;
public ushort wRightMotorSpeed;
}
[StructLayout(LayoutKind.Sequential)]
struct XINPUT_CAPABILITIES
{
public byte Type;
public byte SubType;
public ushort Flags;
public XINPUT_GAMEPAD Gamepad;
public XINPUT_VIBRATION Vibration;
}
[DllImport("xinput1_4.dll", EntryPoint = "XInputGetState")]
static extern uint XInputGetState(uint dwUserIndex, ref XINPUT_STATE pState);
[DllImport("xinput1_4.dll", EntryPoint = "XInputGetCapabilities")]
static extern uint XInputGetCapabilities(uint dwUserIndex, uint dwFlags, ref XINPUT_CAPABILITIES pCapabilities);
// XInput button constants
const ushort XINPUT_DPAD_UP = 0x0001;
const ushort XINPUT_DPAD_DOWN = 0x0002;
const ushort XINPUT_BTN_A = 0x1000; // Green fret / Green drum pad
const ushort XINPUT_BTN_B = 0x2000; // Red fret / Red drum pad
const ushort XINPUT_BTN_X = 0x4000; // Blue fret / Blue drum pad
const ushort XINPUT_BTN_Y = 0x8000; // Yellow fret/ Yellow drum pad
const ushort XINPUT_BTN_LB = 0x0100; // Orange fret / Kick pedal
const ushort XINPUT_BTN_RB = 0x0200; // (unused for guitars) / 2nd kick or extra pad
// XInput device subtypes
const byte XINPUT_DEVSUBTYPE_DRUM_KIT = 0x08;
const byte XINPUT_DEVSUBTYPE_KEYBOARD = 0x0F;
const byte XINPUT_DEVSUBTYPE_PRO_GUITAR = 0x19;
static void PollXInput()
{
var prevPacket = new uint[4];
var prevBtns = new ushort[4];
// null = unknown; 0 = guitar/gamepad; 1 = drum kit; 2 = keyboard
var slotType = new byte?[4];
Console.WriteLine("[XInput] polling started (controllers 0-3)");
while (true)
{
for (uint i = 0; i < 4; i++)
{
var state = new XINPUT_STATE();
uint result = XInputGetState(i, ref state);
if (result != 0)
{
if (slotType[i] != null) // slot was occupied, now disconnected
{
lock (StateLocks[i])
{
if (PlayerStates[i].Connected &&
PlayerStates[i].GuitarName?.StartsWith("XInput") == true)
UpdatePlayerState((int)i, new GuitarState { Connected = false });
}
slotType[i] = null;
}
prevBtns[i] = 0;
continue;
}
// First time we see this slot: check capabilities to identify device type
if (slotType[i] == null)
{
var caps = new XINPUT_CAPABILITIES();
if (XInputGetCapabilities(i, 0, ref caps) == 0)
{
if (caps.SubType == XINPUT_DEVSUBTYPE_DRUM_KIT) slotType[i] = 1;
else if (caps.SubType == XINPUT_DEVSUBTYPE_KEYBOARD) slotType[i] = 2;
else if (caps.SubType == XINPUT_DEVSUBTYPE_PRO_GUITAR) slotType[i] = 3;
else slotType[i] = 0;
Console.WriteLine(
$"[XInput] slot {i}: SubType=0x{caps.SubType:X2} " +
$"→ {(slotType[i] == 1 ? "drum kit" : slotType[i] == 2 ? "keyboard" : slotType[i] == 3 ? "pro guitar" : "guitar/gamepad")}");
}
else
{
slotType[i] = 0; // can't identify → treat as guitar
}
}
if (slotType[i] == 1)
{
// ── XInput drum kit ─────────────────────────────────────────
// Set drum mode + connected on first hit (or if mode changed)
lock (StateLocks[i])
{
var ps = PlayerStates[i];
if (!ps.Connected || ps.DrumMode != "rb")
{
EverConnected[i] = true;
ps.Connected = true;
ps.GuitarName = $"XInput Drum Kit {i}";
ps.DrumMode = "rb";
ps.InstrumentType = "drums";
BroadcastPlayerState((int)i, ps);
}
}
// Only process rising edges so each hit is a discrete 120ms flash
if (state.dwPacketNumber == prevPacket[i]) continue;
prevPacket[i] = state.dwPacketNumber;
var gp = state.Gamepad;
ushort pressed = (ushort)(gp.wButtons & ~prevBtns[i]);
prevBtns[i] = gp.wButtons;
// RB drums: Green=A, Red=B, Yellow=Y, Blue=X, Kick=LB
if ((pressed & XINPUT_BTN_A) != 0) FlashPlayerDrumPad((int)i, 'G');
if ((pressed & XINPUT_BTN_B) != 0) FlashPlayerDrumPad((int)i, 'R');
if ((pressed & XINPUT_BTN_Y) != 0) FlashPlayerDrumPad((int)i, 'Y');
if ((pressed & XINPUT_BTN_X) != 0) FlashPlayerDrumPad((int)i, 'B');
if ((pressed & XINPUT_BTN_LB) != 0) FlashPlayerDrumPad((int)i, 'K');
}
else if (slotType[i] == 2)
{
// ── XInput keyboard (RB3 keys) ───────────────────────────────
if (state.dwPacketNumber == prevPacket[i]) continue;
prevPacket[i] = state.dwPacketNumber;
var gp = state.Gamepad;
// Key bit positions (PlasticBand spec, 5-fret mapping):
// C2 = G : bRightTrigger bit 3 (0x08)
// D2 = R : bRightTrigger bit 1 (0x02)
// E2 = Y : sThumbLX bit 7 (0x0080)
// F2 = B : sThumbLX bit 6 (0x0040)
// G2 = O : sThumbLX bit 4 (0x0010)
bool g = (gp.bRightTrigger & 0x08) != 0;
bool r = (gp.bRightTrigger & 0x02) != 0;
bool y = ((ushort)gp.sThumbLX & 0x0080) != 0;
bool b = ((ushort)gp.sThumbLX & 0x0040) != 0;
bool o = ((ushort)gp.sThumbLX & 0x0010) != 0;
UpdatePlayerState((int)i, new GuitarState
{
Connected = true,
GuitarName = $"XInput Keyboard {i}",
InstrumentType = "keys",
G = g, R = r, Y = y, B = b, O = o,
Strum = "neutral"
});
}
else if (slotType[i] == 3)
{
// ── XInput pro guitar (RB3 Mustang) ─────────────────────────
if (state.dwPacketNumber == prevPacket[i]) continue;
prevPacket[i] = state.dwPacketNumber;
var gp = state.Gamepad;
// Per-string fret numbers (5 bits each, 0=open, 1–17 = fret)
// Strings 1–3 (Low E, A, D) packed into combined triggers
// Strings 4–6 (G, B, High E) packed into sThumbLX
ushort trig = (ushort)(gp.bLeftTrigger | (gp.bRightTrigger << 8));
ushort lx = (ushort)gp.sThumbLX;
int fLowE = trig & 0x1F;
int fA = (trig >> 5) & 0x1F;
int fD = (trig >> 10) & 0x1F;
int fG = lx & 0x1F;
int fB = (lx >> 5) & 0x1F;
int fHighE = (lx >> 10) & 0x1F;
// Frets 13–17 are the solo zone (upper neck, same as solo buttons
// on a standard RB guitar). Any string there = solo mode.
bool anySolo = (fLowE >= 13 && fLowE <= 17) ||
(fA >= 13 && fA <= 17) ||
(fD >= 13 && fD <= 17) ||
(fG >= 13 && fG <= 17) ||
(fB >= 13 && fB <= 17) ||
(fHighE >= 13 && fHighE <= 17);
// 5-fret color flags — high bits of velocity byte pairs
// Green = sThumbLY bit 7 (0x0080)
// Red = sThumbLY bit 15 (0x8000)
// Yellow = sThumbRX bit 7 (0x0080)
// Blue = sThumbRX bit 15 (0x8000)
// Orange = sThumbRY bit 7 (0x0080)
bool g = ((ushort)gp.sThumbLY & 0x0080) != 0;
bool r = ((ushort)gp.sThumbLY & 0x8000) != 0;
bool y = ((ushort)gp.sThumbRX & 0x0080) != 0;
bool b = ((ushort)gp.sThumbRX & 0x8000) != 0;
bool o = ((ushort)gp.sThumbRY & 0x0080) != 0;
// Strum: D-pad up/down
string strum = "neutral";
if ((gp.wButtons & XINPUT_DPAD_UP) != 0) strum = "up";
if ((gp.wButtons & XINPUT_DPAD_DOWN) != 0) strum = "down";
// Route color flags: solo zone → solo frets, regular zone → frets
UpdatePlayerState((int)i, new GuitarState
{
Connected = true,
GuitarName = $"XInput Pro Guitar {i}",
InstrumentType = "guitar",
G = !anySolo && g,
R = !anySolo && r,
Y = !anySolo && y,
B = !anySolo && b,
O = !anySolo && o,
Strum = strum
});
UpdatePlayerSoloFrets((int)i,
anySolo && g,
anySolo && r,
anySolo && y,
anySolo && b,
anySolo && o);
}
else
{
// ── XInput guitar / gamepad ──────────────────────────────────
// Packet number not used — some controllers (e.g. Santroller)
// don't increment it reliably. Use button-state change instead.
var gp = state.Gamepad;
if (gp.wButtons == prevBtns[i] && state.dwPacketNumber == prevPacket[i]) continue;
prevPacket[i] = state.dwPacketNumber;
prevBtns[i] = gp.wButtons;
// Fret mapping: Green=A, Red=B, Yellow=Y, Blue=X, Orange=LB
bool g = (gp.wButtons & XINPUT_BTN_A) != 0;
bool r = (gp.wButtons & XINPUT_BTN_B) != 0;
bool y = (gp.wButtons & XINPUT_BTN_Y) != 0;
bool b = (gp.wButtons & XINPUT_BTN_X) != 0;
bool o = (gp.wButtons & XINPUT_BTN_LB) != 0;
// Strum: D-pad up/down, or left stick Y
string strum = "neutral";
if ((gp.wButtons & XINPUT_DPAD_UP) != 0) strum = "up";
if ((gp.wButtons & XINPUT_DPAD_DOWN) != 0) strum = "down";
if (strum == "neutral" && gp.sThumbLY < -20000) strum = "down";
if (strum == "neutral" && gp.sThumbLY > 20000) strum = "up";
UpdatePlayerState((int)i, new GuitarState
{
Connected = true,
GuitarName = $"XInput Controller {i}",
InstrumentType = "guitar",
G = g, R = r, Y = y, B = b, O = o,
Strum = strum
});
}
}
Thread.Sleep(4); // ~250hz polling
}
}
// Shared by XInput drum path and MIDI path — flash a drum pad for 120 ms
static void FlashPlayerDrumPad(int player, char pad)
{
long now = Environment.TickCount64;
lock (StateLocks[player]) {
_drumHitTime[player][pad] = now;
SetPlayerDrumPad(player, pad, true);
BroadcastPlayerState(player, PlayerStates[player]);
}
ThreadPool.QueueUserWorkItem(_ => {
Thread.Sleep(120);
lock (StateLocks[player]) {
if (_drumHitTime[player].TryGetValue(pad, out long t) && Environment.TickCount64 - t >= 120) {
SetPlayerDrumPad(player, pad, false);
BroadcastPlayerState(player, PlayerStates[player]);
}
}
});
}
// =========================================================================
// HID PATH - reads HID guitars (Santroller, RCM, RB wireless)
// =========================================================================
// Known guitar VID/PIDs
static readonly (int vid, int pid, bool hasSolo, string name)[] KnownGuitars = {
(0x1430, 0x4748, false, "GH Xplorer"),
(0x1430, 0x474C, false, "GH Les Paul"),
(0x1430, 0x4750, false, "GH World Tour"),
(0x1BAD, 0x0002, true, "RB1/RB2 Guitar"),
(0x1BAD, 0x02AA, true, "RB2 Guitar (wireless)"),
(0x1BAD, 0x0203, true, "RB3 Guitar"),
(0x1BAD, 0x0004, true, "RB4 Guitar"),
};
[DllImport("hid.dll")]
static extern bool HidD_GetHidGuid(out Guid HidGuid);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, string Enumerator,
IntPtr hwndParent, uint Flags);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
static extern bool SetupDiEnumDeviceInterfaces(IntPtr DeviceInfoSet,
IntPtr DeviceInfoData, ref Guid InterfaceClassGuid,
uint MemberIndex, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr DeviceInfoSet,
ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData,
IntPtr DeviceInterfaceDetailData, uint DeviceInterfaceDetailDataSize,
out uint RequiredSize, IntPtr DeviceInfoData);
[DllImport("setupapi.dll")]
static extern bool SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll")]
static extern bool ReadFile(IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToRead,
out uint lpNumberOfBytesRead, IntPtr lpOverlapped);
[DllImport("kernel32.dll")]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("hid.dll")]
static extern bool HidD_GetAttributes(IntPtr HidDeviceObject,
ref HIDD_ATTRIBUTES Attributes);
[DllImport("hid.dll", CharSet = CharSet.Auto)]
static extern bool HidD_GetProductString(IntPtr HidDeviceObject,
byte[] Buffer, uint BufferLength);
[StructLayout(LayoutKind.Sequential)]
struct SP_DEVICE_INTERFACE_DATA
{
public uint cbSize;
public Guid InterfaceClassGuid;
public uint Flags;
public IntPtr Reserved;
}
[StructLayout(LayoutKind.Sequential)]
struct HIDD_ATTRIBUTES
{
public uint Size;
public ushort VendorID;
public ushort ProductID;
public ushort VersionNumber;
}
const uint DIGCF_PRESENT = 0x02;
const uint DIGCF_DEVICEINTERFACE = 0x10;
const uint GENERIC_READ = 0x80000000;
const uint FILE_SHARE_READ = 0x01;
const uint FILE_SHARE_WRITE = 0x02;
const uint OPEN_EXISTING = 3;
const uint FILE_FLAG_OVERLAPPED = 0x40000000;
static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
static void PollHID()
{
Console.WriteLine("[HID] polling started");
while (true)
{
// Don't compete with XInput player 0 if it has an active guitar
bool xinputActive;
lock (StateLocks[0])
xinputActive = PlayerStates[0].Connected &&
PlayerStates[0].GuitarName?.StartsWith("XInput") == true;
if (xinputActive)
{
Thread.Sleep(500);
continue;
}
IntPtr handle = INVALID_HANDLE_VALUE;
string guitarName = null;
bool hasSolo = false;
try
{
HidD_GetHidGuid(out Guid hidGuid);
var devInfoSet = SetupDiGetClassDevs(ref hidGuid, null,
IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (devInfoSet == INVALID_HANDLE_VALUE)
{
Thread.Sleep(2000);
continue;
}
uint idx = 0;
var devIfaceData = new SP_DEVICE_INTERFACE_DATA();
devIfaceData.cbSize = (uint)Marshal.SizeOf(devIfaceData);
while (SetupDiEnumDeviceInterfaces(devInfoSet, IntPtr.Zero,
ref hidGuid, idx++, ref devIfaceData))
{
SetupDiGetDeviceInterfaceDetail(devInfoSet, ref devIfaceData,
IntPtr.Zero, 0, out uint reqSize, IntPtr.Zero);
if (reqSize == 0) continue;
var detailBuf = Marshal.AllocHGlobal((int)reqSize);
Marshal.WriteInt32(detailBuf, IntPtr.Size == 8 ? 8 : 6);
SetupDiGetDeviceInterfaceDetail(devInfoSet, ref devIfaceData,
detailBuf, reqSize, out _, IntPtr.Zero);
string path = Marshal.PtrToStringAuto(
IntPtr.Add(detailBuf, 4));
Marshal.FreeHGlobal(detailBuf);
if (string.IsNullOrEmpty(path)) continue;
// Skip XInput interfaces
if (path.ToUpper().Contains("IG_")) continue;
var tmpHandle = CreateFile(path,
GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (tmpHandle == INVALID_HANDLE_VALUE) continue;
var attrs = new HIDD_ATTRIBUTES();
attrs.Size = (uint)Marshal.SizeOf(attrs);
if (!HidD_GetAttributes(tmpHandle, ref attrs))
{
CloseHandle(tmpHandle);
continue;
}
int vid = attrs.VendorID;
int pid = attrs.ProductID;
bool matched = false;
foreach (var (kv, kp, ks, kn) in KnownGuitars)
{
if (kv == vid && kp == pid)
{
handle = tmpHandle;
guitarName = kn;
hasSolo = ks;
matched = true;
Console.WriteLine($"[HID] found: {kn} ({vid:X4}:{pid:X4})");
break;
}
}
if (!matched)
{
CloseHandle(tmpHandle);
}
else
{
Console.WriteLine($"[HID] matched: {guitarName} path: {path}");
break;
}
}
SetupDiDestroyDeviceInfoList(devInfoSet);
}
catch (Exception ex)
{
Console.WriteLine($"[HID] scan error: {ex.Message}");
Thread.Sleep(2000);
continue;
}
if (handle == INVALID_HANDLE_VALUE || handle == IntPtr.Zero)
{
Thread.Sleep(2000);
continue;
}
// Read loop
UpdatePlayerState(0, new GuitarState { Connected = true, GuitarName = guitarName, InstrumentType = "guitar" });
var buf = new byte[64];
while (true)
{
if (!ReadFile(handle, buf, (uint)buf.Length, out uint bytesRead, IntPtr.Zero)
|| bytesRead == 0)
{
var err = Marshal.GetLastWin32Error();
Console.WriteLine($"[HID] read failed (error {err}), reconnecting...");
break;
}
int regularFrets = buf[6];
// buf[7] contains combined fret state (regular + solo); mask out regular to isolate solo-only bits
int soloFrets = hasSolo ? (buf[7] & ~regularFrets) : 0;
// Keep regular and solo frets separate — solo frets use their own sprites
int strum = buf[8];
UpdatePlayerState(0, new GuitarState
{
Connected = true,
GuitarName = guitarName,
InstrumentType = "guitar",
G = (regularFrets & 0x01) != 0,
R = (regularFrets & 0x02) != 0,
Y = (regularFrets & 0x08) != 0,
B = (regularFrets & 0x04) != 0,
O = (regularFrets & 0x10) != 0,
Strum = strum == 1 ? "up" : strum == 5 ? "down" : "neutral",
});
if (hasSolo)
UpdatePlayerSoloFrets(0,
(soloFrets & 0x01) != 0, (soloFrets & 0x02) != 0,
(soloFrets & 0x08) != 0, (soloFrets & 0x04) != 0,
(soloFrets & 0x10) != 0);
}
CloseHandle(handle);
UpdatePlayerState(0, new GuitarState { Connected = false });
Thread.Sleep(2000);
}
}
// =========================================================================
// SOLO FRET POLLING — reads buf[7] from IG_ HID paths (XInput RB guitars)
// XInput exposes raw HID reports on the IG_ path alongside its own API.
// PollHID skips IG_ paths, so this task handles solo frets for those devices.
// Non-IG_ hasSolo devices are handled directly inside PollHID.
// =========================================================================
static void PollSoloFrets()
{
Console.WriteLine("[Solo Frets] poller started");
while (true)
{
IntPtr handle = INVALID_HANDLE_VALUE;
try
{
HidD_GetHidGuid(out Guid hidGuid);
var devInfoSet = SetupDiGetClassDevs(ref hidGuid, null,
IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (devInfoSet == INVALID_HANDLE_VALUE) { Thread.Sleep(2000); continue; }
uint idx = 0;
var devIfaceData = new SP_DEVICE_INTERFACE_DATA();
devIfaceData.cbSize = (uint)Marshal.SizeOf(devIfaceData);
while (SetupDiEnumDeviceInterfaces(devInfoSet, IntPtr.Zero,
ref hidGuid, idx++, ref devIfaceData))
{
SetupDiGetDeviceInterfaceDetail(devInfoSet, ref devIfaceData,
IntPtr.Zero, 0, out uint reqSize, IntPtr.Zero);
if (reqSize == 0) continue;
var detailBuf = Marshal.AllocHGlobal((int)reqSize);
Marshal.WriteInt32(detailBuf, IntPtr.Size == 8 ? 8 : 6);
SetupDiGetDeviceInterfaceDetail(devInfoSet, ref devIfaceData,
detailBuf, reqSize, out _, IntPtr.Zero);
string path = Marshal.PtrToStringAuto(IntPtr.Add(detailBuf, 4));
Marshal.FreeHGlobal(detailBuf);
if (string.IsNullOrEmpty(path)) continue;
// We ONLY handle XInput HID paths (IG_) here.
// Non-IG_ hasSolo devices are handled by PollHID.
if (!path.ToUpper().Contains("IG_")) continue;
var tmpHandle = CreateFile(path,
GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (tmpHandle == INVALID_HANDLE_VALUE) continue;
var attrs = new HIDD_ATTRIBUTES();
attrs.Size = (uint)Marshal.SizeOf(attrs);
if (!HidD_GetAttributes(tmpHandle, ref attrs))
{ CloseHandle(tmpHandle); continue; }
int vid = attrs.VendorID;
int pid = attrs.ProductID;
bool matched = false;
foreach (var (kv, kp, ks, kn) in KnownGuitars)
{
if (kv == vid && kp == pid && ks) // hasSolo only
{
handle = tmpHandle;
matched = true;
Console.WriteLine($"[Solo Frets] reader: {kn} ({vid:X4}:{pid:X4})");
break;
}
}
if (!matched) CloseHandle(tmpHandle);
else break;
}
SetupDiDestroyDeviceInfoList(devInfoSet);
}
catch (Exception ex)
{
Console.WriteLine($"[Solo Frets] scan error: {ex.Message}");
Thread.Sleep(2000);
continue;
}
if (handle == INVALID_HANDLE_VALUE || handle == IntPtr.Zero)
{
Thread.Sleep(2000);
continue;
}
// Read loop — buf[8]=0x01: solo frets active, buf[7] has the fret bits.
// buf[8]=0x00: regular frets active, solo frets cleared.
var buf = new byte[64];
while (true)
{
if (!ReadFile(handle, buf, (uint)buf.Length, out uint bytesRead, IntPtr.Zero)
|| bytesRead == 0)
{
Console.WriteLine("[Solo Frets] reader disconnected, rescanning...");
UpdatePlayerSoloFrets(0, false, false, false, false, false);
break;
}
int fretBits = buf[8] == 0x01 ? buf[7] : 0;
UpdatePlayerSoloFrets(0,
(fretBits & 0x01) != 0, (fretBits & 0x02) != 0,
(fretBits & 0x08) != 0, (fretBits & 0x04) != 0,
(fretBits & 0x10) != 0);
}
CloseHandle(handle);
Thread.Sleep(2000);
}
}
// =========================================================================
// MIC POLLING — WaveIn (captures PCM) + RNNoise voice activity detection
// =========================================================================
// ── RNNoise P/Invoke ──────────────────────────────────────────────────────
// Native DLL (rnnoise.dll) is bundled via YellowDogMan.RNNoise.NET NuGet.
// Returns voice probability 0–1 per 480-sample frame at 48 kHz.
[DllImport("rnnoise", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr rnnoise_create(IntPtr model);
[DllImport("rnnoise", CallingConvention = CallingConvention.Cdecl)]
static extern void rnnoise_destroy(IntPtr st);
[DllImport("rnnoise", CallingConvention = CallingConvention.Cdecl)]
static extern float rnnoise_process_frame(IntPtr st, float[] pcmOut, float[] pcmIn);
const int RNNOISE_FRAME_SIZE = 480; // 10 ms at 48 kHz
const float MIC_VOICE_PROB = 0.80f; // voice probability to open mouth (0–1)
// ── Fallback amplitude gate (used if rnnoise.dll is missing) ─────────────
const float MIC_THRESHOLD = 0.01f;
const float MIC_CEILING = 0.45f;
const float MIC_EMA_ALPHA = 0.30f;
const int MIC_HOLD_FRAMES = 3;
[StructLayout(LayoutKind.Sequential)]
struct WAVEFORMATEX_MIC {
public ushort wFormatTag;
public ushort nChannels;
public uint nSamplesPerSec;
public uint nAvgBytesPerSec;
public ushort nBlockAlign;
public ushort wBitsPerSample;
public ushort cbSize;
}
[StructLayout(LayoutKind.Sequential)]
struct WAVEHDR {
public IntPtr lpData;
public uint dwBufferLength;
public uint dwBytesRecorded;
public IntPtr dwUser;
public uint dwFlags;
public uint dwLoops;
public IntPtr lpNext;
public IntPtr reserved;
}
const uint WHDR_DONE = 0x00000001;
[DllImport("winmm.dll")] static extern uint waveInOpen(out IntPtr hwi, uint dev, ref WAVEFORMATEX_MIC fmt, IntPtr cb, IntPtr inst, uint flags);
[DllImport("winmm.dll")] static extern uint waveInPrepareHeader(IntPtr hwi, IntPtr pwh, uint cb);
[DllImport("winmm.dll")] static extern uint waveInAddBuffer(IntPtr hwi, IntPtr pwh, uint cb);
[DllImport("winmm.dll")] static extern uint waveInStart(IntPtr hwi);
[DllImport("winmm.dll")] static extern uint waveInReset(IntPtr hwi);
[DllImport("winmm.dll")] static extern uint waveInUnprepareHeader(IntPtr hwi, IntPtr pwh, uint cb);
[DllImport("winmm.dll")] static extern uint waveInClose(IntPtr hwi);
static float ComputePeak16(IntPtr buf, int bytes)
{
float peak = 0f;
for (int i = 0; i < bytes / 2; i++)
{
float v = Math.Abs((int)Marshal.ReadInt16(buf, i * 2)) / 32768f;
if (v > peak) peak = v;
}
return peak;
}
static void UpdateMouth(bool open)
{
lock (StateLocks[0])
{
if (PlayerStates[0].MouthOpen == open) return;
PlayerStates[0].MouthOpen = open;
BroadcastPlayerState(0, PlayerStates[0]);
}
}
static void PollMic()
{
Console.WriteLine("[Mic] polling started");
const uint RATE = 48000; // RNNoise requires 48 kHz
const int BUF_BYTES = (int)(RATE / 10 * 2); // 100 ms, mono, 16-bit = 9600 bytes
// ── Init RNNoise (once, lives for process lifetime) ───────────────────
IntPtr rnState = IntPtr.Zero;
var rnIn = new float[RNNOISE_FRAME_SIZE];
var rnOut = new float[RNNOISE_FRAME_SIZE];
try
{
rnState = rnnoise_create(IntPtr.Zero);
if (rnState != IntPtr.Zero)
Console.WriteLine("[Mic] voice detection active");
}
catch (DllNotFoundException)
{