forked from ge9/IddSampleDriver
-
-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathDriver.cpp
More file actions
5052 lines (4306 loc) · 167 KB
/
Driver.cpp
File metadata and controls
5052 lines (4306 loc) · 167 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
/*++
Copyright (c) Microsoft Corporation
Abstract:
MSDN documentation on indirect displays can be found at https://msdn.microsoft.com/en-us/library/windows/hardware/mt761968(v=vs.85).aspx.
Environment:
User Mode, UMDF
--*/
#include "Driver.h"
//#include "Driver.tmh"
#include<fstream>
#include<sstream>
#include<string>
#include<tuple>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<chrono>
#include <AdapterOption.h>
#include <xmllite.h>
#include <shlwapi.h>
#include <atlbase.h>
#include <iostream>
#include <cstdlib>
#include <windows.h>
#include <cstdio>
#include <sddl.h>
#include <mutex>
#include <chrono>
#include <iomanip>
#include <cerrno>
#include <locale>
#include <cwchar>
#include <map>
#include <set>
#define PIPE_NAME L"\\\\.\\pipe\\MTTVirtualDisplayPipe"
#pragma comment(lib, "xmllite.lib")
#pragma comment(lib, "shlwapi.lib")
HANDLE hPipeThread = NULL;
bool g_Running = true;
mutex g_Mutex;
HANDLE g_pipeHandle = INVALID_HANDLE_VALUE;
using namespace std;
using namespace Microsoft::IndirectDisp;
using namespace Microsoft::WRL;
void vddlog(const char* type, const char* message);
extern "C" DRIVER_INITIALIZE DriverEntry;
EVT_WDF_DRIVER_DEVICE_ADD VirtualDisplayDriverDeviceAdd;
EVT_WDF_DEVICE_D0_ENTRY VirtualDisplayDriverDeviceD0Entry;
EVT_IDD_CX_ADAPTER_INIT_FINISHED VirtualDisplayDriverAdapterInitFinished;
EVT_IDD_CX_ADAPTER_COMMIT_MODES VirtualDisplayDriverAdapterCommitModes;
EVT_IDD_CX_PARSE_MONITOR_DESCRIPTION VirtualDisplayDriverParseMonitorDescription;
EVT_IDD_CX_MONITOR_GET_DEFAULT_DESCRIPTION_MODES VirtualDisplayDriverMonitorGetDefaultModes;
EVT_IDD_CX_MONITOR_QUERY_TARGET_MODES VirtualDisplayDriverMonitorQueryModes;
EVT_IDD_CX_MONITOR_ASSIGN_SWAPCHAIN VirtualDisplayDriverMonitorAssignSwapChain;
EVT_IDD_CX_MONITOR_UNASSIGN_SWAPCHAIN VirtualDisplayDriverMonitorUnassignSwapChain;
EVT_IDD_CX_ADAPTER_QUERY_TARGET_INFO VirtualDisplayDriverEvtIddCxAdapterQueryTargetInfo;
EVT_IDD_CX_MONITOR_SET_DEFAULT_HDR_METADATA VirtualDisplayDriverEvtIddCxMonitorSetDefaultHdrMetadata;
EVT_IDD_CX_PARSE_MONITOR_DESCRIPTION2 VirtualDisplayDriverEvtIddCxParseMonitorDescription2;
EVT_IDD_CX_MONITOR_QUERY_TARGET_MODES2 VirtualDisplayDriverEvtIddCxMonitorQueryTargetModes2;
EVT_IDD_CX_ADAPTER_COMMIT_MODES2 VirtualDisplayDriverEvtIddCxAdapterCommitModes2;
EVT_IDD_CX_MONITOR_SET_GAMMA_RAMP VirtualDisplayDriverEvtIddCxMonitorSetGammaRamp;
struct
{
AdapterOption Adapter;
} Options;
vector<tuple<int, int, int, int>> monitorModes;
vector< DISPLAYCONFIG_VIDEO_SIGNAL_INFO> s_KnownMonitorModes2;
UINT numVirtualDisplays;
wstring gpuname;
wstring confpath = L"C:\\VirtualDisplayDriver";
bool logsEnabled = false;
bool debugLogs = false;
bool HDRPlus = false;
bool SDR10 = false;
bool customEdid = false;
bool hardwareCursor = false;
bool preventManufacturerSpoof = false;
bool edidCeaOverride = false;
bool sendLogsThroughPipe = true;
constexpr DISPLAYCONFIG_VIDEO_SIGNAL_INFO dispinfo(UINT32 h, UINT32 v, UINT32 rn, UINT32 rd);
namespace
{
void RebuildKnownMonitorModesCache()
{
s_KnownMonitorModes2.clear();
s_KnownMonitorModes2.reserve(monitorModes.size());
for (const auto& mode : monitorModes)
{
s_KnownMonitorModes2.push_back(
dispinfo(
std::get<0>(mode),
std::get<1>(mode),
std::get<2>(mode),
std::get<3>(mode)));
}
}
}
//Mouse settings
bool alphaCursorSupport = true;
int CursorMaxX = 128;
int CursorMaxY = 128;
IDDCX_XOR_CURSOR_SUPPORT XorCursorSupportLevel = IDDCX_XOR_CURSOR_SUPPORT_FULL;
//Rest
IDDCX_BITS_PER_COMPONENT SDRCOLOUR = IDDCX_BITS_PER_COMPONENT_8;
IDDCX_BITS_PER_COMPONENT HDRCOLOUR = IDDCX_BITS_PER_COMPONENT_10;
wstring ColourFormat = L"RGB";
// === EDID INTEGRATION SETTINGS ===
bool edidIntegrationEnabled = false;
bool autoConfigureFromEdid = false;
wstring edidProfilePath = L"EDID/monitor_profile.xml";
bool overrideManualSettings = false;
bool fallbackOnError = true;
// === HDR ADVANCED SETTINGS ===
bool hdr10StaticMetadataEnabled = false;
double maxDisplayMasteringLuminance = 1000.0;
double minDisplayMasteringLuminance = 0.05;
int maxContentLightLevel = 1000;
int maxFrameAvgLightLevel = 400;
bool colorPrimariesEnabled = false;
double redX = 0.708, redY = 0.292;
double greenX = 0.170, greenY = 0.797;
double blueX = 0.131, blueY = 0.046;
double whiteX = 0.3127, whiteY = 0.3290;
bool colorSpaceEnabled = false;
double gammaCorrection = 2.4;
wstring primaryColorSpace = L"sRGB";
bool enableMatrixTransform = false;
// === AUTO RESOLUTIONS SETTINGS ===
bool autoResolutionsEnabled = false;
wstring sourcePriority = L"manual";
int minRefreshRate = 24;
int maxRefreshRate = 240;
bool excludeFractionalRates = false;
int minResolutionWidth = 640;
int minResolutionHeight = 480;
int maxResolutionWidth = 7680;
int maxResolutionHeight = 4320;
bool useEdidPreferred = false;
int fallbackWidth = 1920;
int fallbackHeight = 1080;
int fallbackRefresh = 60;
// === COLOR ADVANCED SETTINGS ===
bool autoSelectFromColorSpace = false;
wstring forceBitDepth = L"auto";
bool fp16SurfaceSupport = true;
bool wideColorGamut = false;
bool hdrToneMapping = false;
double sdrWhiteLevel = 80.0;
// === MONITOR EMULATION SETTINGS ===
bool monitorEmulationEnabled = false;
bool emulatePhysicalDimensions = false;
int physicalWidthMm = 510;
int physicalHeightMm = 287;
bool manufacturerEmulationEnabled = false;
wstring manufacturerName = L"Generic";
wstring modelName = L"Virtual Display";
wstring serialNumber = L"VDD001";
std::map<std::wstring, std::pair<std::wstring, std::wstring>> SettingsQueryMap = {
{L"LoggingEnabled", {L"LOGS", L"logging"}},
{L"DebugLoggingEnabled", {L"DEBUGLOGS", L"debuglogging"}},
{L"CustomEdidEnabled", {L"CUSTOMEDID", L"CustomEdid"}},
{L"PreventMonitorSpoof", {L"PREVENTMONITORSPOOF", L"PreventSpoof"}},
{L"EdidCeaOverride", {L"EDIDCEAOVERRIDE", L"EdidCeaOverride"}},
{L"SendLogsThroughPipe", {L"SENDLOGSTHROUGHPIPE", L"SendLogsThroughPipe"}},
//Cursor Begin
{L"HardwareCursorEnabled", {L"HARDWARECURSOR", L"HardwareCursor"}},
{L"AlphaCursorSupport", {L"ALPHACURSORSUPPORT", L"AlphaCursorSupport"}},
{L"CursorMaxX", {L"CURSORMAXX", L"CursorMaxX"}},
{L"CursorMaxY", {L"CURSORMAXY", L"CursorMaxY"}},
{L"XorCursorSupportLevel", {L"XORCURSORSUPPORTLEVEL", L"XorCursorSupportLevel"}},
//Cursor End
//Colour Begin
{L"HDRPlusEnabled", {L"HDRPLUS", L"HDRPlus"}},
{L"SDR10Enabled", {L"SDR10BIT", L"SDR10bit"}},
{L"ColourFormat", {L"COLOURFORMAT", L"ColourFormat"}},
//Colour End
//EDID Integration Begin
{L"EdidIntegrationEnabled", {L"EDIDINTEGRATION", L"enabled"}},
{L"AutoConfigureFromEdid", {L"AUTOCONFIGFROMEDID", L"auto_configure_from_edid"}},
{L"EdidProfilePath", {L"EDIDPROFILEPATH", L"edid_profile_path"}},
{L"OverrideManualSettings", {L"OVERRIDEMANUALSETTINGS", L"override_manual_settings"}},
{L"FallbackOnError", {L"FALLBACKONERROR", L"fallback_on_error"}},
//EDID Integration End
//HDR Advanced Begin
{L"Hdr10StaticMetadataEnabled", {L"HDR10STATICMETADATA", L"enabled"}},
{L"MaxDisplayMasteringLuminance", {L"MAXLUMINANCE", L"max_display_mastering_luminance"}},
{L"MinDisplayMasteringLuminance", {L"MINLUMINANCE", L"min_display_mastering_luminance"}},
{L"MaxContentLightLevel", {L"MAXCONTENTLIGHT", L"max_content_light_level"}},
{L"MaxFrameAvgLightLevel", {L"MAXFRAMEAVGLIGHT", L"max_frame_avg_light_level"}},
{L"ColorPrimariesEnabled", {L"COLORPRIMARIES", L"enabled"}},
{L"RedX", {L"REDX", L"red_x"}},
{L"RedY", {L"REDY", L"red_y"}},
{L"GreenX", {L"GREENX", L"green_x"}},
{L"GreenY", {L"GREENY", L"green_y"}},
{L"BlueX", {L"BLUEX", L"blue_x"}},
{L"BlueY", {L"BLUEY", L"blue_y"}},
{L"WhiteX", {L"WHITEX", L"white_x"}},
{L"WhiteY", {L"WHITEY", L"white_y"}},
{L"ColorSpaceEnabled", {L"COLORSPACE", L"enabled"}},
{L"GammaCorrection", {L"GAMMA", L"gamma_correction"}},
{L"PrimaryColorSpace", {L"PRIMARYCOLORSPACE", L"primary_color_space"}},
{L"EnableMatrixTransform", {L"MATRIXTRANSFORM", L"enable_matrix_transform"}},
//HDR Advanced End
//Auto Resolutions Begin
{L"AutoResolutionsEnabled", {L"AUTORESOLUTIONS", L"enabled"}},
{L"SourcePriority", {L"SOURCEPRIORITY", L"source_priority"}},
{L"MinRefreshRate", {L"MINREFRESHRATE", L"min_refresh_rate"}},
{L"MaxRefreshRate", {L"MAXREFRESHRATE", L"max_refresh_rate"}},
{L"ExcludeFractionalRates", {L"EXCLUDEFRACTIONAL", L"exclude_fractional_rates"}},
{L"MinResolutionWidth", {L"MINWIDTH", L"min_resolution_width"}},
{L"MinResolutionHeight", {L"MINHEIGHT", L"min_resolution_height"}},
{L"MaxResolutionWidth", {L"MAXWIDTH", L"max_resolution_width"}},
{L"MaxResolutionHeight", {L"MAXHEIGHT", L"max_resolution_height"}},
{L"UseEdidPreferred", {L"USEEDIDPREFERRED", L"use_edid_preferred"}},
{L"FallbackWidth", {L"FALLBACKWIDTH", L"fallback_width"}},
{L"FallbackHeight", {L"FALLBACKHEIGHT", L"fallback_height"}},
{L"FallbackRefresh", {L"FALLBACKREFRESH", L"fallback_refresh"}},
//Auto Resolutions End
//Color Advanced Begin
{L"AutoSelectFromColorSpace", {L"AUTOSELECTCOLOR", L"auto_select_from_color_space"}},
{L"ForceBitDepth", {L"FORCEBITDEPTH", L"force_bit_depth"}},
{L"Fp16SurfaceSupport", {L"FP16SUPPORT", L"fp16_surface_support"}},
{L"WideColorGamut", {L"WIDECOLORGAMUT", L"wide_color_gamut"}},
{L"HdrToneMapping", {L"HDRTONEMAPPING", L"hdr_tone_mapping"}},
{L"SdrWhiteLevel", {L"SDRWHITELEVEL", L"sdr_white_level"}},
//Color Advanced End
//Monitor Emulation Begin
{L"MonitorEmulationEnabled", {L"MONITOREMULATION", L"enabled"}},
{L"EmulatePhysicalDimensions", {L"EMULATEPHYSICAL", L"emulate_physical_dimensions"}},
{L"PhysicalWidthMm", {L"PHYSICALWIDTH", L"physical_width_mm"}},
{L"PhysicalHeightMm", {L"PHYSICALHEIGHT", L"physical_height_mm"}},
{L"ManufacturerEmulationEnabled", {L"MANUFACTUREREMULATION", L"enabled"}},
{L"ManufacturerName", {L"MANUFACTURERNAME", L"manufacturer_name"}},
{L"ModelName", {L"MODELNAME", L"model_name"}},
{L"SerialNumber", {L"SERIALNUMBER", L"serial_number"}},
//Monitor Emulation End
};
const char* XorCursorSupportLevelToString(IDDCX_XOR_CURSOR_SUPPORT level) {
switch (level) {
case IDDCX_XOR_CURSOR_SUPPORT_UNINITIALIZED:
return "IDDCX_XOR_CURSOR_SUPPORT_UNINITIALIZED";
case IDDCX_XOR_CURSOR_SUPPORT_NONE:
return "IDDCX_XOR_CURSOR_SUPPORT_NONE";
case IDDCX_XOR_CURSOR_SUPPORT_FULL:
return "IDDCX_XOR_CURSOR_SUPPORT_FULL";
case IDDCX_XOR_CURSOR_SUPPORT_EMULATION:
return "IDDCX_XOR_CURSOR_SUPPORT_EMULATION";
default:
return "Unknown";
}
}
vector<unsigned char> Microsoft::IndirectDisp::IndirectDeviceContext::s_KnownMonitorEdid; //Changed to support static vector
std::map<LUID, std::shared_ptr<Direct3DDevice>, Microsoft::IndirectDisp::LuidComparator> Microsoft::IndirectDisp::IndirectDeviceContext::s_DeviceCache;
std::mutex Microsoft::IndirectDisp::IndirectDeviceContext::s_DeviceCacheMutex;
struct IndirectDeviceContextWrapper
{
IndirectDeviceContext* pContext;
void Cleanup()
{
delete pContext;
pContext = nullptr;
}
};
void LogQueries(const char* severity, const std::wstring& xmlName) {
if (xmlName.find(L"logging") == std::wstring::npos) {
int size_needed = WideCharToMultiByte(CP_UTF8, 0, xmlName.c_str(), (int)xmlName.size(), NULL, 0, NULL, NULL);
if (size_needed > 0) {
std::string strMessage(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, xmlName.c_str(), (int)xmlName.size(), &strMessage[0], size_needed, NULL, NULL);
vddlog(severity, strMessage.c_str());
}
}
}
string WStringToString(const wstring& wstr) { //basically just a function for converting strings since codecvt is depricated in c++ 17
if (wstr.empty()) return "";
int size_needed = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), NULL, 0, NULL, NULL);
string str(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.size(), &str[0], size_needed, NULL, NULL);
return str;
}
bool EnabledQuery(const std::wstring& settingKey) {
auto it = SettingsQueryMap.find(settingKey);
if (it == SettingsQueryMap.end()) {
vddlog("e", "requested data not found in xml, consider updating xml!");
return false;
}
std::wstring regName = it->second.first;
std::wstring xmlName = it->second.second;
std::wstring settingsname = confpath + L"\\vdd_settings.xml";
HKEY hKey;
DWORD dwValue;
DWORD dwBufferSize = sizeof(dwValue);
LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\MikeTheTech\\VirtualDisplayDriver", 0, KEY_READ, &hKey);
if (lResult == ERROR_SUCCESS) {
lResult = RegQueryValueExW(hKey, regName.c_str(), NULL, NULL, (LPBYTE)&dwValue, &dwBufferSize);
if (lResult == ERROR_SUCCESS) {
RegCloseKey(hKey);
if (dwValue == 1) {
LogQueries("d", xmlName + L" - is enabled (value = 1).");
return true;
}
else if (dwValue == 0) {
goto check_xml;
}
}
else {
LogQueries("d", xmlName + L" - Failed to retrieve value from registry. Attempting to read as string.");
wchar_t path[MAX_PATH];
dwBufferSize = sizeof(path);
lResult = RegQueryValueExW(hKey, regName.c_str(), NULL, NULL, (LPBYTE)path, &dwBufferSize);
if (lResult == ERROR_SUCCESS) {
std::wstring logValue(path);
RegCloseKey(hKey);
if (logValue == L"true" || logValue == L"1") {
LogQueries("d", xmlName + L" - is enabled (string value).");
return true;
}
else if (logValue == L"false" || logValue == L"0") {
goto check_xml;
}
}
RegCloseKey(hKey);
LogQueries("d", xmlName + L" - Failed to retrieve string value from registry.");
}
}
check_xml:
CComPtr<IStream> pFileStream;
HRESULT hr = SHCreateStreamOnFileEx(settingsname.c_str(), STGM_READ, FILE_ATTRIBUTE_NORMAL, FALSE, nullptr, &pFileStream);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to create file stream for XML settings.");
return false;
}
CComPtr<IXmlReader> pReader;
hr = CreateXmlReader(__uuidof(IXmlReader), (void**)&pReader, nullptr);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to create XML reader.");
return false;
}
hr = pReader->SetInput(pFileStream);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to set input for XML reader.");
return false;
}
XmlNodeType nodeType;
const wchar_t* pwszLocalName;
bool xmlLoggingValue = false;
while (S_OK == pReader->Read(&nodeType)) {
if (nodeType == XmlNodeType_Element) {
pReader->GetLocalName(&pwszLocalName, nullptr);
if (pwszLocalName && wcscmp(pwszLocalName, xmlName.c_str()) == 0) {
pReader->Read(&nodeType);
if (nodeType == XmlNodeType_Text) {
const wchar_t* pwszValue;
pReader->GetValue(&pwszValue, nullptr);
if (pwszValue) {
xmlLoggingValue = (wcscmp(pwszValue, L"true") == 0);
}
LogQueries("i", xmlName + (xmlLoggingValue ? L" is enabled." : L" is disabled."));
break;
}
}
}
}
return xmlLoggingValue;
}
int GetIntegerSetting(const std::wstring& settingKey) {
auto it = SettingsQueryMap.find(settingKey);
if (it == SettingsQueryMap.end()) {
vddlog("e", "requested data not found in xml, consider updating xml!");
return -1;
}
std::wstring regName = it->second.first;
std::wstring xmlName = it->second.second;
std::wstring settingsname = confpath + L"\\vdd_settings.xml";
HKEY hKey;
DWORD dwValue;
DWORD dwBufferSize = sizeof(dwValue);
LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\MikeTheTech\\VirtualDisplayDriver", 0, KEY_READ, &hKey);
if (lResult == ERROR_SUCCESS) {
lResult = RegQueryValueExW(hKey, regName.c_str(), NULL, NULL, (LPBYTE)&dwValue, &dwBufferSize);
if (lResult == ERROR_SUCCESS) {
RegCloseKey(hKey);
LogQueries("d", xmlName + L" - Retrieved integer value: " + std::to_wstring(dwValue));
return static_cast<int>(dwValue);
}
else {
LogQueries("d", xmlName + L" - Failed to retrieve integer value from registry. Attempting to read as string.");
wchar_t path[MAX_PATH];
dwBufferSize = sizeof(path);
lResult = RegQueryValueExW(hKey, regName.c_str(), NULL, NULL, (LPBYTE)path, &dwBufferSize);
RegCloseKey(hKey);
if (lResult == ERROR_SUCCESS) {
try {
int logValue = std::stoi(path);
LogQueries("d", xmlName + L" - Retrieved string value: " + std::to_wstring(logValue));
return logValue;
}
catch (const std::exception&) {
LogQueries("d", xmlName + L" - Failed to convert registry string value to integer.");
}
}
}
}
CComPtr<IStream> pFileStream;
HRESULT hr = SHCreateStreamOnFileEx(settingsname.c_str(), STGM_READ, FILE_ATTRIBUTE_NORMAL, FALSE, nullptr, &pFileStream);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to create file stream for XML settings.");
return -1;
}
CComPtr<IXmlReader> pReader;
hr = CreateXmlReader(__uuidof(IXmlReader), (void**)&pReader, nullptr);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to create XML reader.");
return -1;
}
hr = pReader->SetInput(pFileStream);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to set input for XML reader.");
return -1;
}
XmlNodeType nodeType;
const wchar_t* pwszLocalName;
int xmlLoggingValue = -1;
while (S_OK == pReader->Read(&nodeType)) {
if (nodeType == XmlNodeType_Element) {
pReader->GetLocalName(&pwszLocalName, nullptr);
if (pwszLocalName && wcscmp(pwszLocalName, xmlName.c_str()) == 0) {
pReader->Read(&nodeType);
if (nodeType == XmlNodeType_Text) {
const wchar_t* pwszValue;
pReader->GetValue(&pwszValue, nullptr);
if (pwszValue) {
try {
xmlLoggingValue = std::stoi(pwszValue);
LogQueries("i", xmlName + L" - Retrieved from XML: " + std::to_wstring(xmlLoggingValue));
}
catch (const std::exception&) {
LogQueries("d", xmlName + L" - Failed to convert XML string value to integer.");
}
}
break;
}
}
}
}
return xmlLoggingValue;
}
std::wstring GetStringSetting(const std::wstring& settingKey) {
auto it = SettingsQueryMap.find(settingKey);
if (it == SettingsQueryMap.end()) {
vddlog("e", "requested data not found in xml, consider updating xml!");
return L"";
}
std::wstring regName = it->second.first;
std::wstring xmlName = it->second.second;
std::wstring settingsname = confpath + L"\\vdd_settings.xml";
HKEY hKey;
DWORD dwBufferSize = MAX_PATH;
wchar_t buffer[MAX_PATH];
LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\MikeTheTech\\VirtualDisplayDriver", 0, KEY_READ, &hKey);
if (lResult == ERROR_SUCCESS) {
lResult = RegQueryValueExW(hKey, regName.c_str(), NULL, NULL, (LPBYTE)buffer, &dwBufferSize);
RegCloseKey(hKey);
if (lResult == ERROR_SUCCESS) {
LogQueries("d", xmlName + L" - Retrieved string value from registry: " + buffer);
return std::wstring(buffer);
}
else {
LogQueries("d", xmlName + L" - Failed to retrieve string value from registry. Attempting to read as XML.");
}
}
CComPtr<IStream> pFileStream;
HRESULT hr = SHCreateStreamOnFileEx(settingsname.c_str(), STGM_READ, FILE_ATTRIBUTE_NORMAL, FALSE, nullptr, &pFileStream);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to create file stream for XML settings.");
return L"";
}
CComPtr<IXmlReader> pReader;
hr = CreateXmlReader(__uuidof(IXmlReader), (void**)&pReader, nullptr);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to create XML reader.");
return L"";
}
hr = pReader->SetInput(pFileStream);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to set input for XML reader.");
return L"";
}
XmlNodeType nodeType;
const wchar_t* pwszLocalName;
std::wstring xmlLoggingValue = L"";
while (S_OK == pReader->Read(&nodeType)) {
if (nodeType == XmlNodeType_Element) {
pReader->GetLocalName(&pwszLocalName, nullptr);
if (pwszLocalName && wcscmp(pwszLocalName, xmlName.c_str()) == 0) {
pReader->Read(&nodeType);
if (nodeType == XmlNodeType_Text) {
const wchar_t* pwszValue;
pReader->GetValue(&pwszValue, nullptr);
if (pwszValue) {
xmlLoggingValue = pwszValue;
}
LogQueries("i", xmlName + L" - Retrieved from XML: " + xmlLoggingValue);
break;
}
}
}
}
return xmlLoggingValue;
}
double GetDoubleSetting(const std::wstring& settingKey) {
auto it = SettingsQueryMap.find(settingKey);
if (it == SettingsQueryMap.end()) {
vddlog("e", "requested data not found in xml, consider updating xml!");
return 0.0;
}
std::wstring regName = it->second.first;
std::wstring xmlName = it->second.second;
std::wstring settingsname = confpath + L"\\vdd_settings.xml";
HKEY hKey;
DWORD dwBufferSize = MAX_PATH;
wchar_t buffer[MAX_PATH];
LONG lResult = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\MikeTheTech\\VirtualDisplayDriver", 0, KEY_READ, &hKey);
if (lResult == ERROR_SUCCESS) {
lResult = RegQueryValueExW(hKey, regName.c_str(), NULL, NULL, (LPBYTE)buffer, &dwBufferSize);
if (lResult == ERROR_SUCCESS) {
RegCloseKey(hKey);
try {
double regValue = std::stod(buffer);
LogQueries("d", xmlName + L" - Retrieved from registry: " + std::to_wstring(regValue));
return regValue;
}
catch (const std::exception&) {
LogQueries("d", xmlName + L" - Failed to convert registry value to double.");
}
}
else {
RegCloseKey(hKey);
}
}
CComPtr<IStream> pFileStream;
HRESULT hr = SHCreateStreamOnFileEx(settingsname.c_str(), STGM_READ, FILE_ATTRIBUTE_NORMAL, FALSE, nullptr, &pFileStream);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to create file stream for XML settings.");
return 0.0;
}
CComPtr<IXmlReader> pReader;
hr = CreateXmlReader(__uuidof(IXmlReader), (void**)&pReader, nullptr);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to create XML reader.");
return 0.0;
}
hr = pReader->SetInput(pFileStream);
if (FAILED(hr)) {
LogQueries("d", xmlName + L" - Failed to set input for XML reader.");
return 0.0;
}
XmlNodeType nodeType;
const wchar_t* pwszLocalName;
double xmlLoggingValue = 0.0;
while (S_OK == pReader->Read(&nodeType)) {
if (nodeType == XmlNodeType_Element) {
pReader->GetLocalName(&pwszLocalName, nullptr);
if (pwszLocalName && wcscmp(pwszLocalName, xmlName.c_str()) == 0) {
pReader->Read(&nodeType);
if (nodeType == XmlNodeType_Text) {
const wchar_t* pwszValue;
pReader->GetValue(&pwszValue, nullptr);
if (pwszValue) {
try {
xmlLoggingValue = std::stod(pwszValue);
LogQueries("i", xmlName + L" - Retrieved from XML: " + std::to_wstring(xmlLoggingValue));
}
catch (const std::exception&) {
LogQueries("d", xmlName + L" - Failed to convert XML value to double.");
}
}
break;
}
}
}
}
return xmlLoggingValue;
}
// === EDID PROFILE LOADING FUNCTION ===
struct EdidProfileData {
vector<tuple<int, int, int, int>> modes;
bool hdr10Supported = false;
bool dolbyVisionSupported = false;
bool hdr10PlusSupported = false;
double maxLuminance = 0.0;
double minLuminance = 0.0;
wstring primaryColorSpace = L"sRGB";
double gamma = 2.2;
double redX = 0.64, redY = 0.33;
double greenX = 0.30, greenY = 0.60;
double blueX = 0.15, blueY = 0.06;
double whiteX = 0.3127, whiteY = 0.3290;
int preferredWidth = 1920;
int preferredHeight = 1080;
double preferredRefresh = 60.0;
};
// === COLOR SPACE AND GAMMA STRUCTURES ===
struct VddColorMatrix {
FLOAT matrix[3][4] = {}; // 3x4 color space transformation matrix - zero initialized
bool isValid = false;
};
struct VddGammaRamp {
FLOAT gamma = 2.2f;
wstring colorSpace;
VddColorMatrix matrix = {};
bool useMatrix = false;
bool isValid = false;
};
// === GAMMA AND COLOR SPACE STORAGE ===
std::map<IDDCX_MONITOR, VddGammaRamp> g_GammaRampStore;
// === COLOR SPACE AND GAMMA CONVERSION FUNCTIONS ===
// Convert gamma value to 3x4 color space transformation matrix
VddColorMatrix ConvertGammaToMatrix(double gamma, const wstring& colorSpace) {
VddColorMatrix matrix = {};
// Identity matrix as base
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
matrix.matrix[i][j] = (i == j) ? 1.0f : 0.0f;
}
}
// Apply gamma correction to diagonal elements
float gammaValue = static_cast<float>(gamma);
if (colorSpace == L"sRGB") {
// sRGB gamma correction (2.2)
matrix.matrix[0][0] = gammaValue / 2.2f; // Red
matrix.matrix[1][1] = gammaValue / 2.2f; // Green
matrix.matrix[2][2] = gammaValue / 2.2f; // Blue
}
else if (colorSpace == L"DCI-P3") {
// DCI-P3 color space transformation with gamma
// P3 to sRGB matrix with gamma correction
matrix.matrix[0][0] = 1.2249f * (gammaValue / 2.4f);
matrix.matrix[0][1] = -0.2247f;
matrix.matrix[0][2] = 0.0f;
matrix.matrix[1][0] = -0.0420f;
matrix.matrix[1][1] = 1.0419f * (gammaValue / 2.4f);
matrix.matrix[1][2] = 0.0f;
matrix.matrix[2][0] = -0.0196f;
matrix.matrix[2][1] = -0.0786f;
matrix.matrix[2][2] = 1.0982f * (gammaValue / 2.4f);
}
else if (colorSpace == L"Rec.2020") {
// Rec.2020 to sRGB matrix with gamma correction
matrix.matrix[0][0] = 1.7347f * (gammaValue / 2.4f);
matrix.matrix[0][1] = -0.7347f;
matrix.matrix[0][2] = 0.0f;
matrix.matrix[1][0] = -0.1316f;
matrix.matrix[1][1] = 1.1316f * (gammaValue / 2.4f);
matrix.matrix[1][2] = 0.0f;
matrix.matrix[2][0] = -0.0241f;
matrix.matrix[2][1] = -0.1289f;
matrix.matrix[2][2] = 1.1530f * (gammaValue / 2.4f);
}
else if (colorSpace == L"Adobe_RGB") {
// Adobe RGB with gamma correction
matrix.matrix[0][0] = 1.0f * (gammaValue / 2.2f);
matrix.matrix[1][1] = 1.0f * (gammaValue / 2.2f);
matrix.matrix[2][2] = 1.0f * (gammaValue / 2.2f);
}
else {
// Default to sRGB for unknown color spaces
matrix.matrix[0][0] = gammaValue / 2.2f;
matrix.matrix[1][1] = gammaValue / 2.2f;
matrix.matrix[2][2] = gammaValue / 2.2f;
}
matrix.isValid = true;
return matrix;
}
// Convert EDID profile to gamma ramp
VddGammaRamp ConvertEdidToGammaRamp(const EdidProfileData& profile) {
VddGammaRamp gammaRamp = {};
gammaRamp.gamma = static_cast<FLOAT>(profile.gamma);
gammaRamp.colorSpace = profile.primaryColorSpace;
// Generate matrix if matrix transforms are enabled
if (enableMatrixTransform) {
gammaRamp.matrix = ConvertGammaToMatrix(profile.gamma, profile.primaryColorSpace);
gammaRamp.useMatrix = gammaRamp.matrix.isValid;
}
gammaRamp.isValid = colorSpaceEnabled;
return gammaRamp;
}
// Convert manual settings to gamma ramp
VddGammaRamp ConvertManualToGammaRamp() {
VddGammaRamp gammaRamp = {};
gammaRamp.gamma = static_cast<FLOAT>(gammaCorrection);
gammaRamp.colorSpace = primaryColorSpace;
// Generate matrix if matrix transforms are enabled
if (enableMatrixTransform) {
gammaRamp.matrix = ConvertGammaToMatrix(gammaCorrection, primaryColorSpace);
gammaRamp.useMatrix = gammaRamp.matrix.isValid;
}
gammaRamp.isValid = colorSpaceEnabled;
return gammaRamp;
}
// Enhanced color format selection based on color space
IDDCX_BITS_PER_COMPONENT SelectBitDepthFromColorSpace(const wstring& colorSpace) {
if (autoSelectFromColorSpace) {
if (colorSpace == L"Rec.2020") {
return IDDCX_BITS_PER_COMPONENT_10; // HDR10 - 10-bit for wide color gamut
} else if (colorSpace == L"DCI-P3") {
return IDDCX_BITS_PER_COMPONENT_10; // Wide color gamut - 10-bit
} else if (colorSpace == L"Adobe_RGB") {
return IDDCX_BITS_PER_COMPONENT_10; // Professional - 10-bit
} else {
return IDDCX_BITS_PER_COMPONENT_8; // sRGB - 8-bit
}
}
// Manual bit depth override
if (forceBitDepth == L"8") {
return IDDCX_BITS_PER_COMPONENT_8;
} else if (forceBitDepth == L"10") {
return IDDCX_BITS_PER_COMPONENT_10;
} else if (forceBitDepth == L"12") {
return IDDCX_BITS_PER_COMPONENT_12;
}
// Default to existing color depth logic
return HDRPlus ? IDDCX_BITS_PER_COMPONENT_12 :
(SDR10 ? IDDCX_BITS_PER_COMPONENT_10 : IDDCX_BITS_PER_COMPONENT_8);
}
// === SMPTE ST.2086 HDR METADATA STRUCTURE ===
struct VddHdrMetadata {
// SMPTE ST.2086 Display Primaries (scaled 0-50000) - zero initialized
UINT16 display_primaries_x[3] = {}; // R, G, B chromaticity x coordinates
UINT16 display_primaries_y[3] = {}; // R, G, B chromaticity y coordinates
UINT16 white_point_x = 0; // White point x coordinate
UINT16 white_point_y = 0; // White point y coordinate
// Luminance values (0.0001 cd/m² units for SMPTE ST.2086)
UINT32 max_display_mastering_luminance = 0;
UINT32 min_display_mastering_luminance = 0;
// Content light level (nits)
UINT16 max_content_light_level = 0;
UINT16 max_frame_avg_light_level = 0;
// Validation flag
bool isValid = false;
};
// === HDR METADATA STORAGE ===
std::map<IDDCX_MONITOR, VddHdrMetadata> g_HdrMetadataStore;
// === HDR METADATA CONVERSION FUNCTIONS ===
// Convert EDID chromaticity (0.0-1.0) to SMPTE ST.2086 format (0-50000)
UINT16 ConvertChromaticityToSmpte(double edidValue) {
// Clamp to valid range
if (edidValue < 0.0) edidValue = 0.0;
if (edidValue > 1.0) edidValue = 1.0;
return static_cast<UINT16>(edidValue * 50000.0);
}
// Convert EDID luminance (nits) to SMPTE ST.2086 format (0.0001 cd/m² units)
UINT32 ConvertLuminanceToSmpte(double nits) {
// Clamp to reasonable range (0.0001 to 10000 nits)
if (nits < 0.0001) nits = 0.0001;
if (nits > 10000.0) nits = 10000.0;
return static_cast<UINT32>(nits * 10000.0);
}
// Convert EDID profile data to SMPTE ST.2086 HDR metadata
VddHdrMetadata ConvertEdidToSmpteMetadata(const EdidProfileData& profile) {
VddHdrMetadata metadata = {};
// Convert chromaticity coordinates
metadata.display_primaries_x[0] = ConvertChromaticityToSmpte(profile.redX); // Red
metadata.display_primaries_y[0] = ConvertChromaticityToSmpte(profile.redY);
metadata.display_primaries_x[1] = ConvertChromaticityToSmpte(profile.greenX); // Green
metadata.display_primaries_y[1] = ConvertChromaticityToSmpte(profile.greenY);
metadata.display_primaries_x[2] = ConvertChromaticityToSmpte(profile.blueX); // Blue
metadata.display_primaries_y[2] = ConvertChromaticityToSmpte(profile.blueY);
// Convert white point
metadata.white_point_x = ConvertChromaticityToSmpte(profile.whiteX);
metadata.white_point_y = ConvertChromaticityToSmpte(profile.whiteY);
// Convert luminance values
metadata.max_display_mastering_luminance = ConvertLuminanceToSmpte(profile.maxLuminance);
metadata.min_display_mastering_luminance = ConvertLuminanceToSmpte(profile.minLuminance);
// Use configured content light levels (from vdd_settings.xml)
metadata.max_content_light_level = static_cast<UINT16>(maxContentLightLevel);
metadata.max_frame_avg_light_level = static_cast<UINT16>(maxFrameAvgLightLevel);
// Mark as valid if we have HDR10 support
metadata.isValid = profile.hdr10Supported && hdr10StaticMetadataEnabled;
return metadata;
}
// Convert manual settings to SMPTE ST.2086 HDR metadata
VddHdrMetadata ConvertManualToSmpteMetadata() {
VddHdrMetadata metadata = {};
// Convert manual chromaticity coordinates
metadata.display_primaries_x[0] = ConvertChromaticityToSmpte(redX); // Red
metadata.display_primaries_y[0] = ConvertChromaticityToSmpte(redY);
metadata.display_primaries_x[1] = ConvertChromaticityToSmpte(greenX); // Green
metadata.display_primaries_y[1] = ConvertChromaticityToSmpte(greenY);
metadata.display_primaries_x[2] = ConvertChromaticityToSmpte(blueX); // Blue
metadata.display_primaries_y[2] = ConvertChromaticityToSmpte(blueY);
// Convert manual white point
metadata.white_point_x = ConvertChromaticityToSmpte(whiteX);
metadata.white_point_y = ConvertChromaticityToSmpte(whiteY);
// Convert manual luminance values
metadata.max_display_mastering_luminance = ConvertLuminanceToSmpte(maxDisplayMasteringLuminance);
metadata.min_display_mastering_luminance = ConvertLuminanceToSmpte(minDisplayMasteringLuminance);
// Use configured content light levels
metadata.max_content_light_level = static_cast<UINT16>(maxContentLightLevel);
metadata.max_frame_avg_light_level = static_cast<UINT16>(maxFrameAvgLightLevel);
// Mark as valid if HDR10 metadata is enabled and color primaries are enabled
metadata.isValid = hdr10StaticMetadataEnabled && colorPrimariesEnabled;
return metadata;
}
// === ENHANCED MODE MANAGEMENT FUNCTIONS ===
// Generate modes from EDID with advanced filtering and optimization
vector<tuple<int, int, int, int>> GenerateModesFromEdid(const EdidProfileData& profile) {
vector<tuple<int, int, int, int>> generatedModes;
if (!autoResolutionsEnabled) {
vddlog("i", "Auto resolutions disabled, skipping EDID mode generation");
return generatedModes;
}
for (const auto& mode : profile.modes) {
int width = get<0>(mode);
int height = get<1>(mode);
int refreshRateMultiplier = get<2>(mode);
int nominalRefreshRate = get<3>(mode);
// Apply comprehensive filtering
bool passesFilter = true;
// Resolution range filtering
if (width < minResolutionWidth || width > maxResolutionWidth ||
height < minResolutionHeight || height > maxResolutionHeight) {
passesFilter = false;
}
// Refresh rate filtering
if (nominalRefreshRate < minRefreshRate || nominalRefreshRate > maxRefreshRate) {
passesFilter = false;
}
// Fractional rate filtering
if (excludeFractionalRates && refreshRateMultiplier != 1000) {
passesFilter = false;
}
// Add custom quality filtering
if (passesFilter) {
// Prefer standard aspect ratios for better compatibility
double aspectRatio = static_cast<double>(width) / height;
bool isStandardAspect = (abs(aspectRatio - 16.0/9.0) < 0.01) || // 16:9
(abs(aspectRatio - 16.0/10.0) < 0.01) || // 16:10
(abs(aspectRatio - 4.0/3.0) < 0.01) || // 4:3
(abs(aspectRatio - 21.0/9.0) < 0.01); // 21:9
// Log non-standard aspect ratios for information
if (!isStandardAspect) {
stringstream ss;
ss << "Including non-standard aspect ratio mode: " << width << "x" << height
<< " (ratio: " << fixed << setprecision(2) << aspectRatio << ")";
vddlog("d", ss.str().c_str());
}