-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathusb_hid.c
More file actions
3466 lines (2990 loc) · 137 KB
/
Copy pathusb_hid.c
File metadata and controls
3466 lines (2990 loc) · 137 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
/*
* Hurricane PIOKMBox Firmware
*/
#include "usb_hid.h"
#include "defines.h"
#include "led_control.h"
#include "lib/kmbox-commands/kmbox_commands.h"
#include "pico/stdlib.h"
#include "pico/platform.h"
#include "hardware/timer.h" // For time_us_32() in hid_device_task
#include "kmbox_serial_handler.h" // Include the header for serial handling
#include "state_management.h" // Include the header for state management
#include "watchdog.h" // Include the header for watchdog management
#include "smooth_injection.h" // Include the header for smooth mouse injection
#include "humanization_fpu.h" // Include for tremor generation
#include "xbox_gip.h" // Xbox mode flag
#include "xbox_device.h" // Xbox device descriptors
#include <string.h> // For strcpy, strlen, memset
#include <math.h> // For sqrtf, roundf
#include "pico/rand.h" // For get_rand_32() hardware TRNG
uint16_t attached_vid = 0;
uint16_t attached_pid = 0;
bool attached_has_serial = false;
static volatile bool pending_device_reenumeration = false;
static bool checked_runtime_mouse_override = false;
// Dynamic string descriptor storage
static char attached_manufacturer[64] = "";
static char attached_product[64] = "";
static char attached_serial[32] = "";
static bool string_descriptors_fetched = false;
#define LANGUAGE_ID 0x0409 // English (US)
// UTF-16LE string descriptor -> UTF-8 (ASCII-only) conversion.
// Uses the descriptor's bLength to avoid reading past valid data.
static void utf16_to_utf8(uint16_t *utf16_buf, size_t utf16_buf_bytes, char *utf8_buf, size_t utf8_len)
{
if (!utf16_buf || !utf8_buf || utf8_len == 0)
return;
// String descriptor format: [bLength (1B)][bDescriptorType (1B)][UTF-16LE code units...]
// Determine actual descriptor length from first byte
const uint8_t *raw = (const uint8_t *)utf16_buf;
// Cap length by provided buffer size to be safe
uint8_t bLength = raw[0];
if (bLength > utf16_buf_bytes)
{
bLength = (uint8_t)utf16_buf_bytes;
}
// Compute number of 16-bit code units
size_t code_units = 0;
if (bLength >= 2)
{
code_units = (size_t)(bLength - 2) / 2;
}
size_t utf8_pos = 0;
// Unroll loop by 4 for better performance (most strings are short)
size_t i = 0;
size_t utf16_buf_len = utf16_buf_bytes / 2; // Total UTF-16 code units available
while (i + 3 < code_units && utf8_pos + 3 < utf8_len - 1 && (1 + i + 3) < utf16_buf_len) {
uint16_t u0 = utf16_buf[1 + i];
uint16_t u1 = utf16_buf[1 + i + 1];
uint16_t u2 = utf16_buf[1 + i + 2];
uint16_t u3 = utf16_buf[1 + i + 3];
// Early exit on NUL
if (u0 == 0) break;
utf8_buf[utf8_pos++] = (u0 <= 0x7F) ? (char)u0 : '?';
if (u1 == 0) break;
utf8_buf[utf8_pos++] = (u1 <= 0x7F) ? (char)u1 : '?';
if (u2 == 0) break;
utf8_buf[utf8_pos++] = (u2 <= 0x7F) ? (char)u2 : '?';
if (u3 == 0) break;
utf8_buf[utf8_pos++] = (u3 <= 0x7F) ? (char)u3 : '?';
i += 4;
}
// Handle remaining code units
for (; i < code_units && utf8_pos < utf8_len - 1; i++)
{
uint16_t u = utf16_buf[1 + i];
if (u == 0) break;
utf8_buf[utf8_pos++] = (u <= 0x7F) ? (char)u : '?';
}
utf8_buf[utf8_pos] = '\0';
}
// Function to set the VID and PID of the attached device
void set_attached_device_vid_pid(uint16_t vid, uint16_t pid) {
// Only update and re-enumerate if VID/PID has actually changed
if (attached_vid != vid || attached_pid != pid) {
attached_vid = vid;
attached_pid = pid;
attached_has_serial = false; // Default to no serial number unless device has one
// Force USB re-enumeration to update descriptor
force_usb_reenumeration();
}
}
void force_usb_reenumeration() {
// Disconnect from USB host
tud_disconnect();
// Wait for host to recognize disconnection (500ms for Windows/macOS)
// Feed watchdog during long wait to prevent reset
for (int i = 0; i < 50; i++) {
sleep_ms(10);
watchdog_core0_heartbeat();
}
// Reconnect with new descriptor
tud_connect();
// Wait for reconnection (250ms for stability)
// Feed watchdog during wait
for (int i = 0; i < 25; i++) {
sleep_ms(10);
watchdog_core0_heartbeat();
}
}
static inline void request_device_reenumeration(void) {
__dmb();
pending_device_reenumeration = true;
}
//--------------------------------------------------------------------+
// USB Descriptor Cloning Infrastructure
//--------------------------------------------------------------------+
// Forward declarations
static void build_runtime_hid_report_with_mouse(const uint8_t *mouse_desc, size_t mouse_len);
static void rebuild_configuration_descriptor(void);
static void parse_host_config_descriptor(const uint8_t *cfg_desc, uint16_t cfg_len);
static void reset_device_string_descriptors(void); // Defined after all global state
// Captured host device descriptor fields for cloning
static struct {
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize0;
uint16_t bcdDevice;
uint8_t iManufacturer;
uint8_t iProduct;
uint8_t iSerialNumber;
bool valid;
} host_device_info = { .bcdUSB = 0x0200, .bMaxPacketSize0 = 64, .bcdDevice = 0x0100, .valid = false };
// Captured host config descriptor fields for cloning
static struct {
uint8_t bmAttributes; // Self-powered, remote wakeup
uint8_t bMaxPower; // In 2mA units
uint8_t bInterfaceProtocol; // Boot mouse protocol etc
uint8_t bInterfaceSubClass;
uint16_t wMaxPacketSize; // Endpoint max packet size
uint8_t bInterval; // Polling interval
bool valid;
} host_config_info = { .bmAttributes = TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP, .bMaxPower = USB_CONFIG_POWER_MA / 2, .bInterfaceProtocol = HID_ITF_PROTOCOL_NONE, .bInterfaceSubClass = 0, .wMaxPacketSize = CFG_TUD_HID_EP_BUFSIZE, .bInterval = HID_POLLING_INTERVAL_MS, .valid = false };
// Runtime configuration descriptor buffer (large enough for multi-interface)
static uint8_t desc_configuration_runtime[DESC_CONFIG_RUNTIME_MAX];
static bool desc_config_runtime_valid = false;
//--------------------------------------------------------------------+
// Multi-interface mirroring infrastructure
//--------------------------------------------------------------------+
// Per-interface state captured from host device for faithful mirroring.
// Gaming mice expose 2-4 HID interfaces (mouse, keyboard-macros, vendor).
// We capture all of them and present matching interfaces on the device side.
typedef struct {
// Interface properties (from host config descriptor)
uint8_t itf_subclass;
uint8_t itf_protocol;
uint16_t ep_in_max_packet;
uint8_t ep_in_interval;
bool has_ep_out;
uint16_t ep_out_max_packet;
uint8_t ep_out_interval;
// Runtime state (populated during tuh_hid_mount_cb)
uint8_t host_dev_addr;
uint8_t host_instance;
bool is_mouse; // Interface we inject mouse/keyboard/consumer into
// HID report descriptor (non-mouse only; mouse uses desc_hid_report_runtime)
uint8_t report_desc[MIRROR_ITF_DESC_MAX];
uint16_t report_desc_len;
bool active;
} mirrored_interface_t;
static mirrored_interface_t mirrored_itfs[MAX_DEVICE_HID_INTERFACES];
static uint8_t mirrored_itf_count = 0; // Active mirrored interfaces
static uint8_t expected_hid_itf_count = 0; // Expected from config descriptor
static uint8_t mounted_hid_itf_count = 0; // Mounted so far
// Which device-side HID instance carries the composite descriptor (keyboard +
// mouse + consumer). All mouse/keyboard/consumer reports must be sent on this
// instance. Defaults to 0 for single-interface mode.
static uint8_t mouse_device_instance = 0;
// Vendor report passthrough queue (Core1 producer → Core0 consumer).
// When the host mouse sends vendor reports (e.g. Logitech HID++, Razer),
// Core1 queues them here and Core0 drains them via tud_hid_report().
#define VENDOR_QUEUE_SIZE 16
#define VENDOR_QUEUE_MASK (VENDOR_QUEUE_SIZE - 1)
#define VENDOR_REPORT_MAX_LEN 64
#define PASSTHROUGH_GET_TIMEOUT_US 80000u
typedef struct {
uint8_t device_instance; // Which device-side HID instance to send on
uint8_t report_id;
uint8_t data[VENDOR_REPORT_MAX_LEN];
uint8_t len;
} vendor_report_entry_t;
static struct {
vendor_report_entry_t entries[VENDOR_QUEUE_SIZE];
volatile uint8_t head; // Written by Core1 (producer)
volatile uint8_t tail; // Read by Core0 (consumer)
} vendor_fwd_queue;
// SET_REPORT passthrough queue (Core0 producer → Core1 consumer).
// When the downstream PC sends SET_REPORT to vendor interfaces, Core0
// queues them here and Core1 forwards to the real mouse.
typedef struct {
uint8_t host_dev_addr;
uint8_t host_instance;
uint8_t report_id;
uint8_t report_type;
uint8_t data[VENDOR_REPORT_MAX_LEN];
uint8_t len;
} set_report_entry_t;
static struct {
set_report_entry_t entries[VENDOR_QUEUE_SIZE];
volatile uint8_t head; // Written by Core0 (producer)
volatile uint8_t tail; // Read by Core1 (consumer)
} set_report_queue;
// Extended string descriptor cache.
// Gaming mice may use string indices beyond the standard 1-3 (manufacturer,
// product, serial). Interface strings, HID class strings, etc.
#define MAX_CACHED_STRINGS 8
#define CACHED_STRING_MAX_LEN 64
typedef struct {
uint8_t index;
char str[CACHED_STRING_MAX_LEN];
bool valid;
} cached_string_t;
static cached_string_t extra_strings[MAX_CACHED_STRINGS];
static uint8_t extra_string_count = 0;
static uint8_t max_string_index_seen = 3; // Track highest string index from host
// GET_REPORT cache: stores the last received report per (instance, report_id)
// so that tud_hid_get_report_cb can respond to the host (macOS IOKit sends
// GET_REPORT during device open to verify responsiveness).
// Written by Core1 (in queue_vendor_report), read by Core0 (in get_report_cb).
#define REPORT_CACHE_SLOTS_PER_ITF 8
typedef struct {
uint8_t report_id;
uint8_t report_type;
uint8_t data[VENDOR_REPORT_MAX_LEN];
uint8_t len;
bool valid;
} cached_report_t;
static cached_report_t report_cache[MAX_DEVICE_HID_INTERFACES][REPORT_CACHE_SLOTS_PER_ITF];
typedef struct {
volatile bool pending;
volatile bool busy;
volatile bool done;
uint8_t host_dev_addr;
uint8_t host_instance;
uint8_t report_id;
uint8_t report_type;
uint16_t request_len;
volatile uint16_t actual_len;
uint8_t data[VENDOR_REPORT_MAX_LEN];
} get_report_bridge_t;
static get_report_bridge_t get_report_bridge;
// Function to fetch string descriptors from attached device
static void fetch_device_string_descriptors(uint8_t dev_addr) {
// Reset string descriptors
memset(attached_manufacturer, 0, sizeof(attached_manufacturer));
memset(attached_product, 0, sizeof(attached_product));
memset(attached_serial, 0, sizeof(attached_serial));
string_descriptors_fetched = false;
// Temporary buffers for UTF-16 strings
uint16_t temp_manufacturer[32];
uint16_t temp_product[48];
uint16_t temp_serial[16];
// Ensure buffers are zeroed to avoid stray data being interpreted
memset(temp_manufacturer, 0, sizeof(temp_manufacturer));
memset(temp_product, 0, sizeof(temp_product));
memset(temp_serial, 0, sizeof(temp_serial));
// Get manufacturer string
if (tuh_descriptor_get_manufacturer_string_sync(dev_addr, LANGUAGE_ID, temp_manufacturer, sizeof(temp_manufacturer)) == XFER_RESULT_SUCCESS) {
utf16_to_utf8(temp_manufacturer, sizeof(temp_manufacturer), attached_manufacturer, sizeof(attached_manufacturer));
kmbox_send_status(attached_manufacturer);
} else {
strcpy(attached_manufacturer, MANUFACTURER_STRING); // Fallback
}
// Get product string
if (tuh_descriptor_get_product_string_sync(dev_addr, LANGUAGE_ID, temp_product, sizeof(temp_product)) == XFER_RESULT_SUCCESS) {
utf16_to_utf8(temp_product, sizeof(temp_product), attached_product, sizeof(attached_product));
kmbox_send_status(attached_product);
} else {
strcpy(attached_product, PRODUCT_STRING); // Fallback
}
// Get serial string (optional)
if (tuh_descriptor_get_serial_string_sync(dev_addr, LANGUAGE_ID, temp_serial, sizeof(temp_serial)) == XFER_RESULT_SUCCESS) {
utf16_to_utf8(temp_serial, sizeof(temp_serial), attached_serial, sizeof(attached_serial));
char serial_msg[64];
snprintf(serial_msg, sizeof(serial_msg), "Serial: %s", attached_serial);
kmbox_send_status(serial_msg);
attached_has_serial = (strlen(attached_serial) > 0);
} else {
attached_has_serial = false;
}
string_descriptors_fetched = true;
}
// reset_device_string_descriptors() — defined after all global state declarations
// (see forward declaration above)
// Function to get the VID of the attached device
uint16_t get_attached_vid(void) {
return attached_vid;
}
// Function to get the PID of the attached device
uint16_t get_attached_pid(void) {
return attached_pid;
}
// Function to get attached device manufacturer string
const char* get_attached_manufacturer(void) {
return attached_manufacturer;
}
// Function to get attached device product string
const char* get_attached_product(void) {
return attached_product;
}
// Function to get dynamic serial string
const char* get_dynamic_serial_string() {
static char dynamic_serial[64];
if (attached_vid && attached_pid) {
snprintf(dynamic_serial, sizeof(dynamic_serial), "PIOKMbox_%04X_%04X", attached_vid, attached_pid);
return dynamic_serial;
}
return "PIOKMbox_v1.0";
}
// Error tracking structure with better organization
typedef struct
{
uint32_t device_errors;
uint32_t host_errors;
uint32_t consecutive_device_errors;
uint32_t consecutive_host_errors;
uint32_t last_error_check_time;
bool device_error_state;
bool host_error_state;
} usb_error_tracker_t;
// Device connection state with better encapsulation
typedef struct
{
bool mouse_connected;
bool keyboard_connected;
uint8_t mouse_dev_addr;
uint8_t keyboard_dev_addr;
} device_connection_state_t;
// Device mode state
static bool caps_lock_state = false;
static device_connection_state_t connection_state = {0};
// Error tracking - now properly typed
static usb_error_tracker_t usb_error_tracker = {0};
// USB stack initialization tracking
static bool usb_device_initialized = false;
static bool usb_host_initialized = false;
// Track the last button byte sent to the host across ALL report paths
// (physical mouse forwarding, kmbox injection, smooth injection).
// Used by hid_device_task() to detect button-only changes that need
// an immediate report — a real mouse sends button changes on the very
// next poll.
static volatile uint8_t last_sent_buttons = 0;
// Track whether the previous cycle had activity, so we can send one
// final zero-delta "stop" report on the active→idle edge.
static volatile bool was_active = false;
// Set by Core1 after accumulating physical mouse data.
// Checked by Core0's hid_device_task() to bypass the 1ms timer
// and send immediately when the USB endpoint is ready.
static volatile bool fresh_mouse_data = false;
//--------------------------------------------------------------------+
// Output-stage PRNG (xorshift32, independent from smooth_injection.c)
//--------------------------------------------------------------------+
static uint32_t hid_rng_state = 0;
static void hid_rng_seed(uint32_t seed) {
hid_rng_state = seed ? seed : 0xDEADBEEF;
}
static inline uint32_t hid_rng_next(void) {
uint32_t x = hid_rng_state;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
hid_rng_state = x;
return x;
}
// Gaussian approximation via CLT: sum of 4 uniform [0,1) values → ~N(2,1/√3)
// Normalized to ~N(0,1) by subtracting 2 and scaling.
static inline float hid_rng_gaussian(void) {
const float scale = 1.0f / 4294967296.0f; // 1/(2^32)
float sum = (float)hid_rng_next() * scale
+ (float)hid_rng_next() * scale
+ (float)hid_rng_next() * scale
+ (float)hid_rng_next() * scale;
// sum ∈ [0,4), mean=2, stddev≈0.577; normalize to ~N(0,1)
return (sum - 2.0f) * 1.7320508f; // 1/0.577 ≈ √3
}
// Device management helpers
static void handle_device_disconnection(uint8_t dev_addr);
static void handle_hid_device_connection(uint8_t dev_addr, uint8_t itf_protocol);
// Report processing helpers
static bool process_keyboard_report_internal(const hid_keyboard_report_t *report);
static bool process_mouse_report_internal(const hid_mouse_report_t *report);
// Humanization helpers
static void apply_output_humanization(int16_t *x, int16_t *y, int16_t injected_x, int16_t injected_y);
static inline int8_t clamp_i8(int32_t val);
// Stochastic rounding: a value of 0.3 rounds to 1 with 30% probability, 0 with 70%.
// This preserves the statistical mean while making sub-pixel tremor actually visible
// in the output — deterministic roundf() kills any tremor < 0.5px.
static inline int16_t stochastic_round(float v) {
if (v >= 0.0f) {
int16_t floor_v = (int16_t)v;
float frac = v - (float)floor_v;
float r = (float)(hid_rng_next() & 0xFFFF) * (1.0f / 65536.0f);
return floor_v + (r < frac ? 1 : 0);
} else {
float abs_v = -v;
int16_t floor_v = (int16_t)abs_v;
float frac = abs_v - (float)floor_v;
float r = (float)(hid_rng_next() & 0xFFFF) * (1.0f / 65536.0f);
return -(floor_v + (r < frac ? 1 : 0));
}
}
// --- Runtime HID descriptor mirroring storage & helpers ---
// Gaming mice (Razer, Logitech, SteelSeries) can have very large HID
// report descriptors — 500-1000+ bytes with multiple collections for
// mouse, keyboard macros, and vendor-specific features.
#define HID_DESC_BUF_SIZE 1024
static const uint8_t desc_hid_keyboard[] = {
TUD_HID_REPORT_DESC_KEYBOARD(HID_REPORT_ID(REPORT_ID_KEYBOARD))};
// 16-bit mouse descriptor for gaming mice (G703, G Pro Wireless, etc.)
// Matches the G703 Lightspeed structure: 16-bit buttons, 16-bit X/Y, 8-bit wheel/pan
static const uint8_t desc_hid_mouse_16bit[] = {
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,
HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,
HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,
HID_REPORT_ID( REPORT_ID_MOUSE )
HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,
HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,
// Buttons: 16 bits (to match high-end gaming mice)
HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,
HID_USAGE_MIN ( 1 ) ,
HID_USAGE_MAX ( 16 ) ,
HID_LOGICAL_MIN ( 0 ) ,
HID_LOGICAL_MAX ( 1 ) ,
HID_REPORT_COUNT( 16 ) ,
HID_REPORT_SIZE ( 1 ) ,
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,
// X, Y: 16-bit relative (-32767 to +32767)
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,
HID_USAGE ( HID_USAGE_DESKTOP_X ) ,
HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,
HID_LOGICAL_MIN_N ( -32767, 2 ) ,
HID_LOGICAL_MAX_N ( 32767, 2 ) ,
HID_REPORT_COUNT( 2 ) ,
HID_REPORT_SIZE ( 16 ) ,
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,
// Wheel: 8-bit relative
HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,
HID_LOGICAL_MIN ( 0x81 ) ,
HID_LOGICAL_MAX ( 0x7F ) ,
HID_REPORT_COUNT( 1 ) ,
HID_REPORT_SIZE ( 8 ) ,
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,
// AC Pan: 8-bit relative (horizontal scroll)
HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ) ,
HID_USAGE_N ( HID_USAGE_CONSUMER_AC_PAN, 2 ) ,
HID_LOGICAL_MIN ( 0x81 ) ,
HID_LOGICAL_MAX ( 0x7F ) ,
HID_REPORT_COUNT( 1 ) ,
HID_REPORT_SIZE ( 8 ) ,
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,
HID_COLLECTION_END ,
HID_COLLECTION_END
};
static const uint8_t desc_hid_consumer[] = {
TUD_HID_REPORT_DESC_CONSUMER(HID_REPORT_ID(REPORT_ID_CONSUMER_CONTROL))};
// Static fallback concatenated descriptor (used by config descriptor sizeof)
const uint8_t desc_hid_report[] = {
TUD_HID_REPORT_DESC_KEYBOARD(HID_REPORT_ID(REPORT_ID_KEYBOARD)),
TUD_HID_REPORT_DESC_MOUSE(HID_REPORT_ID(REPORT_ID_MOUSE)),
TUD_HID_REPORT_DESC_CONSUMER(HID_REPORT_ID(REPORT_ID_CONSUMER_CONTROL))};
static uint8_t desc_hid_report_runtime[HID_DESC_BUF_SIZE];
static size_t desc_hid_runtime_len = 0;
static bool desc_hid_runtime_valid = false;
static bool using_16bit_output_override = false; // True when we override to 16-bit descriptor
static uint8_t host_mouse_desc[HID_DESC_BUF_SIZE];
static size_t host_mouse_desc_len = 0;
static bool host_mouse_has_report_id = false;
static uint8_t host_mouse_report_id = 0;
// --- Raw report forwarding for gaming mice ---
// When we clone the host mouse's HID report descriptor, we must send reports
// in the exact same binary format. We parse the host descriptor to discover
// the byte layout (offsets & widths of buttons, X, Y, wheel) and then forward
// incoming reports with kmbox/smooth deltas injected in-place.
//
// Layout populated by parse_mouse_report_layout() during tuh_hid_mount_cb.
// Fast-path classification for forward_raw_mouse_report():
// Most gaming mice use byte-aligned 8-bit or 16-bit XY. Classifying the
// layout at parse time lets the hot path skip complex bitwise extraction.
typedef enum {
LAYOUT_GENERIC, // Arbitrary bit-width / non-aligned — full extraction needed
LAYOUT_FAST_8BIT, // buttons[1] + X[i8] + Y[i8] + optional wheel/pan — all byte-aligned
LAYOUT_FAST_16BIT, // buttons[1-2] + X[i16 LE] + Y[i16 LE] — all byte-aligned
} layout_class_t;
typedef struct {
// Total expected report size (excluding report-ID prefix byte)
uint8_t report_size;
// Button byte
uint8_t buttons_offset;
uint8_t buttons_bits; // typically 5 or 8
// X axis
uint8_t x_offset;
bool x_is_16bit;
uint16_t x_bit_offset;
uint8_t x_bits;
uint8_t x_start_byte;
uint8_t x_bit_in_byte;
// Y axis
uint8_t y_offset;
bool y_is_16bit;
uint16_t y_bit_offset;
uint8_t y_bits;
uint8_t y_start_byte;
uint8_t y_bit_in_byte;
// Wheel (vertical scroll)
uint8_t wheel_offset;
bool has_wheel;
// Horizontal scroll / pan
uint8_t pan_offset;
bool has_pan;
// Report ID for the mouse collection (0 = no report IDs in descriptor)
uint8_t mouse_report_id;
bool has_report_id;
bool valid; // true once successfully parsed
layout_class_t layout_class; // fast-path classification (set by classify_layout)
} mouse_report_layout_t;
static mouse_report_layout_t host_mouse_layout = { .valid = false };
static mouse_report_layout_t output_mouse_layout_16bit = {
.report_size = 8,
.buttons_offset = 0,
.buttons_bits = 16,
.x_offset = 2,
.x_is_16bit = true,
.x_bit_offset = 16,
.x_bits = 16,
.x_start_byte = 2,
.x_bit_in_byte = 0,
.y_offset = 4,
.y_is_16bit = true,
.y_bit_offset = 32,
.y_bits = 16,
.y_start_byte = 4,
.y_bit_in_byte = 0,
.wheel_offset = 6,
.has_wheel = true,
.pan_offset = 7,
.has_pan = true,
.mouse_report_id = REPORT_ID_MOUSE,
.has_report_id = true,
.valid = true
};
// Track which dev_addr we've already cloned device/config descriptors for,
// so we only do it once for multi-interface composite devices (e.g. Razer
// Basilisk V3 has 4 HID interfaces, each triggers tuh_hid_mount_cb).
static uint8_t cloned_dev_addr = 0;
// Runtime report IDs — may be remapped to avoid conflicts with host mouse descriptor
static uint8_t runtime_kbd_report_id = REPORT_ID_KEYBOARD;
static uint8_t runtime_consumer_report_id = REPORT_ID_CONSUMER_CONTROL;
// Function to reset string descriptors and cloned state when device is disconnected
static void reset_device_string_descriptors(void) {
memset(attached_manufacturer, 0, sizeof(attached_manufacturer));
memset(attached_product, 0, sizeof(attached_product));
memset(attached_serial, 0, sizeof(attached_serial));
string_descriptors_fetched = false;
attached_has_serial = false;
// Reset cloned descriptor state
host_device_info.valid = false;
host_config_info.valid = false;
host_mouse_layout.valid = false;
host_mouse_desc_len = 0;
host_mouse_has_report_id = false;
host_mouse_report_id = 0;
cloned_dev_addr = 0;
// Reset multi-interface mirroring state
mirrored_itf_count = 0;
expected_hid_itf_count = 0;
mounted_hid_itf_count = 0;
mouse_device_instance = 0;
memset(mirrored_itfs, 0, sizeof(mirrored_itfs));
// Reset vendor report queues and GET_REPORT cache
vendor_fwd_queue.head = vendor_fwd_queue.tail = 0;
set_report_queue.head = set_report_queue.tail = 0;
memset(report_cache, 0, sizeof(report_cache));
memset(&get_report_bridge, 0, sizeof(get_report_bridge));
// Reset extra string descriptor cache
extra_string_count = 0;
max_string_index_seen = 3;
memset(extra_strings, 0, sizeof(extra_strings));
// Reset runtime report IDs to defaults
runtime_kbd_report_id = REPORT_ID_KEYBOARD;
runtime_consumer_report_id = REPORT_ID_CONSUMER_CONTROL;
// Rebuild config descriptor with defaults
build_runtime_hid_report_with_mouse(NULL, 0);
rebuild_configuration_descriptor();
}
//--------------------------------------------------------------------+
// Inline Helper Functions
//--------------------------------------------------------------------+
static __force_inline int8_t clamp_i8(int32_t val) {
if (val > 127) return 127;
if (val < -128) return -128;
return (int8_t)val;
}
//--------------------------------------------------------------------+
// Final Stage Humanization (Applied proportionally to injected movement)
//--------------------------------------------------------------------+
/**
* Apply humanization tremor to final HID output movement.
*
* KEY DESIGN: Human mouse movement is already human — it doesn't need
* additional tremor/jitter. Tremor is only applied proportionally to the
* synthetic (injected) fraction of the total movement. This keeps the
* mouse feeling natural and responsive during normal use while still
* humanizing injected/bot movement.
*
* Blend logic:
* - Pure physical movement (injected == 0): no tremor applied
* - Mixed (physical + injected): tremor scaled by injected fraction
* - Pure injected (no physical): full tremor applied
*
* @param x Pointer to total X movement (modified in place)
* @param y Pointer to total Y movement (modified in place)
* @param injected_x The injected/synthetic X component (smooth queue + kmbox serial)
* @param injected_y The injected/synthetic Y component (smooth queue + kmbox serial)
*/
static void apply_output_humanization(int16_t *x, int16_t *y, int16_t injected_x, int16_t injected_y) {
// Skip if humanization is completely disabled
humanization_mode_t mode = smooth_get_humanization_mode();
if (mode == HUMANIZATION_OFF) {
return;
}
// Get humanization parameters from smooth injection state
int32_t jitter_amount_fp;
bool jitter_enabled;
smooth_get_humanization_params(&jitter_amount_fp, &jitter_enabled);
if (!jitter_enabled) {
return;
}
// --- Calculate blend ratio: how much of this movement is synthetic? ---
// If there's no injected component, the user is just moving their mouse.
// Human movement is already human — don't add tremor to it.
float inject_mag = sqrtf((float)injected_x * injected_x + (float)injected_y * injected_y);
// No injected movement — nothing to humanize. Do NOT apply tremor.
// This prevents phantom tremor after injection queue drains (the "shaking" bug).
if (inject_mag < 0.5f) {
return;
}
float total_mag = sqrtf((float)(*x) * (*x) + (float)(*y) * (*y));
// No movement at all — skip (don't generate idle tremor on pure physical idle)
if (total_mag < 0.5f && inject_mag < 0.5f) {
return;
}
// Blend ratio: 0.0 = pure physical, 1.0 = pure injected
float blend;
if (total_mag < 0.5f) {
// Total is ~zero but inject is non-zero (rare edge: physical cancelled inject)
blend = 1.0f;
} else {
blend = inject_mag / total_mag;
// Clamp to [0, 1] — inject_mag can exceed total_mag if they oppose
if (blend > 1.0f) blend = 1.0f;
}
// If movement is almost entirely physical, skip tremor entirely
// This threshold avoids wasting FPU cycles for negligible tremor
if (blend < 0.05f) {
return;
}
// --- Calculate tremor magnitude ---
float magnitude = total_mag;
// Mode-dependent intensity scaling
// MICRO was 0.5x which, combined with 0.5px base jitter, gave only 0.25px
// effective tremor — too small to survive even stochastic rounding consistently.
float mode_scale = 1.0f;
switch (mode) {
case HUMANIZATION_MICRO:
mode_scale = 0.75f;
break;
case HUMANIZATION_FULL:
mode_scale = 1.0f;
break;
default:
break;
}
// Calculate tremor scale with blend factor
float movement_scale = humanization_jitter_scale(magnitude);
float base_jitter = (float)jitter_amount_fp / 65536.0f; // Convert from 16.16 fixed-point
float tremor_scale = base_jitter * movement_scale * mode_scale * blend;
// Scale noise DOWN at low velocities to prevent overwhelming the signal.
// At 1-2 count deltas, ±1 of tremor is 50-100% perturbation, creating
// chaotic scribble instead of smooth slow transitions.
// Ramp: 0 at 0px → full at 4px
float low_speed_scale = fminf(1.0f, magnitude / 4.0f);
tremor_scale *= low_speed_scale;
// Get runtime tremor (layered oscillators + noise)
float tremor_x, tremor_y;
humanization_get_tremor(tremor_scale, &tremor_x, &tremor_y);
if (magnitude > 2.0f) {
// Moving cursor: perpendicular + parallel decomposition
float fx = (float)(*x);
float fy = (float)(*y);
float norm_x = fx / magnitude;
float norm_y = fy / magnitude;
// Perpendicular component (tremor_y) - primary humanization signal
float perp_dx = -norm_y * tremor_y;
float perp_dy = norm_x * tremor_y;
// Parallel component (tremor_x) - speed variation (smaller)
float para_dx = norm_x * tremor_x * 0.3f;
float para_dy = norm_y * tremor_x * 0.3f;
// Apply tremor to output (stochastic rounding so sub-pixel tremor
// probabilistically produces visible ±1 counts instead of always 0)
*x = (int16_t)(*x + stochastic_round(perp_dx + para_dx));
*y = (int16_t)(*y + stochastic_round(perp_dy + para_dy));
} else {
// Small/idle movement with injection active: apply tremor as raw X/Y
*x += stochastic_round(tremor_x);
*y += stochastic_round(tremor_y);
}
}
// Sensor noise: gaussian-based quantization noise with stochastic rounding.
// Real optical sensors have continuous noise that maps to discrete count
// perturbations. Using a continuous gaussian source ensures consecutive
// identical underlying deltas get DIFFERENT noise samples, reducing repeats.
// Always-±1 binary noise has P(match)=50% — worse than {-1,0,+1} was.
static inline int16_t apply_sensor_noise(int16_t value) {
if (value == 0) return 0; // stationary sensor produces no noise
// Gaussian with stddev ~0.7 → mostly ±1, sometimes ±2 or 0.
// Continuous source means consecutive values are decorrelated.
float noise = hid_rng_gaussian() * 0.7f;
return value + stochastic_round(noise);
}
// Minimal HID descriptor parser — extracts report field layout for the mouse
// collection so we know where to inject deltas in raw reports.
// This is intentionally simple and handles the common gaming mouse patterns:
// buttons (1-3 bytes), X (8/12/16 bit), Y (8/12/16 bit), wheel, pan.
static void parse_mouse_report_layout(const uint8_t *desc, size_t len,
mouse_report_layout_t *layout)
{
memset(layout, 0, sizeof(*layout));
layout->valid = false;
if (!desc || len < 4) return;
// HID descriptor state machine — minimal implementation
bool in_mouse_collection = false;
uint16_t usage_page = 0; // 16-bit: vendor pages (0xFF00) truncate in uint8_t
uint8_t usage = 0;
uint32_t bit_offset = 0; // current bit position in the report
uint32_t mouse_bit_max = 0; // track highest bit offset within mouse collection
uint8_t report_size_bits = 0; // current REPORT_SIZE
uint8_t report_count = 0; // current REPORT_COUNT
int collection_depth = 0;
int mouse_collection_depth = -1;
uint8_t current_report_id = 0; // current Report ID context
uint8_t mouse_report_id = 0; // Report ID that contains the mouse collection
bool found_mouse_report_id = false;
// Track what usages we've seen before each INPUT item
#define MAX_USAGES 16
uint8_t usage_stack[MAX_USAGES];
uint8_t usage_stack_count = 0;
bool has_usage_range = false;
uint8_t usage_min = 0;
size_t i = 0;
while (i < len) {
uint8_t item = desc[i];
uint8_t item_size = item & 0x03;
if (item_size == 3) item_size = 4; // size=3 means 4 bytes
if (i + 1 + item_size > len) break;
uint32_t value = 0;
for (uint8_t b = 0; b < item_size; b++) {
value |= (uint32_t)desc[i + 1 + b] << (b * 8);
}
uint8_t item_tag = item & 0xFC; // tag + type
switch (item_tag) {
case 0x04: // Usage Page (Global)
usage_page = (uint16_t)value;
break;
case 0x08: // Usage (Local)
if (usage_stack_count < MAX_USAGES) {
usage_stack[usage_stack_count++] = (uint8_t)value;
}
usage = (uint8_t)value;
break;
case 0x18: // Usage Minimum (Local)
has_usage_range = true;
usage_min = (uint8_t)value;
break;
case 0x28: // Usage Maximum (Local)
break;
case 0xA0: // Collection
collection_depth++;
if (usage_page == HID_USAGE_PAGE_DESKTOP && usage == HID_USAGE_DESKTOP_MOUSE) {
in_mouse_collection = true;
mouse_collection_depth = collection_depth;
// Record which Report ID contains the mouse collection
mouse_report_id = current_report_id;
found_mouse_report_id = (current_report_id != 0);
}
break;
case 0xC0: // End Collection
if (in_mouse_collection && collection_depth == mouse_collection_depth) {
// Exiting the mouse collection — record max bit offset for size calc
if (bit_offset > mouse_bit_max) {
mouse_bit_max = bit_offset;
}
in_mouse_collection = false;
mouse_collection_depth = -1;
}
collection_depth--;
break;
case 0x74: // Report Size (Global)
report_size_bits = (uint8_t)value;
break;
case 0x94: // Report Count (Global)
report_count = (uint8_t)value;
break;
case 0x80: // Input (Main)
{
if (in_mouse_collection) {
bool is_constant = (value & 0x01); // bit 0: constant vs data
uint32_t total_bits = (uint32_t)report_size_bits * report_count;
if (!is_constant) {
// Determine what this input field is based on usage context
bool is_desktop_range = (has_usage_range && usage_page == HID_USAGE_PAGE_DESKTOP);
if (usage_page == HID_USAGE_PAGE_BUTTON || (has_usage_range && !is_desktop_range)) {
// Button field
layout->buttons_offset = bit_offset / 8;
layout->buttons_bits = report_count;
} else if (usage_page == HID_USAGE_PAGE_DESKTOP) {
// Process usages (explicit stack or range-based)
for (uint8_t u = 0; u < report_count; u++) {
uint8_t cur_usage = 0;
if (has_usage_range) {
cur_usage = usage_min + u;
} else if (u < usage_stack_count) {
cur_usage = usage_stack[u];
} else {
// No more usages in stack vs report count
break;
}
uint32_t field_bit_offset = bit_offset + (u * report_size_bits);
uint8_t byte_off = field_bit_offset / 8;
if (cur_usage == HID_USAGE_DESKTOP_X) {
layout->x_offset = byte_off;
layout->x_is_16bit = (report_size_bits >= 16);
layout->x_bit_offset = (uint16_t)field_bit_offset;
layout->x_bits = report_size_bits;
layout->x_start_byte = byte_off;
layout->x_bit_in_byte = field_bit_offset % 8;
} else if (cur_usage == HID_USAGE_DESKTOP_Y) {
layout->y_offset = byte_off;
layout->y_is_16bit = (report_size_bits >= 16);
layout->y_bit_offset = (uint16_t)field_bit_offset;
layout->y_bits = report_size_bits;
layout->y_start_byte = byte_off;
layout->y_bit_in_byte = field_bit_offset % 8;
} else if (cur_usage == HID_USAGE_DESKTOP_WHEEL) {
layout->wheel_offset = byte_off;
layout->has_wheel = true;
}