Repository navigation
Expand file tree
/
Copy pathInterceptor.cpp
More file actions
2408 lines (2372 loc) · 150 KB
/
Copy pathInterceptor.cpp
File metadata and controls
2408 lines (2372 loc) · 150 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
#ifndef IC_SDK_INTERNAL
#define IC_SDK_INTERNAL
#endif
#include "Interceptor.h"
// Interceptor SDK implementation. No other project files are required.
// ---- Interceptor.cpp ----
// ---- ContextInternal.h ----
// Wire-compatibility entry point for the archived regression harnesses only.
// Applications use the single public Create_Context() declaration.
namespace Interceptor { namespace Detail {
struct Preparation_Options {DWORD timeout=0;HANDLE stop_event=nullptr;};
Context_Result Create_Selected_Context(std::uint8_t mask,std::uint8_t controllers,const Preparation_Options& wait={});
}}
// ---- internal/CaptureAll.h ----
// Optional ABI4 extension. Legacy CREATE endpoints retain their exact contract.
// This endpoint reserves all compiled families, including empty/pending ones.
// Preparation completes asynchronously as each source becomes capturable.
#define IOCTL_IC_CREATE_ALL IC_IOCTL(0xA2E)
#define IOCTL_IC_CONTEXT_DEVICES IC_IOCTL(0xA2F)
// ---- NativePolicy.h ----
// Shared by initialization and its pure tests. No device/registry access here.
// ---- internal/XusbMirrorIdentity.h ----
// xusb22 assigns the IG component to the translated HID view; it is not
// necessarily 00, nor the ViGEm target index. Parse exactly two hex digits and
// a component boundary. Parent identity and descriptor validation remain
// separate mandatory checks; the group alone never associates two devices.
static __inline int IcXusbMirrorHex(uint16_t c) {
if(c>='0'&&c<='9')return (int)(c-'0');
if(c>='a'&&c<='f')return (int)(c-'a'+10);
if(c>='A'&&c<='F')return (int)(c-'A'+10);
return -1;
}
// Parse the product component only, never a substring or a truncated ID.
// VID/PID identify a device; the xusb22 service, wired compatible IDs and
// verified mirror descriptor establish its supported protocol separately.
static __inline int IcXusbProduct(const uint16_t* text,uint32_t chars,int usb,uint16_t* vid,uint16_t* pid) {
const char* prefix=usb?"USB\\VID_":"HID\\VID_";
uint32_t i;uint16_t v=0,p=0;
if(!text || chars<21)return 0;
for(i=0;i<21;++i) {
uint16_t c=text[i];int digit;
if(c>='a'&&c<='z')c=(uint16_t)(c-'a'+'A');
if((i>=8 && i<12)||(i>=17 && i<21)) {
digit=IcXusbMirrorHex(c);if(digit<0)return 0;
if(i<12)v=(uint16_t)((v<<4)|digit);else p=(uint16_t)((p<<4)|digit);
} else if(c!=(uint16_t)(i<8?prefix[i]:"&PID_"[i-12]))return 0;
}
if(chars>21 && text[21]!='&' && text[21]!='\\')return 0;
if(vid)*vid=v;if(pid)*pid=p;return 1;
}
static __inline int IcXusbMirrorGroup(const uint16_t* text,uint32_t chars,int usb) {
uint32_t i;int high,low;
if(chars<27 || !IcXusbProduct(text,chars,usb,0,0))return -1;
for(i=21;i<25;++i){uint16_t c=text[i];if(c>='a'&&c<='z')c=(uint16_t)(c-'a'+'A');if(c!=(uint16_t)"&IG_"[i-21])return -1;}
high=IcXusbMirrorHex(text[25]);low=IcXusbMirrorHex(text[26]);
if(high<0||low<0||(chars>27&&text[27]!='&'&&text[27]!='\\'))return -1;
return high*16+low;
}
#include <algorithm>
#include <atomic>
#include <string>
#include <vector>
namespace Interceptor { namespace Policy {
inline bool Equal(const std::wstring& a,const wchar_t* b) {return _wcsicmp(a.c_str(),b)==0;}
inline bool Has(const std::vector<std::wstring>& names,const wchar_t* value) {
return std::any_of(names.begin(),names.end(),[&](const auto& name){return Equal(name,value);});
}
inline bool ForeignInterceptor(const std::wstring& name) {
return !Equal(name,IC_SDK_SERVICE) && (Equal(name,L"Interceptor") ||
Equal(name,L"InterceptorKeyboardMouse") || Equal(name,L"InterceptorGamepadController"));
}
inline bool ForeignFilters(const std::vector<std::wstring>& names) {
return std::any_of(names.begin(),names.end(),[](const auto& name){return ForeignInterceptor(name);});
}
enum class ClassAssociation { PerDevice, ExistingXusbUpper, Conflict };
inline ClassAssociation ClassFilterAssociation(std::uint32_t transport,
const std::vector<std::wstring>& deviceUpper,const std::vector<std::wstring>& deviceLower,
const std::vector<std::wstring>& classUpper,const std::vector<std::wstring>& classLower) {
if(ForeignFilters(deviceUpper)||ForeignFilters(deviceLower)||ForeignFilters(classUpper)||ForeignFilters(classLower))
return ClassAssociation::Conflict;
const auto count=[](const auto& names){return std::count_if(names.begin(),names.end(),
[](const auto& name){return Equal(name,IC_SDK_SERVICE);});};
const auto upper=count(classUpper),lower=count(classLower);
if(!upper&&!lower)return ClassAssociation::PerDevice;
// The native XUSB dispatch supports an upper filter above xusb22. A class
// registration and a device registration would load our service twice.
// XInputHID requires device-list ordering before xinputhid; GIP dispatch
// currently requires the per-device LowerFilters property. Class placement
// alone cannot establish either of those supported contracts.
if(transport==IC_CONTROLLER_XUSB && upper==1 && !lower &&
!count(deviceUpper) && !count(deviceLower))return ClassAssociation::ExistingXusbUpper;
return ClassAssociation::Conflict;
}
inline bool ValidCapabilities(const IC_CAPABILITIES& c,std::size_t bytes) {
return bytes==sizeof(c) && c.size==sizeof(c) && c.version==IC_CAPABILITIES_VERSION && c.abi_version==IC_VERSION &&
!(c.input_mask&~IC_BOTH) && !(c.controller_mask&~15u) && !c.flags && !c.reserved[0] && !c.reserved[1] && !c.reserved[2] &&
c.max_devices && c.max_devices<=IC_MAX_DEVICES && c.queue_capacity==IC_CAPACITY && c.max_send==IC_MAX_SEND &&
c.hid_report_max==(c.controller_mask?IC_HID_REPORT_MAX:0);
}
inline std::uint32_t SupportedControllers(const IC_CAPABILITIES& c) {
auto mask=c.controller_mask&IC_CONTROLLER_HID;
if(c.xusb_profiles&(IC_PROFILE_XUSB_WIRED_028E|IC_PROFILE_XUSB_WIRED_COMPATIBLE))mask|=c.controller_mask&IC_CONTROLLER_XUSB;
if(c.xinputhid_profiles&IC_PROFILE_XINPUTHID_GENERIC6)mask|=c.controller_mask&IC_CONTROLLER_XINPUTHID;
if(c.gip_profiles&IC_PROFILE_GIP_USB_GAMEPAD14)mask|=c.controller_mask&IC_CONTROLLER_GIP;
return mask;
}
inline bool Usb028e(const std::wstring& id) {
constexpr auto prefix=L"USB\\VID_045E&PID_028E";constexpr std::size_t length=21;
return id.size()>=length && !_wcsnicmp(id.c_str(),prefix,length) &&
(id.size()==length || id[length]==L'&' || id[length]==L'\\');
}
struct NativeNode {
std::wstring instance,service,deviceClass;
std::vector<std::wstring> hardware,compatible,upper;
std::uint32_t propertyFlags=UINT32_MAX;
bool blockedAncestry=true;
};
inline bool SameProduct(const std::wstring& a,bool aUsb,const std::wstring& b,bool bUsb) {
uint16_t av=0,ap=0,bv=0,bp=0;
return a.size()<=UINT32_MAX && b.size()<=UINT32_MAX &&
IcXusbProduct(reinterpret_cast<const uint16_t*>(a.data()),static_cast<uint32_t>(a.size()),aUsb,&av,&ap) &&
IcXusbProduct(reinterpret_cast<const uint16_t*>(b.data()),static_cast<uint32_t>(b.size()),bUsb,&bv,&bp) && av==bv && ap==bp;
}
inline bool XusbProfileAvailable(const NativeNode& n,const IC_CAPABILITIES& c) {
return (c.xusb_profiles&IC_PROFILE_XUSB_WIRED_COMPATIBLE) ||
((c.xusb_profiles&IC_PROFILE_XUSB_WIRED_028E) && Usb028e(n.instance));
}
inline std::uint32_t Transport(const NativeNode& n) {
const bool usb=!_wcsnicmp(n.instance.c_str(),L"USB\\",4);
const bool hid=!_wcsnicmp(n.instance.c_str(),L"HID\\",4);
if(usb && Equal(n.deviceClass,L"{D61CA365-5AF4-4486-998B-9DB4734C6CA3}") && Equal(n.service,L"xusb22") &&
std::any_of(n.hardware.begin(),n.hardware.end(),[&](const auto& id){return SameProduct(n.instance,true,id,true);}) &&
(Usb028e(n.instance) || (Has(n.compatible,L"USB\\MS_COMP_XUSB10") &&
Has(n.compatible,L"USB\\Class_ff&SubClass_5d&Prot_01"))))return IC_CONTROLLER_XUSB;
if(hid && n.propertyFlags==6 && !n.blockedAncestry &&
Equal(n.deviceClass,L"{745A17A0-74D3-11D0-B6FE-00A0C90F57DA}") && Has(n.upper,L"xinputhid")) {
for(const auto& ids:{&n.hardware,&n.compatible})for(const auto& id:*ids)
if(Equal(id,L"HID_DEVICE_UP:0001_U:0004") || Equal(id,L"HID_DEVICE_UP:0001_U:0005") || Equal(id,L"HID_DEVICE_UP:0001_U:0008"))return IC_CONTROLLER_XINPUTHID;
}
if(usb && Equal(n.deviceClass,L"{05F5CFE2-4733-4950-A6BB-07AAD01A3A84}") && Equal(n.service,L"dc1-controller") &&
Has(n.compatible,L"USB\\MS_COMP_XGIP10"))return IC_CONTROLLER_GIP;
return 0;
}
inline bool ComponentPrefix(const std::wstring& id,const wchar_t* prefix) {
const auto length=wcslen(prefix);
return id.size()>=length && !_wcsnicmp(id.c_str(),prefix,length) &&
(id.size()==length || id[length]==L'&' || id[length]==L'\\');
}
inline int XusbMirrorGroup(const std::wstring& id,bool usb=false) {
if(id.size()>UINT32_MAX)return -1;
return IcXusbMirrorGroup(reinterpret_cast<const uint16_t*>(id.data()),static_cast<uint32_t>(id.size()),usb?1:0);
}
inline bool XusbMirror(const NativeNode& collection,const NativeNode& hid,const NativeNode& xusb) {
const int group=XusbMirrorGroup(collection.instance);
if(group<0 || XusbMirrorGroup(hid.instance,true)!=group ||
!SameProduct(collection.instance,false,hid.instance,true) || !SameProduct(hid.instance,true,xusb.instance,true) ||
!Equal(collection.deviceClass,L"{745A17A0-74D3-11D0-B6FE-00A0C90F57DA}") ||
Has(collection.upper,L"xinputhid") ||
!Equal(hid.service,L"HidUsb") ||
!Equal(hid.deviceClass,L"{745A17A0-74D3-11D0-B6FE-00A0C90F57DA}") || Transport(xusb)!=IC_CONTROLLER_XUSB)return false;
const bool gamepad=Has(collection.hardware,L"HID_DEVICE_UP:0001_U:0005") || Has(collection.compatible,L"HID_DEVICE_UP:0001_U:0005");
return gamepad && std::any_of(hid.hardware.begin(),hid.hardware.end(),[&](const auto& id){return XusbMirrorGroup(id,true)==group && SameProduct(id,true,hid.instance,true);}) &&
std::any_of(collection.hardware.begin(),collection.hardware.end(),[&](const auto& id){return XusbMirrorGroup(id)==group && SameProduct(id,false,collection.instance,false);});
}
inline std::vector<std::wstring> Filters(const std::vector<std::wstring>& original,std::uint32_t transport,bool remove) {
std::vector<std::wstring> out;out.reserve(original.size()+1);bool inserted=false;
for(const auto& name:original) {
if(Equal(name,IC_SDK_SERVICE))continue; // Remove duplicates and correct a previous wrong position.
if(!remove && transport==IC_CONTROLLER_XINPUTHID && Equal(name,L"xinputhid") && !inserted) {
out.emplace_back(IC_SDK_SERVICE);inserted=true;
}
out.push_back(name);
}
if(!remove && !inserted)out.emplace_back(IC_SDK_SERVICE);
return out;
}
}}
// ---- SendBatch.h ----
#include <algorithm>
#include <utility>
namespace Interceptor::Detail {
// A failed factory destroys its partial resources before returning. The cache
// only becomes ready after the complete source set has been prepared.
template<class Resources> class SourceCache {
Resources resources_;
bool ready_=false;
public:
template<class Factory> void Prepare(Factory&& factory) {
if(ready_)return;
auto replacement=factory();
resources_=std::move(replacement);ready_=true;
}
void Reset() noexcept {resources_.clear();ready_=false;}
};
inline bool SourceUnavailable(DWORD error) noexcept {
return error==ERROR_DEVICE_NOT_CONNECTED || error==ERROR_NOT_READY;
}
// send(offset,count) reports an accepted prefix. Refresh is allowed once per
// public call, only for a remaining suffix; a committed input is never resent.
template<class Submit,class Refresh>
Send_Result SendBatches(std::size_t count,Submit&& send,Refresh&& refresh,bool canRefresh) {
std::size_t accepted=0;bool refreshed=false;
while(accepted<count) {
const auto n=std::min<std::size_t>(IC_MAX_SEND,count-accepted);
const auto result=send(accepted,n);
if(result.accepted>n)return {accepted,ERROR_INVALID_DATA};
accepted+=result.accepted;
if(result.error) {
if(canRefresh && !refreshed && accepted<count && SourceUnavailable(result.error)) {
refreshed=true;
const DWORD error=refresh();
if(error)return {accepted,error};
continue;
}
return {accepted,result.error};
}
if(result.accepted!=n)return {accepted,ERROR_INVALID_DATA};
}
return {accepted,ERROR_SUCCESS};
}
}
// ---- ContextPreparation.h ----
#include <Windows.h>
#include <algorithm>
#include <system_error>
namespace Interceptor { namespace Detail {
// Shared by CREATE and host-safe fault tests. Never restart a revoked capture:
// this loop is used only before a context has been successfully acquired.
template<class Attempt,class Clock,class Pause>
void PrepareContext(Attempt attempt,Clock now,Pause pause,DWORD timeout) {
const auto started=now();
for(;;) {
// A zero-duration pause checks cancellation before the first attempt.
pause(0);
try {attempt();return;}
catch(const std::system_error& error) {
if(error.code().value()!=ERROR_NOT_READY || !timeout)throw;
const auto elapsed=now()-started;
if(elapsed>=timeout)throw std::system_error(ERROR_TIMEOUT,std::system_category(),"Device present but capture preparation timed out");
pause(static_cast<DWORD>(std::min<ULONGLONG>(100,timeout-elapsed)));
}
}
}
}}
// ---- InputProcessing.h ----
#include <system_error>
namespace Interceptor::Detail {
// Shared with the real processor and its fault-injection tests. A partial
// send is never replayed: the public owning wrapper closes capture on error.
template<class T,class Read,class Send>
std::size_t ProcessBatch(std::vector<T>& inputs,Read&& read,Send&& send,bool (*handler)(void*,T&),void* user) {
read(inputs);
const auto received=inputs.size();std::size_t kept=0;
for(std::size_t i=0;i<received;++i) {
if(handler && !handler(user,inputs[i]))continue;
if(kept!=i)inputs[kept]=inputs[i];
++kept;
}
if(kept) {
const auto result=send(Detail::Input_View<const T>(inputs.data(),kept));
if(result.error || result.accepted!=kept)
throw std::system_error(static_cast<int>(result.error?result.error:ERROR_WRITE_FAULT),std::system_category(),"Forward processed input");
}
return received;
}
}
// ---- internal/InputRead.h ----
// Selected input-read request. Queue implementation is private to the driver.
#define IC_GET_PEEK 1u
typedef struct IC_GET_SELECT {IC_GET base;uint32_t device,flags;} IC_GET_SELECT;
#if defined(__cplusplus)
static_assert(sizeof(IC_GET_SELECT)==16,"Selected GET request ABI");
#endif
// ---- internal/DeviceAvailability.h ----
// One interpretation for all six backends. Ready describes capture startup,
// never recent activity. A GIP report is required to validate its wire shape,
// not to prove the user moved a stick. An idle established source stays ready.
static __inline void IcDeviceAvailability(IC_DEVICE_QUERY_RESULT* result,uint32_t extra) {
const uint32_t f=result->flags;uint32_t reasons=extra,state;
if(!(f&1u) || extra) {
if(result->type<=IC_TYPE_MOUSE) {
if(!(f&16u))reasons|=IC_DEVICE_WAIT_CONNECTION;
if(!(f&2u) || !(f&1u))reasons|=IC_DEVICE_WAIT_READER;
} else {
if(!(f&4u))reasons|=IC_DEVICE_WAIT_POWER;
if(!(f&2u))reasons|=IC_DEVICE_WAIT_READER;
if(result->type==IC_TYPE_CONTROLLER_GIP) {
if(!(f&128u))reasons|=IC_DEVICE_WAIT_HELLO;
if(!(f&512u))reasons|=IC_DEVICE_WAIT_METADATA;
if(!(f&8u))reasons|=IC_DEVICE_WAIT_FIRST_REPORT;
if((f&64u) || ((f&512u) && !(f&1024u)))reasons|=IC_DEVICE_PROFILE_REJECTED;
} else if(result->type==IC_TYPE_CONTROLLER_HID || result->type==IC_TYPE_CONTROLLER_XINPUTHID) {
if(!(f&16u))reasons|=IC_DEVICE_WAIT_PROFILE;
if(f&64u)reasons|=IC_DEVICE_TRANSPARENT;
} else if(!(f&1u) && !extra)reasons|=IC_DEVICE_WAIT_READER;
}
}
if((f&1u) && !reasons)state=IC_DEVICE_READY;
else if(reasons&IC_DEVICE_PROFILE_REJECTED)state=IC_DEVICE_UNSUPPORTED;
else if(reasons&(IC_DEVICE_WAIT_POWER|IC_DEVICE_TRANSPARENT))state=IC_DEVICE_UNAVAILABLE;
else state=IC_DEVICE_PREPARING;
result->reserved[0]=state;result->reserved[1]=reasons;
// In both query versions, bit 0 must agree with actual capture readiness.
if(state!=IC_DEVICE_READY)result->flags&=~1u;
}
// ---- internal/ControllerXusbMirror.h ----
// Private source for the legacy HID child of a native XUSB gamepad. It does not
// expose a second capture queue: its lifetime and delivery follow XUSB ownership.
#define IC_XUSB_MIRROR_INTERFACE_GUID {0x547198fb,0x889e,0x410d,{0x82,0xf1,0x5e,0x0a,0xc4,0x49,0xa7,0xfd}}
#define IOCTL_IC_XUSB_MIRROR_SOURCE IC_IOCTL(0xA15)
#define IC_XUSB_MIRROR_HID_PARENT_VALUE L"InterceptorKeyboardMouseXusbHidParent"
#define IC_XUSB_MIRROR_PARENT_VALUE L"InterceptorKeyboardMouseXusbParent"
#define IC_XUSB_MIRROR_INSTANCE_CHARS 200u
#include <algorithm>
#include <SetupAPI.h>
#include <hidsdi.h>
#include <hidpi.h>
// ---- HidCodec.h ----
#include <hidsdi.h>
#include <hidpi.h>
#include <array>
namespace Interceptor::Detail {
// The replaceable parser boundary is used by pure tests. Production uses HidP.
struct Hid_Parser {
decltype(&HidP_GetCaps) caps=HidP_GetCaps;
decltype(&HidP_GetValueCaps) values=HidP_GetValueCaps;
decltype(&HidP_GetButtonCaps) buttons=HidP_GetButtonCaps;
decltype(&HidP_GetUsageValueArray) array=HidP_GetUsageValueArray;
decltype(&HidP_GetData) data=HidP_GetData;
decltype(&HidP_SetData) setData=HidP_SetData;
decltype(&HidP_MaxDataListLength) maxData=HidP_MaxDataListLength;
decltype(&HidP_GetLinkCollectionNodes) collections=HidP_GetLinkCollectionNodes;
};
inline Hid_Parser hidParser;
struct Hid_Codec {
struct Value {HIDP_VALUE_CAPS cap;USHORT usage,index;std::uint32_t bit_offset=0;NTSTATUS array_status=HIDP_STATUS_SUCCESS;Hid_Value_Kind kind=Hid_Value_Kind::Value;};
struct Button {USHORT page,usage,link;UCHAR report;USHORT index;bool trigger=false;};
struct Report {
std::vector<std::size_t> values,buttons;
// Exact output reservations avoid geometric allocation/copy growth on
// freshly returned public inputs. Index by Hid_Value_Kind, then binary.
std::array<std::size_t,5> counts{};
};
std::vector<std::uint8_t> descriptor;
std::vector<Value> valueDefs;
std::vector<Button> buttonDefs;
std::array<Report,256> reports;
HIDP_CAPS caps{};
ULONG maxDataCount=0;
Hid_Parser parser;
static std::shared_ptr<const Hid_Codec> Create(std::vector<std::uint8_t>);
static void Decode(const std::shared_ptr<const Hid_Codec>&,Hid_Decoded_Input&,const std::uint8_t*,std::uint32_t,std::uint32_t);
static DWORD Encode(const Hid_Decoded_Input&,std::uint8_t*,std::uint32_t,std::uint32_t);
};
}
#pragma comment(lib,"setupapi.lib")
#pragma comment(lib,"hid.lib")
#include <mutex>
#include <stdexcept>
#include <system_error>
namespace Interceptor {
namespace {
[[noreturn]] void Fail(const char* operation,DWORD error=GetLastError()) {
if(error==IC_ERROR_TRIAL_EXPIRED)operation="Interceptor one-hour trial expired; restart Windows to use capture again";
throw std::system_error(static_cast<int>(error),std::system_category(),operation);
}
struct Handle {
HANDLE value=INVALID_HANDLE_VALUE;
~Handle() { if(value && value!=INVALID_HANDLE_VALUE)CloseHandle(value); }
Handle()=default;Handle(const Handle&)=delete;Handle& operator=(const Handle&)=delete;
};
void Open(Handle& h) {
h.value=CreateFileW(IC_SDK_DOS_DEVICE,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,
nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if(h.value==INVALID_HANDLE_VALUE)Fail("Open Interceptor (install driver and run as administrator)");
}
DWORD Io(HANDLE handle,DWORD code,const void* in,DWORD inBytes,void* out,DWORD outBytes) {
DWORD bytes=0;
if(!DeviceIoControl(handle,code,const_cast<void*>(in),inBytes,out,outBytes,&bytes,nullptr))Fail("Interceptor DeviceIoControl");
return bytes;
}
IC_CAPABILITIES Capabilities(HANDLE handle) {
IC_CAPABILITIES c{};
const auto bytes=Io(handle,IOCTL_IC_CAPABILITIES,nullptr,0,&c,sizeof(c));
if(!Policy::ValidCapabilities(c,bytes))Fail("Invalid Interceptor capabilities",ERROR_REVISION_MISMATCH);
return c;
}
using SourceHandles=std::vector<std::unique_ptr<Handle>>;
void ValidateControllerCapabilities(HANDLE driver,std::uint8_t controllers,std::uint8_t inputs=0) {
if(!(controllers&~Controller_Hid))return; // Keep compatibility with ABI4 HID-only drivers.
IC_CAPABILITIES capabilities{};
try {capabilities=Capabilities(driver);}
catch(const std::system_error& e) {
if(e.code().value()==ERROR_INVALID_FUNCTION)Fail("Loaded driver has no native capabilities endpoint",ERROR_NOT_SUPPORTED);
throw;
}
if((controllers&~Policy::SupportedControllers(capabilities)) || (inputs&~capabilities.input_mask))
Fail("Controller profile unavailable in the loaded driver",ERROR_NOT_SUPPORTED);
}
SourceHandles OpenControllerSources(std::uint8_t controllers,bool availableOnly=false) {
SourceHandles sources;
const GUID sourceGuids[]={IC_HID_INTERFACE_GUID,IC_XUSB_INTERFACE_GUID,IC_XINPUTHID_INTERFACE_GUID,IC_XUSB_MIRROR_INTERFACE_GUID};
const DWORD sourceIoctls[]={IOCTL_IC_HID_SOURCE,IOCTL_IC_XUSB_SOURCE,IOCTL_IC_XINPUTHID_SOURCE,IOCTL_IC_XUSB_MIRROR_SOURCE};
// GIP is driven by Windows USB URBs. It has no user-mode source handle.
for(unsigned native=0;native<4;++native)if(controllers&(native==3?Controller_Xinput:1u<<native)) {
const auto before=sources.size();
struct Set {HDEVINFO value;~Set(){if(value!=INVALID_HANDLE_VALUE)SetupDiDestroyDeviceInfoList(value);}};
Set set{SetupDiGetClassDevsW(&sourceGuids[native],nullptr,nullptr,DIGCF_PRESENT|DIGCF_DEVICEINTERFACE)};
if(set.value==INVALID_HANDLE_VALUE)Fail("Enumerate controller filters");
for(DWORD i=0;;++i) {
SP_DEVICE_INTERFACE_DATA item{};item.cbSize=sizeof(item);
if(!SetupDiEnumDeviceInterfaces(set.value,nullptr,&sourceGuids[native],i,&item)) {
if(GetLastError()!=ERROR_NO_MORE_ITEMS)Fail("Enumerate controller interface");break;
}
DWORD required=0;SetupDiGetDeviceInterfaceDetailW(set.value,&item,nullptr,0,&required,nullptr);
if(GetLastError()!=ERROR_INSUFFICIENT_BUFFER || required<sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W))
Fail("Query controller path size",ERROR_INVALID_DATA);
std::vector<BYTE> path(required);auto* detail=reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA_W*>(path.data());
detail->cbSize=sizeof(*detail);
if(!SetupDiGetDeviceInterfaceDetailW(set.value,&item,detail,required,nullptr,nullptr))Fail("Query controller path");
auto source=std::make_unique<Handle>();
source->value=CreateFileW(detail->DevicePath,GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,nullptr,OPEN_EXISTING,0,nullptr);
if(source->value==INVALID_HANDLE_VALUE) {
const auto error=GetLastError();
if(availableOnly && (error==ERROR_DEVICE_NOT_CONNECTED || error==ERROR_NOT_READY || error==ERROR_FILE_NOT_FOUND || error==ERROR_GEN_FAILURE))continue;
Fail("Open controller source",error);
}
try {Io(source->value,sourceIoctls[native],nullptr,0,nullptr,0);}
catch(const std::system_error& error) {
// Collection filters explicitly report transparent unsupported
// profiles. They must not disable capture of other supported
// HID/XInputHID devices. Keep other failures visible, and never
// omit a native XUSB mirror required for complete isolation.
if((native==0 || native==2) && error.code().value()==ERROR_NOT_SUPPORTED)continue;
if(availableOnly && (error.code().value()==ERROR_NOT_SUPPORTED || error.code().value()==ERROR_NOT_READY || error.code().value()==ERROR_DEVICE_NOT_CONNECTED))continue;
throw;
}
sources.push_back(std::move(source));
}
if(!availableOnly && sources.size()==before)Fail("No active controller filters for requested transport",ERROR_DEVICE_NOT_CONNECTED);
}
return sources;
}
unsigned ControllerSendIndex(DWORD code) noexcept {
switch(code) {
case IOCTL_IC_SEND_HID:return 0;
case IOCTL_IC_SEND_XUSB:return 1;
case IOCTL_IC_SEND_XINPUTHID:return 2;
case IOCTL_IC_SEND_GIP:case IOCTL_IC_SEND_GIP_RAW:return 3;
default:return 4;
}
}
struct SenderState {
// Reverse destruction closes the source files before the control handle.
Handle driver;
Detail::SourceCache<SourceHandles> sources[4];
HANDLE Prepare(unsigned index) {
if(driver.value==INVALID_HANDLE_VALUE)Open(driver);
if(index<4)sources[index].Prepare([&] {
const auto controllers=static_cast<std::uint8_t>(1u<<index);
ValidateControllerCapabilities(driver.value,controllers);
return OpenControllerSources(controllers);
});
return driver.value;
}
void Refresh(unsigned index) {
if(index<4)sources[index].Reset();
(void)Prepare(index);
}
};
SenderState& Sender() {thread_local SenderState state;return state;}
DWORD NtError(std::uint32_t status) {
if(status==0)return ERROR_SUCCESS;
if(status==0x80000011u)return ERROR_BUSY; // STATUS_DEVICE_BUSY
if(status==0xC000009Du)return ERROR_DEVICE_NOT_CONNECTED;
using Convert=ULONG(WINAPI*)(LONG);
auto module=GetModuleHandleW(L"ntdll.dll");
if(!module)return ERROR_GEN_FAILURE;
auto fn=reinterpret_cast<Convert>(GetProcAddress(module,"RtlNtStatusToDosError"));
return fn?fn(static_cast<LONG>(status)):ERROR_GEN_FAILURE;
}
template<class T> Send_Result Send(DWORD code,const T* data,std::size_t count,HANDLE bound=INVALID_HANDLE_VALUE) {
if(count && !data)throw std::invalid_argument("Send: null input");
const auto index=ControllerSendIndex(code);
return Detail::SendBatches(count,[&](std::size_t offset,std::size_t n)->Send_Result {
IC_SEND_RESULT result{};
try {
const void* payload=data+offset;
if constexpr(Detail::DecodedHid<T>) {
// Reused per caller thread; no timer/worker or allocation after warmup.
thread_local std::vector<Detail::Wire<T>> encoded;
encoded.resize(n);
for(std::size_t i=0;i<n;++i) {
const auto& input=data[offset+i];encoded[i]=static_cast<const Detail::Wire<T>&>(input);
const auto error=Detail::Hid_Codec::Encode(input,encoded[i].report,encoded[i].length,encoded[i].device);
if(error)return {0,error};
}
payload=encoded.data();
}
const DWORD bytes=Io(bound==INVALID_HANDLE_VALUE?Sender().Prepare(index):bound,code,payload,static_cast<DWORD>(n*sizeof(Detail::Wire<T>)),&result,sizeof(result));
if(bytes!=sizeof(result) || result.accepted>n)Fail("Invalid Interceptor send response",ERROR_INVALID_DATA);
} catch(const std::system_error& e) {return {0,static_cast<DWORD>(e.code().value())};}
return {result.accepted,NtError(result.status)};
},[&]()->DWORD {
try {Sender().Refresh(index);return ERROR_SUCCESS;}
catch(const std::system_error& e) {return static_cast<DWORD>(e.code().value());}
},bound==INVALID_HANDLE_VALUE && index<4);
}
}
struct Input_Processing_Storage {
std::vector<Keyboard_Input> keyboard;
std::vector<Mouse_Input> mouse;
std::vector<Controller_Hid_Input> hid;
std::vector<Controller_Xinput_Input> xusb;
std::vector<Controller_XinputHid_Input> xinputhid;
std::vector<Controller_GIP_Input> gip;
std::vector<Controller_GIP_Raw_Input> gipRaw;
};
class Context {
public:
SourceHandles sources;
Handle driver,events[IC_STREAM_COUNT],revoked;std::uint8_t mask=0;std::mutex readers[IC_STREAM_COUNT];
std::atomic<bool> multipleReady{false}; // Relaxed hint; Windows remains authoritative.
std::vector<Detail::Wire<Controller_Hid_Input>> hid;
std::vector<Controller_Xinput_Input> xusb;
std::vector<Detail::Wire<Controller_XinputHid_Input>> xinputhid;
std::vector<Controller_GIP_Input> gip;
std::vector<Controller_GIP_Raw_Input> gipRaw;
bool gipRawSupported=false;
int selectedReadSupport=-1; // Unknown / unavailable / supported, per handle.
std::mutex processing;
std::unique_ptr<Input_Processing_Storage> processingStorage;
~Context() {if(driver.value!=INVALID_HANDLE_VALUE) {CloseHandle(driver.value);driver.value=INVALID_HANDLE_VALUE;}}
std::vector<Keyboard_Input> keyboard;
std::vector<Mouse_Input> mouse;
};
void Context_Deleter::operator()(Context* c) const noexcept { delete c; }
IC_DEVICE_QUERY_RESULT DeviceDetails(HANDLE driver,std::uint32_t type,std::uint32_t token,bool ordinal,std::uint32_t version) {
IC_DEVICE_QUERY request{version,type,token,ordinal?1u:0u};IC_DEVICE_QUERY_RESULT result{};
const auto bytes=Io(driver,IOCTL_IC_DEVICE_QUERY,&request,sizeof(request),&result,sizeof(result));
if(bytes!=sizeof(result) || result.size!=sizeof(result) || result.version!=version ||
result.type!=type || (ordinal?!result.instance_token:result.instance_token!=token) || result.reserved[2] ||
(version==IC_DEVICE_QUERY_VERSION && (result.reserved[0] || result.reserved[1])) ||
(version==IC_DEVICE_STATE_VERSION && type && (result.reserved[0]<IC_DEVICE_PREPARING || result.reserved[0]>IC_DEVICE_UNAVAILABLE)) ||
result.instance[255])Fail("Invalid Interceptor device details",ERROR_INVALID_DATA);
return result;
}
Detail::Native_Device_Availability Availability(HANDLE driver,std::uint32_t type,std::uint32_t token,bool ordinal) {
Detail::Native_Device_Availability state;
try {state.details=DeviceDetails(driver,type,token,ordinal,IC_DEVICE_STATE_VERSION);state.reported_by_driver=true;}
catch(const std::system_error& error) {
const auto code=error.code().value();
if(code!=ERROR_INVALID_PARAMETER && code!=ERROR_INVALID_FUNCTION && code!=ERROR_NOT_SUPPORTED)throw;
state.details=DeviceDetails(driver,type,token,ordinal,IC_DEVICE_QUERY_VERSION);
IcDeviceAvailability(&state.details,0);
}
state.state=state.details.reserved[0];state.reasons=state.details.reserved[1];return state;
}
DWORD PreparationError(HANDLE driver,std::uint8_t mask,std::uint8_t controllers,DWORD original) {
if(original!=ERROR_DEVICE_NOT_CONNECTED && original!=ERROR_NOT_READY)return original;
// Older kernels called pending sources disconnected. Query exact registered
// readers, without opening another source/capture, to preserve this distinction.
bool found=false,pending=false;
const unsigned streams=mask|(static_cast<unsigned>(controllers)<<2);
for(unsigned stream=0;stream<6;++stream)if(streams&(1u<<stream)) {
bool familyPresent=false;
for(unsigned ordinal=1;ordinal<=IC_MAX_DEVICES;++ordinal) {
try {
const auto state=Availability(driver,stream+1,ordinal,true);familyPresent=true;found=true;
if(state.state!=IC_DEVICE_UNSUPPORTED)pending=true;
}catch(const std::system_error& error) {
if(error.code().value()==ERROR_DEVICE_NOT_CONNECTED)break;
// Unsupported query extensions preserve the real CREATE error.
if(error.code().value()==ERROR_INVALID_FUNCTION || error.code().value()==ERROR_NOT_SUPPORTED || error.code().value()==ERROR_INVALID_PARAMETER)return original;
throw;
}
}
if(!familyPresent)return ERROR_DEVICE_NOT_CONNECTED;
}
return !found?original:pending?ERROR_NOT_READY:ERROR_NOT_SUPPORTED;
}
static Context_Result CreateImpl(std::uint8_t mask,std::uint8_t controllers,const Detail::Preparation_Options& wait,bool all) {
if((mask&~IC_PRODUCT_INPUT_MASK) || (controllers&~IC_PRODUCT_CONTROLLER_MASK))
throw std::invalid_argument("Create_Context: input family is excluded from this product");
if(controllers&~15u)throw std::invalid_argument("Create_Context: invalid controller mask");
if((!mask && !controllers) || (mask&~Both))throw std::invalid_argument("Create_Context: invalid input mask");
Context_Result result;result.devices.reserve(IC_MAX_DEVICES);
std::vector<std::uint64_t> response((sizeof(IC_CREATE_RESULT)+IC_MAX_DEVICES*sizeof(Device_Info)+7)/8);
Context_Ptr c(new Context);c->mask=static_cast<std::uint8_t>(mask|((controllers&Controller_Hid)?IC_READY_HID:0)|((controllers&Controller_Xinput)?IC_READY_XUSB:0)|((controllers&Controller_XinputHid)?IC_READY_XINPUTHID:0)|((controllers&Controller_GIP)?IC_READY_GIP:0));
Open(c->driver);
if(all) {
const auto capabilities=Capabilities(c->driver.value);
mask=static_cast<std::uint8_t>(capabilities.input_mask&IC_PRODUCT_INPUT_MASK);
controllers=static_cast<std::uint8_t>(Policy::SupportedControllers(capabilities)&IC_PRODUCT_CONTROLLER_MASK);
c->mask=static_cast<std::uint8_t>(mask|(controllers<<2));
}
ValidateControllerCapabilities(c->driver.value,controllers,mask);
if(controllers&Controller_GIP)c->gipRawSupported=(Capabilities(c->driver.value).gip_profiles&IC_PROFILE_GIP_USB_GAMEPAD_RAW)!=0;
IC_CREATE request{};request.version=IC_VERSION;request.mask=mask;request.controller_mask=controllers;
for(unsigned i=0;i<IC_STREAM_COUNT;++i)if(c->mask&(1u<<i)) {
c->events[i].value=CreateEventW(nullptr,TRUE,FALSE,nullptr);
if(!c->events[i].value)Fail("CreateEvent");
}
request.keyboard_event=(mask&Keyboard)?reinterpret_cast<std::uint64_t>(c->events[0].value):0;
request.mouse_event=(mask&Mouse)?reinterpret_cast<std::uint64_t>(c->events[1].value):0;
c->revoked.value=CreateEventW(nullptr,TRUE,FALSE,nullptr);
if(!c->revoked.value)Fail("CreateEvent");
request.revoked_event=reinterpret_cast<std::uint64_t>(c->revoked.value);
request.controller_hid_event=(controllers&Controller_Hid)?reinterpret_cast<std::uint64_t>(c->events[2].value):0;
IC_CREATE_XUSB nativeRequest{request,(controllers&Controller_Xinput)?reinterpret_cast<std::uint64_t>(c->events[3].value):0};
IC_CREATE_NATIVE extendedRequest{request,nativeRequest.xusb_event,(controllers&Controller_XinputHid)?reinterpret_cast<std::uint64_t>(c->events[4].value):0,(controllers&Controller_GIP)?reinterpret_cast<std::uint64_t>(c->events[5].value):0};
const bool extended=all || (controllers&(Controller_XinputHid|Controller_GIP))!=0;
const bool native=(controllers&Controller_Xinput)!=0;
DWORD bytes=0;bool sourcesOpened=false;
const auto attempt=[&] {
try {
if(!sourcesOpened){c->sources=OpenControllerSources(controllers,all);sourcesOpened=true;}
bytes=Io(c->driver.value,all?IOCTL_IC_CREATE_ALL:extended?IOCTL_IC_CREATE_NATIVE:native?IOCTL_IC_CREATE_XUSB:IOCTL_IC_CREATE,
extended?static_cast<const void*>(&extendedRequest):native?static_cast<const void*>(&nativeRequest):&request,
extended?sizeof(extendedRequest):native?sizeof(nativeRequest):sizeof(request),response.data(),static_cast<DWORD>(response.size()*8));
}catch(const std::system_error& error) {
const auto code=static_cast<DWORD>(error.code().value());
Fail("Create capture context",PreparationError(c->driver.value,mask,controllers,code));
}
};
if(all)attempt();
else Detail::PrepareContext(attempt,[]{return GetTickCount64();},[&](DWORD delay) {
if(wait.stop_event) {
const auto state=WaitForSingleObject(wait.stop_event,delay);
if(state==WAIT_OBJECT_0)Fail("Capture preparation cancelled",ERROR_OPERATION_ABORTED);
if(state==WAIT_FAILED)Fail("Wait for capture preparation");
} else if(delay)Sleep(delay);
},wait.timeout);
IC_CREATE_RESULT header{};
if(bytes<sizeof(header))Fail("Invalid context snapshot",ERROR_INVALID_DATA);
memcpy(&header,response.data(),sizeof(header));
if(header.version!=IC_VERSION || header.count>IC_MAX_DEVICES || bytes!=sizeof(header)+header.count*sizeof(Device_Info))
Fail("Invalid context snapshot",ERROR_INVALID_DATA);
result.devices.resize(header.count);
if(header.count)memcpy(result.devices.data(),reinterpret_cast<const BYTE*>(response.data())+sizeof(header),header.count*sizeof(Device_Info));
result.generation=header.generation;result.context=std::move(c);return result;
}
Context_Result Create_Context() {return CreateImpl(IC_PRODUCT_INPUT_MASK,IC_PRODUCT_CONTROLLER_MASK,Detail::Preparation_Options{},true);}
bool Detail::Raw_Gip_Supported(const Context& context) noexcept {return context.gipRawSupported;}
Context_Result Detail::Create_Selected_Context(std::uint8_t mask,std::uint8_t controllers,const Preparation_Options& wait) {
return CreateImpl(mask,controllers,wait,false);
}
std::vector<Device_Info> Get_Devices(Context& c) {
std::vector<std::uint64_t> raw((sizeof(IC_CREATE_RESULT)+IC_MAX_DEVICES*sizeof(Device_Info)+7)/8);
const auto bytes=Io(c.driver.value,IOCTL_IC_CONTEXT_DEVICES,nullptr,0,raw.data(),static_cast<DWORD>(raw.size()*8));
IC_CREATE_RESULT header{};if(bytes<sizeof(header))Fail("Invalid device snapshot",ERROR_INVALID_DATA);
memcpy(&header,raw.data(),sizeof(header));
if(header.version!=IC_VERSION || header.count>IC_MAX_DEVICES || bytes!=sizeof(header)+header.count*sizeof(Device_Info))Fail("Invalid device snapshot",ERROR_INVALID_DATA);
std::vector<Device_Info> out(header.count);
if(header.count)memcpy(out.data(),reinterpret_cast<const BYTE*>(raw.data())+sizeof(header),header.count*sizeof(Device_Info));
return out;
}
void Destroy_Context(Context_Ptr& c) noexcept { c.reset(); }
IC_CAPABILITIES Get_Capabilities() {Handle h;Open(h);return Capabilities(h.value);}
IC_TRIAL_STATUS Get_Trial_Status() {
Handle h;Open(h);IC_TRIAL_STATUS result{};
const auto bytes=Io(h.value,IOCTL_IC_TRIAL_STATUS,nullptr,0,&result,sizeof(result));
if(bytes!=sizeof(result) || result.size!=sizeof(result) || result.version!=IC_TRIAL_VERSION ||
result.state>IC_TRIAL_UNAVAILABLE || result.active_mask&~IC_ALL_STREAMS ||
!result.duration_100ns || result.remaining_100ns>result.duration_100ns ||
result.reserved[0] || result.reserved[1] || result.reserved[2])Fail("Invalid Interceptor trial status",ERROR_INVALID_DATA);
return result;
}
IC_DEVICE_QUERY_RESULT Get_Device_Details(std::uint32_t type,std::uint32_t token,bool ordinal) {
Handle h;Open(h);return DeviceDetails(h.value,type,token,ordinal,IC_DEVICE_QUERY_VERSION);
}
Detail::Native_Device_Availability Get_Device_Availability(std::uint32_t type,std::uint32_t token,bool ordinal) {
if(!type || type>IC_TYPE_CONTROLLER_GIP || !token || (ordinal && token>IC_MAX_DEVICES))throw std::invalid_argument("Invalid device availability query");
Handle h;Open(h);return Availability(h.value,type,token,ordinal);
}
void Destroy_Context(Context_Result& c) noexcept {c.context.reset();c.devices.clear();c.generation=0;}
template<class T> void Get(Context& c,std::vector<T>& out,std::vector<Detail::Wire<T>>& scratch,std::uint32_t count,unsigned stream,DWORD code) {
if(!(c.mask&(1u<<stream)))throw std::invalid_argument("Context does not own this input type");
std::lock_guard<std::mutex> lock(c.readers[stream]);
const auto limit=stream>=2?IC_HID_CAPACITY:IC_CAPACITY;
const auto capacity=count?std::min<std::uint32_t>(count,limit):limit;
// Reserve before dequeue: an allocation failure must not lose captured input.
out.reserve(capacity);IC_GET request{IC_VERSION,count};
if(scratch.size()<capacity)scratch.resize(capacity);
try {
DWORD bytes=Io(c.driver.value,code,&request,sizeof(request),scratch.data(),static_cast<DWORD>(capacity*sizeof(Detail::Wire<T>)));
if(bytes%sizeof(Detail::Wire<T>) || bytes>capacity*sizeof(Detail::Wire<T>))Fail("Invalid Interceptor input response",ERROR_INVALID_DATA);
Detail::AssignWire(out,scratch.data(),bytes/sizeof(Detail::Wire<T>));
} catch(...) { out.clear();throw; }
}
void Get_Keyboard_Input(Context& c,std::vector<Keyboard_Input>& out,std::uint32_t count) { Get(c,out,c.keyboard,count,0,IOCTL_IC_GET_KEYBOARD); }
void Get_Mouse_Input(Context& c,std::vector<Mouse_Input>& out,std::uint32_t count) { Get(c,out,c.mouse,count,1,IOCTL_IC_GET_MOUSE); }
std::vector<Keyboard_Input> Get_Keyboard_Input(Context& c,std::uint32_t count) {
std::vector<Keyboard_Input> out;Get_Keyboard_Input(c,out,count);return out;
}
std::vector<Mouse_Input> Get_Mouse_Input(Context& c,std::uint32_t count) {
std::vector<Mouse_Input> out;Get_Mouse_Input(c,out,count);return out;
}
Send_Result Send_Input(const Keyboard_Input* input,std::size_t count) { return Send(IOCTL_IC_SEND_KEYBOARD,input,count); }
Send_Result Send_Input(const Mouse_Input* input,std::size_t count) { return Send(IOCTL_IC_SEND_MOUSE,input,count); }
Send_Result Send_Input(Context& c,const Keyboard_Input* input,std::size_t count) { return Send(IOCTL_IC_SEND_OWNED_KEYBOARD,input,count,c.driver.value); }
Send_Result Send_Input(Context& c,const Mouse_Input* input,std::size_t count) { return Send(IOCTL_IC_SEND_OWNED_MOUSE,input,count,c.driver.value); }
template<class T> std::uint32_t GetDirect(Context& c,T* out,std::uint32_t capacity,std::uint32_t count,unsigned stream,DWORD code) {
if(!(c.mask&(1u<<stream)) || !out || !capacity || capacity>IC_CAPACITY || (count && std::min(count,IC_CAPACITY)>capacity))
throw std::invalid_argument("Get: invalid stream/buffer/capacity");
std::lock_guard<std::mutex> lock(c.readers[stream]);
IC_GET request{IC_VERSION,count};
if constexpr(Detail::DecodedHid<T>) {
// The per-family reader lock also protects this context-owned wire
// buffer. Allocate before dequeue and reuse it across direct reads.
auto& wire=[&]() -> auto& {
if constexpr(std::is_same_v<T,Controller_Hid_Input>)return c.hid;
else return c.xinputhid;
}();
if(wire.size()<capacity)wire.resize(capacity);
const auto bytes=Io(c.driver.value,code,&request,sizeof(request),wire.data(),static_cast<DWORD>(capacity*sizeof(Detail::Wire<T>)));
if(bytes%sizeof(Detail::Wire<T>)||bytes>capacity*sizeof(Detail::Wire<T>))Fail("Invalid Interceptor input response",ERROR_INVALID_DATA);
const auto n=bytes/sizeof(Detail::Wire<T>);for(std::size_t i=0;i<n;++i)Detail::AssignWire(out[i],wire[i]);return static_cast<std::uint32_t>(n);
} else {
const DWORD bytes=Io(c.driver.value,code,&request,sizeof(request),out,static_cast<DWORD>(capacity*sizeof(T)));
if(bytes%sizeof(T) || bytes>capacity*sizeof(T))Fail("Invalid Interceptor input response",ERROR_INVALID_DATA);
return static_cast<std::uint32_t>(bytes/sizeof(T));
}
}
std::uint32_t Get_Keyboard_Input(Context& c,Keyboard_Input* out,std::uint32_t capacity,std::uint32_t count) { return GetDirect(c,out,capacity,count,0,IOCTL_IC_GET_KEYBOARD); }
std::uint32_t Get_Mouse_Input(Context& c,Mouse_Input* out,std::uint32_t capacity,std::uint32_t count) { return GetDirect(c,out,capacity,count,1,IOCTL_IC_GET_MOUSE); }
void Get_Controller_Hid_Input(Context& c,std::vector<Controller_Hid_Input>& out,std::uint32_t count) {Get(c,out,c.hid,count,2,IOCTL_IC_GET_HID);}
std::vector<Controller_Hid_Input> Get_Controller_Hid_Input(Context& c,std::uint32_t count) {
std::vector<Controller_Hid_Input> out;Get_Controller_Hid_Input(c,out,count);return out;
}
std::uint32_t Get_Controller_Hid_Input(Context& c,Controller_Hid_Input* out,std::uint32_t capacity,std::uint32_t count) {
if(capacity>IC_HID_CAPACITY)throw std::invalid_argument("HID capacity exceeds IC_HID_CAPACITY");
return GetDirect(c,out,capacity,count?std::min(count,IC_HID_CAPACITY):0,2,IOCTL_IC_GET_HID);
}
Send_Result Send_Input(const Controller_Hid_Input* in,std::size_t n) {return Send(IOCTL_IC_SEND_HID,in,n);}
Send_Result Send_Input(Context& c,const Controller_Hid_Input* in,std::size_t n) {return Send(IOCTL_IC_SEND_OWNED_HID,in,n,c.driver.value);}
void Get_Controller_Xinput_Input(Context& c,std::vector<Controller_Xinput_Input>& out,std::uint32_t count){Get(c,out,c.xusb,count,3,IOCTL_IC_GET_XUSB);}
std::vector<Controller_Xinput_Input> Get_Controller_Xinput_Input(Context& c,std::uint32_t count){std::vector<Controller_Xinput_Input> out;Get_Controller_Xinput_Input(c,out,count);return out;}
std::uint32_t Get_Controller_Xinput_Input(Context& c,Controller_Xinput_Input* out,std::uint32_t capacity,std::uint32_t count){if(capacity>IC_XUSB_CAPACITY)throw std::invalid_argument("XUSB capacity");return GetDirect(c,out,capacity,count?std::min(count,IC_XUSB_CAPACITY):0,3,IOCTL_IC_GET_XUSB);}
Send_Result Send_Input(const Controller_Xinput_Input* in,std::size_t n){return Send(IOCTL_IC_SEND_XUSB,in,n);}
Send_Result Send_Input(Context& c,const Controller_Xinput_Input* in,std::size_t n){return Send(IOCTL_IC_SEND_OWNED_XUSB,in,n,c.driver.value);}
void Get_Controller_XinputHid_Input(Context& c,std::vector<Controller_XinputHid_Input>& out,std::uint32_t count){Get(c,out,c.xinputhid,count,4,IOCTL_IC_GET_XINPUTHID);}
std::vector<Controller_XinputHid_Input> Get_Controller_XinputHid_Input(Context& c,std::uint32_t count){std::vector<Controller_XinputHid_Input> out;Get_Controller_XinputHid_Input(c,out,count);return out;}
std::uint32_t Get_Controller_XinputHid_Input(Context& c,Controller_XinputHid_Input* out,std::uint32_t capacity,std::uint32_t count){if(capacity>IC_HID_CAPACITY)throw std::invalid_argument("XInputHID capacity");return GetDirect(c,out,capacity,count?std::min(count,IC_HID_CAPACITY):0,4,IOCTL_IC_GET_XINPUTHID);}
Send_Result Send_Input(const Controller_XinputHid_Input* in,std::size_t n){return Send(IOCTL_IC_SEND_XINPUTHID,in,n);}
Send_Result Send_Input(Context& c,const Controller_XinputHid_Input* in,std::size_t n){return Send(IOCTL_IC_SEND_OWNED_XINPUTHID,in,n,c.driver.value);}
void Get_Controller_GIP_Input(Context& c,std::vector<Controller_GIP_Input>& out,std::uint32_t count){Get(c,out,c.gip,count,5,IOCTL_IC_GET_GIP);}
std::vector<Controller_GIP_Input> Get_Controller_GIP_Input(Context& c,std::uint32_t count){std::vector<Controller_GIP_Input> out;Get_Controller_GIP_Input(c,out,count);return out;}
std::uint32_t Get_Controller_GIP_Input(Context& c,Controller_GIP_Input* out,std::uint32_t capacity,std::uint32_t count){if(capacity>IC_GIP_CAPACITY)throw std::invalid_argument("GIP capacity");return GetDirect(c,out,capacity,count?std::min(count,IC_GIP_CAPACITY):0,5,IOCTL_IC_GET_GIP);}
Send_Result Send_Input(const Controller_GIP_Input* in,std::size_t n){return Send(IOCTL_IC_SEND_GIP,in,n);}
Send_Result Send_Input(Context& c,const Controller_GIP_Input* in,std::size_t n){return Send(IOCTL_IC_SEND_OWNED_GIP,in,n,c.driver.value);}
void Get_Controller_GIP_Raw_Input(Context& c,std::vector<Controller_GIP_Raw_Input>& out,std::uint32_t count) {
if(!c.gipRawSupported)Fail("Loaded driver has no complete GIP report API",ERROR_NOT_SUPPORTED);
Get(c,out,c.gipRaw,count,5,IOCTL_IC_GET_GIP_RAW);
}
std::uint32_t Get_Controller_GIP_Raw_Input(Context& c,Controller_GIP_Raw_Input* out,std::uint32_t capacity,std::uint32_t count) {
if(!c.gipRawSupported)Fail("Loaded driver has no complete GIP report API",ERROR_NOT_SUPPORTED);
if(capacity>IC_GIP_CAPACITY)throw std::invalid_argument("GIP raw capacity");
return GetDirect(c,out,capacity,count?std::min(count,IC_GIP_CAPACITY):0,5,IOCTL_IC_GET_GIP_RAW);
}
Send_Result Send_Input(const Controller_GIP_Raw_Input* in,std::size_t n){return Send(IOCTL_IC_SEND_GIP_RAW,in,n);}
Send_Result Send_Input(Context& c,const Controller_GIP_Raw_Input* in,std::size_t n){
if(!c.gipRawSupported)return {0,ERROR_NOT_SUPPORTED};
return Send(IOCTL_IC_SEND_OWNED_GIP_RAW,in,n,c.driver.value);
}
std::vector<std::uint8_t> Get_Controller_XinputHid_Descriptor(Context& c,std::uint32_t id) {
std::vector<std::uint8_t> out(65536);IC_GET request{IC_VERSION,id};
const auto bytes=Io(c.driver.value,IOCTL_IC_XINPUTHID_DESCRIPTOR,&request,sizeof(request),out.data(),static_cast<DWORD>(out.size()));
if(!bytes || bytes>out.size())Fail("Invalid XInputHID descriptor response",ERROR_INVALID_DATA);
out.resize(bytes);return out;
}
std::vector<std::uint8_t> Get_Controller_Hid_Descriptor(Context& c,std::uint32_t id) {
std::vector<std::uint8_t> out(65536);IC_GET request{IC_VERSION,id};
const auto bytes=Io(c.driver.value,IOCTL_IC_HID_DESCRIPTOR,&request,sizeof(request),out.data(),static_cast<DWORD>(out.size()));
if(!bytes || bytes>out.size())Fail("Invalid HID descriptor response",ERROR_INVALID_DATA);
out.resize(bytes);return out;
}
IC_STATUS Get_Status(Context* c) {
IC_STATUS status{};Handle transient;
if(!c)Open(transient);
DWORD bytes=Io(c?c->driver.value:transient.value,IOCTL_IC_STATUS,nullptr,0,&status,sizeof(status));
if(bytes!=sizeof(status) || status.version!=IC_VERSION)Fail("Interceptor ABI mismatch",ERROR_REVISION_MISMATCH);
return status;
}
std::size_t Detail::ProcessInputs(Context& c,const Input_Callbacks& callbacks,DWORD timeout,HANDLE stop) {
std::unique_lock<std::mutex> lock(c.processing,std::try_to_lock);
if(!lock.owns_lock())Fail("Another input processing call already uses this capture",ERROR_BUSY);
try {
const auto ready=Wait_For_Input(c,timeout,stop);
if(!ready)return 0;
if(!c.processingStorage)c.processingStorage=std::make_unique<Input_Processing_Storage>();
auto& storage=*c.processingStorage;std::size_t processed=0;
#define IC_PROCESS(bit,Name,buffer,callback) if(ready&(bit))processed+=ProcessBatch(storage.buffer, \
[&](auto& out){Get_##Name##_Input(c,out);}, \
[&](auto inputs){return Send_Input(c,inputs);},callbacks.callback,callbacks.user)
IC_PROCESS(Keyboard,Keyboard,keyboard,keyboard);
IC_PROCESS(Mouse,Mouse,mouse,mouse);
IC_PROCESS(Ready_Controller_Hid,Controller_Hid,hid,hid);
IC_PROCESS(Ready_Controller_Xinput,Controller_Xinput,xusb,xusb);
IC_PROCESS(Ready_Controller_XinputHid,Controller_XinputHid,xinputhid,xinputhid);
if(c.gipRawSupported){IC_PROCESS(Ready_Controller_GIP,Controller_GIP_Raw,gipRaw,gipRaw);}
else {IC_PROCESS(Ready_Controller_GIP,Controller_GIP,gip,gip);}
#undef IC_PROCESS
return processed;
}catch(...) {
// Keep the C++ object/events alive for callers already using them.
// Closing control revokes every family and restores physical input.
if(c.driver.value!=INVALID_HANDLE_VALUE){CloseHandle(c.driver.value);c.driver.value=INVALID_HANDLE_VALUE;}
throw;
}
}
std::uint8_t Wait_For_Input(Context& c,DWORD timeout) {
return Wait_For_Input(c,timeout,nullptr);
}
std::uint8_t Wait_For_Input(Context& c,DWORD timeout,HANDLE stop_event) {
HANDLE events[IC_STREAM_COUNT+2]={c.revoked.value};DWORD count=1;
std::uint8_t streams[IC_STREAM_COUNT+2]{};
if(stop_event)events[count++]=stop_event;
for(unsigned i=0;i<IC_STREAM_COUNT;++i)if(c.mask&(1u<<i)) {
streams[count]=static_cast<std::uint8_t>(1u<<i);events[count++]=c.events[i].value;
}
DWORD result=WaitForMultipleObjects(count,events,FALSE,timeout);
if(result==WAIT_FAILED)Fail("WaitForMultipleObjects");
if(result==WAIT_OBJECT_0)Fail("Capture revoked",ERROR_OPERATION_ABORTED);
if(stop_event && result==WAIT_OBJECT_0+1)return 0;
if(result==WAIT_TIMEOUT)return 0;
const auto selected=result-WAIT_OBJECT_0;
if(selected>=count)Fail("Unexpected input wait result",ERROR_INVALID_DATA);
// Wait-any returns the lowest signalled index. Its stream is already
// known; only later streams need polling. Earlier arrivals remain signalled
// for the next receive. Revocation and caller cancellation keep priority.
std::uint8_t ready=streams[selected];
// An empty tail needs one syscall. After finding another ready family,
// individual checks avoid repeated multi-object scans of a dense tail.
DWORD next=selected+1;
if(count-next>1 && !c.multipleReady.load(std::memory_order_relaxed)) {
const auto tail=WaitForMultipleObjects(count-next,events+next,FALSE,0);
if(tail==WAIT_TIMEOUT)return ready;
if(tail==WAIT_FAILED)Fail("WaitForMultipleObjects");
const auto offset=tail-WAIT_OBJECT_0;
if(offset>=count-next)Fail("Unexpected input wait result",ERROR_INVALID_DATA);
next+=offset;ready|=streams[next++];
}
for(;next<count;++next)
if(WaitForSingleObject(events[next],0)==WAIT_OBJECT_0)ready|=streams[next];
c.multipleReady.store((ready&(ready-1))!=0,std::memory_order_relaxed);
return ready;
}
}
// ---- HidCodec.inl ----
// Descriptor-driven SDK decoding. Never opens a device or starts a capture.
#include <cmath>
#include <limits>
#include <unordered_set>
namespace Interceptor::Detail {
namespace {
std::int64_t HidMinimum(const HIDP_VALUE_CAPS& c){return c.LogicalMin;}
std::int64_t HidMaximum(const HIDP_VALUE_CAPS& c){return c.LogicalMin<0?static_cast<std::int64_t>(c.LogicalMax):static_cast<std::uint32_t>(c.LogicalMax);}
std::int64_t HidSigned(std::uint32_t raw,unsigned bits,bool sign) {
const auto mask=bits==32?0xffffffffull:(1ull<<bits)-1;
const auto value=static_cast<std::uint64_t>(raw)&mask;
return sign&&(value&(1ull<<(bits-1)))?static_cast<std::int64_t>(value)-static_cast<std::int64_t>(mask+1):static_cast<std::int64_t>(value);
}
double HidNormalized(std::int64_t value,std::int64_t minimum,std::int64_t maximum) {
if(minimum<0&&maximum>0)return value<0?-static_cast<double>(value)/static_cast<double>(minimum):static_cast<double>(value)/static_cast<double>(maximum);
return 2.0*static_cast<double>(value-minimum)/static_cast<double>(maximum-minimum)-1.0;
}
std::int64_t HidLogical(double value,std::int64_t minimum,std::int64_t maximum) {
const double raw=minimum<0&&maximum>0?(value<0?-value*static_cast<double>(minimum):value*static_cast<double>(maximum)):
static_cast<double>(minimum)+(value+1.0)*0.5*static_cast<double>(maximum-minimum);
return static_cast<std::int64_t>(std::llround(raw));
}
std::uint32_t HidBits(const std::uint8_t* bytes,std::size_t bit,unsigned count) {
// At most five byte loads for a possibly unaligned 32-bit field. No
// unaligned typed loads, full-word overreads or host-endian assumptions.
std::uint64_t raw=0;const auto shift=static_cast<unsigned>(bit%8);
for(unsigned i=0;i<(shift+count+7)/8;++i)raw|=static_cast<std::uint64_t>(bytes[bit/8+i])<<(i*8);
return static_cast<std::uint32_t>((raw>>shift)&((1ull<<count)-1));
}
std::uint32_t HidBits(const std::vector<std::uint8_t>& bytes,std::size_t bit,unsigned count) {return HidBits(bytes.data(),bit,count);}
void HidWriteBits(std::uint8_t* bytes,std::size_t bit,unsigned count,std::uint32_t value) {
while(count) {
const auto shift=static_cast<unsigned>(bit%8),take=(std::min)(8u-shift,count);
const auto mask=static_cast<std::uint8_t>(((1u<<take)-1)<<shift);
auto& byte=bytes[bit/8];byte=static_cast<std::uint8_t>((byte&~mask)|((value<<shift)&mask));
value>>=take;bit+=take;count-=take;
}
}
bool HidTriggerUsage(USHORT page,USHORT usage) {return page==2&&usage==0xC0;}
std::vector<std::uint8_t> HidTriggerCollections(const std::vector<HIDP_LINK_COLLECTION_NODE>& nodes) {
// Resolve each parent edge once, including malformed cycles. Walking the
// same deep ancestry for every usage would multiply descriptor setup cost.
std::vector<std::uint8_t> flags(nodes.size());std::vector<USHORT> path;
for(std::size_t root=0;root<nodes.size();++root) {
if(flags[root])continue;
path.clear();auto link=root;bool trigger=false;
while(link<nodes.size()&&!flags[link]) {
flags[link]=3;path.push_back(static_cast<USHORT>(link));const auto& node=nodes[link];
if(node.LinkUsagePage==5&&node.LinkUsage==0x39){trigger=true;break;}
if(!link||node.Parent==link)break;
link=node.Parent;
}
if(link<nodes.size()&&flags[link]==2)trigger=true;
for(const auto item:path)flags[item]=trigger?2:1;
}
return flags;
}
bool HidTriggerCollection(const std::vector<std::uint8_t>& flags,USHORT link) {return link<flags.size()&&flags[link]==2;}
DWORD HidParseError(NTSTATUS status){return status==HIDP_STATUS_NOT_IMPLEMENTED||status==HIDP_STATUS_NOT_VALUE_ARRAY?ERROR_NOT_SUPPORTED:ERROR_INVALID_DATA;}
}
std::shared_ptr<const Hid_Codec> Hid_Codec::Create(std::vector<std::uint8_t> bytes) {
auto codec=std::make_shared<Hid_Codec>();codec->descriptor=std::move(bytes);codec->parser=hidParser;
if(codec->descriptor.empty())Fail("Empty HID parser data",ERROR_INVALID_DATA);
auto data=reinterpret_cast<PHIDP_PREPARSED_DATA>(codec->descriptor.data());
if(codec->parser.caps(data,&codec->caps)!=HIDP_STATUS_SUCCESS||!codec->caps.InputReportByteLength||codec->caps.InputReportByteLength>IC_HID_REPORT_MAX)
Fail("Invalid HID parser data",ERROR_INVALID_DATA);
std::vector<HIDP_LINK_COLLECTION_NODE> collections(codec->caps.NumberLinkCollectionNodes);
if(!collections.empty()) {
ULONG count=static_cast<ULONG>(collections.size());
if(codec->parser.collections(collections.data(),&count,data)!=HIDP_STATUS_SUCCESS||count>collections.size())
Fail("HID collection capabilities",ERROR_INVALID_DATA);
collections.resize(count);
}
const auto triggerCollections=HidTriggerCollections(collections);
codec->maxDataCount=codec->parser.maxData(HidP_Input,data);
if(codec->maxDataCount>65536)Fail("Invalid HID data count",ERROR_INVALID_DATA);
USHORT count=codec->caps.NumberInputValueCaps;std::vector<HIDP_VALUE_CAPS> values(count);
if(count&&(codec->parser.values(HidP_Input,values.data(),&count,data)!=HIDP_STATUS_SUCCESS||count>values.size()))Fail("HID value capabilities",ERROR_INVALID_DATA);
values.resize(count);std::unordered_set<std::uint64_t> known;
for(const auto& cap:values) {
if(cap.IsAlias)continue;
if(!cap.BitSize||!cap.ReportCount||
(cap.IsRange&&(cap.Range.UsageMax<cap.Range.UsageMin||cap.Range.DataIndexMax<cap.Range.DataIndexMin||
cap.Range.UsageMax-cap.Range.UsageMin!=cap.Range.DataIndexMax-cap.Range.DataIndexMin)))Fail("Invalid HID value range",ERROR_INVALID_DATA);
const unsigned first=cap.IsRange?cap.Range.UsageMin:cap.NotRange.Usage,last=cap.IsRange?cap.Range.UsageMax:first;
for(unsigned usage=first;usage<=last;++usage) {
const auto index=cap.IsRange?static_cast<USHORT>(cap.Range.DataIndexMin+usage-first):cap.NotRange.DataIndex;
if(!known.insert((static_cast<std::uint64_t>(cap.ReportID)<<32)|index).second)continue;
if(codec->valueDefs.size()>=262144)Fail("HID capability expansion too large",ERROR_NOT_SUPPORTED);
Hid_Value_Kind kind=Hid_Value_Kind::Value;
if(HidTriggerUsage(cap.UsagePage,static_cast<USHORT>(usage))||HidTriggerCollection(triggerCollections,cap.LinkCollection))kind=Hid_Value_Kind::Trigger;
else if(cap.UsagePage==1&&usage>=0x30&&usage<=0x38)kind=Hid_Value_Kind::Axis;
else if(cap.UsagePage==1&&usage==0x39)kind=Hid_Value_Kind::Hat;
codec->reports[cap.ReportID].values.push_back(codec->valueDefs.size());
auto& reservation=codec->reports[cap.ReportID].counts[cap.BitSize>32?4:static_cast<std::size_t>(kind)];
reservation+=cap.BitSize>32?1u:cap.IsRange?1u:cap.ReportCount;
if(reservation>static_cast<std::size_t>(codec->caps.InputReportByteLength)*8)Fail("HID scalar expansion too large",ERROR_INVALID_DATA);
Value definition{cap,static_cast<USHORT>(usage),index};definition.kind=kind;codec->valueDefs.push_back(definition);
}
}
count=codec->caps.NumberInputButtonCaps;std::vector<HIDP_BUTTON_CAPS> buttons(count);
if(count&&(codec->parser.buttons(HidP_Input,buttons.data(),&count,data)!=HIDP_STATUS_SUCCESS||count>buttons.size()))Fail("HID button capabilities",ERROR_INVALID_DATA);
buttons.resize(count);known.clear();
for(const auto& cap:buttons) {
if(cap.IsAlias)continue;
if(cap.IsRange&&(cap.Range.UsageMax<cap.Range.UsageMin||cap.Range.DataIndexMax<cap.Range.DataIndexMin||
cap.Range.UsageMax-cap.Range.UsageMin!=cap.Range.DataIndexMax-cap.Range.DataIndexMin))Fail("Invalid HID button range",ERROR_INVALID_DATA);
const unsigned first=cap.IsRange?cap.Range.UsageMin:cap.NotRange.Usage,last=cap.IsRange?cap.Range.UsageMax:first;
for(unsigned usage=first;usage<=last;++usage) {
const auto index=cap.IsRange?static_cast<USHORT>(cap.Range.DataIndexMin+usage-first):cap.NotRange.DataIndex;
if(!known.insert((static_cast<std::uint64_t>(cap.ReportID)<<32)|index).second)continue;
if(codec->buttonDefs.size()>=262144)Fail("HID button expansion too large",ERROR_NOT_SUPPORTED);
codec->reports[cap.ReportID].buttons.push_back(codec->buttonDefs.size());codec->buttonDefs.push_back({cap.UsagePage,static_cast<USHORT>(usage),cap.LinkCollection,cap.ReportID,index,HidTriggerUsage(cap.UsagePage,static_cast<USHORT>(usage))||HidTriggerCollection(triggerCollections,cap.LinkCollection)});
}
}
// Locate array bits once using synthetic tagged reports, never hardware I/O.
// Windows' SetUsageValueArray rejects element sizes not divisible by eight.
// Validated offsets allow exact encoding of those arrays as well.
const auto reportBits=static_cast<unsigned>(codec->caps.InputReportByteLength)*8;
for(auto& def:codec->valueDefs) {
const auto& c=def.cap;const auto arrayCount=c.IsRange?1u:c.ReportCount;
if(arrayCount==1&&c.BitSize<=32)continue;
const auto bits=static_cast<unsigned>(c.BitSize)*arrayCount;
if(!bits||bits>reportBits){def.array_status=HIDP_STATUS_INVALID_REPORT_LENGTH;continue;}
if(std::any_of(codec->valueDefs.begin(),codec->valueDefs.end(),[&](const Value& other){return &other!=&def&&(!other.cap.IsRange&&other.cap.ReportCount>1)&&(!c.LinkCollection||other.cap.LinkCollection==c.LinkCollection)&&other.cap.ReportID==c.ReportID&&other.cap.UsagePage==c.UsagePage&&other.usage==def.usage;})){
def.array_status=HIDP_STATUS_NOT_IMPLEMENTED;continue;
}
std::vector<std::uint8_t> probe(codec->caps.InputReportByteLength),packed((bits+7)/8);
unsigned start=0,planes=0;while((1u<<planes)<reportBits)++planes;