-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathCsvHelper.h
More file actions
1278 lines (1176 loc) · 47.6 KB
/
CsvHelper.h
File metadata and controls
1278 lines (1176 loc) · 47.6 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) 2022-2023 Intel Corporation
// SPDX-License-Identifier: MIT
#pragma once
#include "../PresentMonAPI2/PresentMonAPI.h"
#include "../PresentMonAPI2/Internal.h"
#include "../PresentMonAPIWrapper/PresentMonAPIWrapper.h"
#include "../CommonUtilities/str/String.h"
#include <Windows.h>
#include <vector>
#include <string>
#include <stdexcept>
#include <map>
#include <cmath>
#include <limits>
#include <optional>
#include <cctype>
#include <filesystem>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace fs = std::filesystem;
enum Header {
Header_Application,
Header_ProcessID,
Header_SwapChainAddress,
Header_PresentRuntime,
Header_SyncInterval,
Header_PresentFlags,
Header_AllowsTearing,
Header_PresentMode,
Header_FrameType,
Header_PresentStartQPC,
Header_MsBetweenSimulationStart,
Header_MsPCLatency,
Header_CPUStartTime,
Header_CPUStartQPC,
Header_CPUStartQPCTime,
Header_CPUStartDateTime,
Header_MsBetweenAppStart,
Header_MsCPUBusy,
Header_MsCPUWait,
Header_MsGPULatency,
Header_MsGPUTime,
Header_MsGPUBusy,
Header_MsGPUWait,
Header_MsVideoBusy,
Header_MsAnimationError,
Header_AnimationTime,
Header_MsFlipDelay,
Header_MsClickToPhotonLatency,
Header_MsAllInputToPhotonLatency,
// App Provided Metrics
Header_MsInstrumentedLatency,
// --v1_metrics
Header_Runtime,
Header_Dropped,
Header_TimeInSeconds,
Header_MsBetweenPresents,
Header_MsInPresentAPI,
Header_MsBetweenDisplayChange,
Header_MsUntilRenderComplete,
Header_MsUntilDisplayed,
Header_MsUntilRenderStart,
Header_MsGPUActive,
Header_MsGPUVideoActive,
Header_MsSinceInput,
Header_QPCTime,
// Deprecated
Header_WasBatched,
Header_DwmNotified,
// Special values:
KnownHeaderCount,
UnknownHeader,
};
constexpr double kMissingMetricValue = std::numeric_limits<double>::quiet_NaN();
struct v2Metrics {
std::string appName;
uint32_t processId = 0;
uint64_t swapChain = 0;
PM_GRAPHICS_RUNTIME runtime = PM_GRAPHICS_RUNTIME_UNKNOWN;
int32_t syncInterval = 0;
uint32_t presentFlags = 0;
uint32_t allowsTearing = 0;
PM_PRESENT_MODE presentMode = PM_PRESENT_MODE_UNKNOWN;
PM_FRAME_TYPE frameType = PM_FRAME_TYPE_NOT_SET;
uint64_t presentStartQPC = 0;
double msBetweenPresents = 0.;
double msInPresentAPI = 0.;
double msRenderPresentLatency = 0.;
uint64_t cpuFrameQpc = 0;
double msBetweenAppStart = 0.;
double msCpuBusy = 0.;
double msCpuWait = 0.;
double msGpuLatency = 0.;
double msGpuTime = 0.;
double msGpuBusy = 0.;
double msGpuWait = 0.;
double msVideoBusy = 0.;
double msBetweenSimStart = kMissingMetricValue;
double msUntilDisplayed = kMissingMetricValue;
double msBetweenDisplayChange = kMissingMetricValue;
double msPcLatency = kMissingMetricValue;
double msAnimationError = kMissingMetricValue;
double animationTime = kMissingMetricValue;
double msFlipDelay = kMissingMetricValue;
double msClickToPhotonLatency = kMissingMetricValue;
double msAllInputToPhotonLatency = kMissingMetricValue;
double msInstrumentedLatency = kMissingMetricValue;
double msInstrumentedRenderLatency = kMissingMetricValue;
double msInstrumentedSleep = kMissingMetricValue;
double msInstrumentedGPULatency = kMissingMetricValue;
double msReadyTimeToDisplayLatency = kMissingMetricValue;
double msReprojectedLatency = kMissingMetricValue;
};
constexpr char const* GetHeaderString(Header h)
{
switch (h) {
case Header_Application: return "Application";
case Header_ProcessID: return "ProcessID";
case Header_SwapChainAddress: return "SwapChainAddress";
case Header_PresentRuntime: return "PresentRuntime";
case Header_SyncInterval: return "SyncInterval";
case Header_PresentFlags: return "PresentFlags";
case Header_AllowsTearing: return "AllowsTearing";
case Header_PresentMode: return "PresentMode";
case Header_FrameType: return "FrameType";
case Header_PresentStartQPC: return "PresentStartQPC";
case Header_MsBetweenSimulationStart: return "MsBetweenSimulationStart";
case Header_MsPCLatency: return "MsPCLatency";
case Header_CPUStartTime: return "CPUStartTime";
case Header_CPUStartQPC: return "CPUStartQPC";
case Header_CPUStartQPCTime: return "CPUStartQPCTime";
case Header_CPUStartDateTime: return "CPUStartDateTime";
case Header_MsBetweenAppStart: return "MsBetweenAppStart";
case Header_MsCPUBusy: return "MsCPUBusy";
case Header_MsCPUWait: return "MsCPUWait";
case Header_MsGPULatency: return "MsGPULatency";
case Header_MsGPUTime: return "MsGPUTime";
case Header_MsGPUBusy: return "MsGPUBusy";
case Header_MsFlipDelay: return "MsFlipDelay";
case Header_MsVideoBusy: return "MsVideoBusy";
case Header_MsGPUWait: return "MsGPUWait";
case Header_MsAnimationError: return "MsAnimationError";
case Header_AnimationTime: return "AnimationTime";
case Header_MsClickToPhotonLatency: return "MsClickToPhotonLatency";
case Header_MsAllInputToPhotonLatency: return "MsAllInputToPhotonLatency";
case Header_Runtime: return "Runtime";
case Header_Dropped: return "Dropped";
case Header_TimeInSeconds: return "TimeInQPC";
case Header_MsBetweenPresents: return "MsBetweenPresents";
case Header_MsInPresentAPI: return "MsInPresentAPI";
case Header_MsBetweenDisplayChange: return "MsBetweenDisplayChange";
case Header_MsUntilRenderComplete: return "MsRenderPresentLatency";
case Header_MsUntilDisplayed: return "MsUntilDisplayed";
case Header_MsUntilRenderStart: return "msUntilRenderStart";
case Header_MsGPUActive: return "msGPUActive";
case Header_MsGPUVideoActive: return "msGPUVideoActive";
case Header_MsSinceInput: return "msSinceInput";
case Header_QPCTime: return "QPCTime";
case Header_WasBatched: return "WasBatched";
case Header_DwmNotified: return "DwmNotified";
case Header_MsInstrumentedLatency: return "MsInstrumentedLatency";
default: return "<unknown>";
}
}
std::wstring CreateErrorString(Header columnId, size_t line)
{
std::wstring errorMessage = L"Invalid ";
errorMessage += pmon::util::str::ToWide(GetHeaderString(columnId));
errorMessage += L" at line: ";
errorMessage += std::to_wstring(line);
return errorMessage;
}
class CsvException : public std::runtime_error {
public:
explicit CsvException(const std::string& msg) : std::runtime_error(msg) {}
};
class CsvConversionException : public CsvException {
Header columnId_;
size_t line_;
std::string value_;
public:
CsvConversionException(Header columnId, size_t line, const std::string& value)
: CsvException(std::format("Invalid {} at line {}: '{}'",
GetHeaderString(columnId), line, value))
, columnId_(columnId)
, line_(line)
, value_(value)
{
}
Header GetColumnId() const { return columnId_; }
size_t GetLine() const { return line_; }
const std::string& GetValue() const { return value_; }
};
class CsvFileException : public CsvException {
public:
explicit CsvFileException(const std::string& msg) : CsvException(msg) {}
};
class CsvValidationException : public CsvException {
Header columnId_;
size_t line_;
// Helper to format values for error messages
template<typename T>
static auto FormatValue(const T& value) {
if constexpr (std::is_enum_v<T>) {
return static_cast<std::underlying_type_t<T>>(value);
} else {
return value;
}
}
public:
template<typename T>
CsvValidationException(Header columnId, size_t line, const T& receivedValue, const T& expectedValue)
: CsvException(std::format("{} at line {}: Do not match. Received value {}, Expected value {}",
GetHeaderString(columnId), line, FormatValue(receivedValue), FormatValue(expectedValue)))
, columnId_(columnId)
, line_(line)
{
}
Header GetColumnId() const { return columnId_; }
size_t GetLine() const { return line_; }
};
template <typename T>
class CharConvert {
public:
void Convert(const std::string data, T& convertedData, Header columnId, size_t line);
};
template <typename T>
void CharConvert<T>::Convert(const std::string data, T& convertedData, Header columnId, size_t line) {
if constexpr (std::is_same<T, double>::value) {
try
{
convertedData = std::stod(data);
}
catch (...) {
throw CsvConversionException(columnId, line, data);
}
}
else if constexpr (std::is_same<T, uint32_t>::value) {
try
{
convertedData = std::stoul(data);
}
catch (...) {
throw CsvConversionException(columnId, line, data);
}
}
else if constexpr (std::is_same<T, int32_t>::value) {
try
{
convertedData = std::stoi(data);
}
catch (...) {
throw CsvConversionException(columnId, line, data);
}
}
else if constexpr (std::is_same<T, uint64_t>::value) {
try
{
char* endptr;
unsigned long long result1;
if (data.size() > 2 && data[0] == '0' && (data[1] == 'x' || data[1] == 'X')) {
// Convert hexadecimal
result1 = std::strtoull(data.c_str(), &endptr, 16);
}
else {
// Convert decimal
result1 = std::strtoull(data.c_str(), &endptr, 10);
}
convertedData = static_cast<uint64_t>(result1);
}
catch (...) {
throw CsvConversionException(columnId, line, data);
}
}
else if constexpr (std::is_same<T, PM_GRAPHICS_RUNTIME>::value) {
if (data == "DXGI") {
convertedData = PM_GRAPHICS_RUNTIME_DXGI;
}
else if (data == "D3D9") {
convertedData = PM_GRAPHICS_RUNTIME_D3D9;
}
else if (data == "Other") {
convertedData = PM_GRAPHICS_RUNTIME_UNKNOWN;
}
else {
throw CsvConversionException(columnId, line, data);
}
}
else if constexpr (std::is_same<T, PM_PRESENT_MODE>::value) {
if (data == "Hardware: Legacy Flip") {
convertedData = PM_PRESENT_MODE_HARDWARE_LEGACY_FLIP;
}
else if (data == "Hardware: Legacy Copy to Front Buffer") {
convertedData = PM_PRESENT_MODE_HARDWARE_LEGACY_COPY_TO_FRONT_BUFFER;
}
else if (data == "Hardware: Independent Flip") {
convertedData = PM_PRESENT_MODE_HARDWARE_INDEPENDENT_FLIP;
}
else if (data == "Composed: Flip") {
convertedData = PM_PRESENT_MODE_COMPOSED_FLIP;
}
else if (data == "Composed: Copy with GPU GDI") {
convertedData = PM_PRESENT_MODE_COMPOSED_COPY_WITH_GPU_GDI;
}
else if (data == "Composed: Copy with CPU GDI") {
convertedData = PM_PRESENT_MODE_COMPOSED_COPY_WITH_CPU_GDI;
}
else if (data == "Hardware Composed: Independent Flip") {
convertedData = PM_PRESENT_MODE_HARDWARE_COMPOSED_INDEPENDENT_FLIP;
}
else if (data == "Other") {
convertedData = PM_PRESENT_MODE_UNKNOWN;
}
else {
throw CsvConversionException(Header_PresentMode, line, data);
}
}
else if constexpr (std::is_same<T, PM_FRAME_TYPE>::value) {
if (data == "NotSet") {
convertedData = PM_FRAME_TYPE_NOT_SET;
}
else if (data == "Unspecified") {
convertedData = PM_FRAME_TYPE_UNSPECIFIED;
}
else if (data == "Application") {
convertedData = PM_FRAME_TYPE_APPLICATION;
}
else if (data == "Repeated") {
convertedData = PM_FRAME_TYPE_REPEATED;
}
else if (data == "AMD_AFMF") {
convertedData = PM_FRAME_TYPE_AMD_AFMF;
}
else if (data == "Intel XeSS-FG") {
convertedData = PM_FRAME_TYPE_INTEL_XEFG;
}
else {
throw CsvConversionException(Header_FrameType, line, data);
}
}
else
{
throw CsvException("Unknown type conversion requested");
}
}
bool IsMissingMetricToken(const char* data)
{
if (data == nullptr) {
return true;
}
const char* tokenBegin = data;
while (*tokenBegin != '\0' && std::isspace(static_cast<unsigned char>(*tokenBegin))) {
++tokenBegin;
}
const char* tokenEnd = tokenBegin;
while (*tokenEnd != '\0') {
++tokenEnd;
}
while (tokenEnd > tokenBegin && std::isspace(static_cast<unsigned char>(*(tokenEnd - 1)))) {
--tokenEnd;
}
if (tokenBegin == tokenEnd) {
return true;
}
std::string token(tokenBegin, tokenEnd);
return _stricmp(token.c_str(), "NA") == 0 ||
_stricmp(token.c_str(), "N/A") == 0 ||
_stricmp(token.c_str(), "NaN") == 0;
}
double ParseMetricValue(const char* data, Header columnId, size_t line)
{
if (IsMissingMetricToken(data)) {
return kMissingMetricValue;
}
double convertedData = 0.;
CharConvert<double> converter;
converter.Convert(data, convertedData, columnId, line);
if (std::isnan(convertedData)) {
return kMissingMetricValue;
}
return convertedData;
}
size_t countDecimalPlaces(double value) {
std::string str = std::to_string(value);
auto dotPos = str.find('.');
if (dotPos == std::string::npos) return 0;
// Get the decimal part
std::string decimals = str.substr(dotPos + 1);
// Remove trailing zeros
decimals.erase(decimals.find_last_not_of('0') + 1);
// Count non-zero decimal digits
size_t count = 0;
for (char c : decimals) {
if (c != '0') ++count;
}
return count;
}
bool ValidateFrameType(PM_FRAME_TYPE gold, PM_FRAME_TYPE test) {
// Gold FrameType may be NotSet, Repeated or Application. If Gold is one of NotSet, Unspecified or Repeated test must match. If Gold is
// Application, test can be Application, NotSet, or Repeated. The reason for this is if the gold file was generated from PresentMon version
// that had DEBUG_FRAME_TYPE defined.
if (gold == PM_FRAME_TYPE_NOT_SET || gold == PM_FRAME_TYPE_UNSPECIFIED || gold == PM_FRAME_TYPE_REPEATED) {
return test == gold;
}
else if (gold == PM_FRAME_TYPE_APPLICATION) {
return test == PM_FRAME_TYPE_APPLICATION || test == PM_FRAME_TYPE_NOT_SET || test == PM_FRAME_TYPE_REPEATED;
}
else {
return gold == test;
}
}
template<typename T>
void ValidateOrThrow(Header columnId, size_t line, const T& received, const T& expected) {
if constexpr (std::is_same_v<T, double>) {
// Both NaN is considered a match (both represent missing/invalid data)
if (std::isnan(received) && std::isnan(expected)) {
return;
}
// One NaN and one value is a mismatch
if (std::isnan(received) || std::isnan(expected)) {
throw CsvValidationException(columnId, line, received, expected);
}
// Both are valid numbers, compare with threshold
auto min = std::min(countDecimalPlaces(received), countDecimalPlaces(expected));
double threshold = pow(0.1, min);
double difference = received - expected;
if (difference <= -threshold || difference >= threshold) {
throw CsvValidationException(columnId, line, received, expected);
}
}
else {
if (received != expected) {
throw CsvValidationException(columnId, line, received, expected);
}
}
}
// Overload for std::optional - treats empty optional as NaN
void ValidateOrThrow(Header columnId, size_t line, const std::optional<double>& received, double expected) {
if (received.has_value()) {
ValidateOrThrow(columnId, line, received.value(), expected);
} else {
// No value in CSV (optional is empty), expected should be NaN
if (!std::isnan(expected)) {
throw CsvValidationException(columnId, line, std::nan(""), expected);
}
}
}
template<typename T>
bool Validate(const T& param1, const T& param2) {
if constexpr (std::is_same<T, double>::value) {
auto min = std::min(countDecimalPlaces(param1), countDecimalPlaces(param2));
double threshold = pow(0.1, min);
double difference = param1 - param2;
if (difference > -threshold && difference < threshold) {
return true;
}
else
{
return false;
}
}
else {
return param1 == param2;
}
}
bool ValidateMetricValue(double expected, double actual)
{
const auto expectedMissing = std::isnan(expected);
const auto actualMissing = std::isnan(actual);
if (actualMissing) {
// If actual is missing, it's only valid if expected is exactly 0.0,
// otherwise it would be a mismatch with the gold file. The intent is to eventually
// migrate all gold files to use NA or NAN for missing metrics, but in the meantime
// we want to allow 0.0 as a valid expected value for metrics yet to be transitioned.
return expectedMissing || expected == 0.0;
}
if (expectedMissing) {
return false;
}
return Validate(expected, actual);
}
std::optional<std::ofstream> CreateCsvFile(std::string& output_dir, std::string& processName)
{
// Setup csv file
time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
tm local_time;
localtime_s(&local_time, &now);
try {
// Use filesystem to construct the path properly
fs::path outputPath(output_dir);
fs::path fileName = processName + "_" +
std::to_string(local_time.tm_year + 1900) +
std::to_string(local_time.tm_mon + 1) +
std::to_string(local_time.tm_mday) +
std::to_string(local_time.tm_hour) +
std::to_string(local_time.tm_min) +
std::to_string(local_time.tm_sec) + ".csv";
fs::path fullPath = outputPath / fileName;
std::ofstream csvFile(fullPath);
if (!csvFile.is_open()) {
return std::nullopt;
}
csvFile <<
"Application,ProcessID,SwapChainAddress,PresentRuntime"
",SyncInterval,PresentFlags,AllowsTearing,PresentMode"
",FrameType,TimeInQPC,MsBetweenSimulationStart,MsBetweenPresents"
",MsBetweenDisplayChange,MsInPresent,MsRenderPresentLatency"
",MsUntilDisplayed,MsPCLatency,CPUStartQPC,MsBetweenAppStart"
",MsCPUBusy,MsCPUWait,MsGPULatency,MsGPUTime,MsGPUBusy,MsGPUWait"
",MsVideoBusy,MsAnimationError,AnimationTime,MsFlipDelay,MsAllInputToPhotonLatency"
",MsClickToPhotonLatency,MsInstrumentedLatency";
csvFile << std::endl;
return csvFile;
}
catch (...) {
return std::nullopt;
}
}
std::string TranslatePresentMode(PM_PRESENT_MODE present_mode) {
switch (present_mode) {
case PM_PRESENT_MODE::PM_PRESENT_MODE_HARDWARE_LEGACY_FLIP:
return "Hardware: Legacy Flip";
case PM_PRESENT_MODE::PM_PRESENT_MODE_HARDWARE_LEGACY_COPY_TO_FRONT_BUFFER:
return "Hardware: Legacy Copy to front buffer";
case PM_PRESENT_MODE::PM_PRESENT_MODE_HARDWARE_INDEPENDENT_FLIP:
return "Hardware: Independent Flip";
case PM_PRESENT_MODE::PM_PRESENT_MODE_COMPOSED_FLIP:
return "Composed: Flip";
case PM_PRESENT_MODE::PM_PRESENT_MODE_HARDWARE_COMPOSED_INDEPENDENT_FLIP:
return "Hardware Composed: Independent Flip";
case PM_PRESENT_MODE::PM_PRESENT_MODE_COMPOSED_COPY_WITH_GPU_GDI:
return "Composed: Copy with GPU GDI";
case PM_PRESENT_MODE::PM_PRESENT_MODE_COMPOSED_COPY_WITH_CPU_GDI:
return "Composed: Copy with CPU GDI";
default:
return("Other");
}
}
std::string TranslateGraphicsRuntime(PM_GRAPHICS_RUNTIME graphicsRuntime) {
switch (graphicsRuntime) {
case PM_GRAPHICS_RUNTIME_UNKNOWN:
return "UNKNOWN";
case PM_GRAPHICS_RUNTIME_DXGI:
return "DXGI";
case PM_GRAPHICS_RUNTIME_D3D9:
return "D3D9";
default:
return "UNKNOWN";
}
}
std::string TranslateFrameType(PM_FRAME_TYPE frameType) {
switch (frameType) {
case PM_FRAME_TYPE_NOT_SET:
case PM_FRAME_TYPE_UNSPECIFIED:
case PM_FRAME_TYPE_APPLICATION:
return "Application";
case PM_FRAME_TYPE_AMD_AFMF:
return "AMD_AFMF";
case PM_FRAME_TYPE_INTEL_XEFG:
return "Intel XeSS-FG";
default:
return "<Unknown>";
}
}
void WriteToCSV(std::optional<std::ofstream>& debugCsvFile, const std::string& processName, const unsigned int& processId,
PM_QUERY_ELEMENT(&queryElements)[29], pmapi::BlobContainer& blobs)
{
if (!debugCsvFile.has_value()) {
return;
}
try {
for (auto pBlob : blobs) {
const auto swapChain = *reinterpret_cast<const uint64_t*>(&pBlob[queryElements[0].dataOffset]);
const auto graphicsRuntime = *reinterpret_cast<const PM_GRAPHICS_RUNTIME*>(&pBlob[queryElements[1].dataOffset]);
const auto syncInterval = *reinterpret_cast<const int32_t*>(&pBlob[queryElements[2].dataOffset]);
const auto presentFlags = *reinterpret_cast<const uint32_t*>(&pBlob[queryElements[3].dataOffset]);
const auto allowsTearing = *reinterpret_cast<const bool*>(&pBlob[queryElements[4].dataOffset]);
const auto presentMode = *reinterpret_cast<const PM_PRESENT_MODE*>(&pBlob[queryElements[5].dataOffset]);
const auto frameType = *reinterpret_cast<const PM_FRAME_TYPE*>(&pBlob[queryElements[6].dataOffset]);
const auto timeQpc = *reinterpret_cast<const uint64_t*>(&pBlob[queryElements[7].dataOffset]);
const auto msBetweenSimStartTime = *reinterpret_cast<const double*>(&pBlob[queryElements[8].dataOffset]);
const auto msBetweenPresents = *reinterpret_cast<const double*>(&pBlob[queryElements[9].dataOffset]);
const auto msBetweenDisplayChange = *reinterpret_cast<const double*>(&pBlob[queryElements[10].dataOffset]);
const auto msInPresentApi = *reinterpret_cast<const double*>(&pBlob[queryElements[11].dataOffset]);
const auto msRenderPresentLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[12].dataOffset]);
const auto msUntilDisplayed = *reinterpret_cast<const double*>(&pBlob[queryElements[13].dataOffset]);
const auto msPcLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[14].dataOffset]);
const auto cpuStartQpc = *reinterpret_cast<const uint64_t*>(&pBlob[queryElements[15].dataOffset]);
const auto msBetweenAppStart = *reinterpret_cast<const double*>(&pBlob[queryElements[16].dataOffset]);
const auto msCpuBusy = *reinterpret_cast<const double*>(&pBlob[queryElements[17].dataOffset]);
const auto msCpuWait = *reinterpret_cast<const double*>(&pBlob[queryElements[18].dataOffset]);
const auto msGpuLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[19].dataOffset]);
const auto msGpuTime = *reinterpret_cast<const double*>(&pBlob[queryElements[20].dataOffset]);
const auto msGpuBusy = *reinterpret_cast<const double*>(&pBlob[queryElements[21].dataOffset]);
const auto msGpuWait = *reinterpret_cast<const double*>(&pBlob[queryElements[22].dataOffset]);
const auto msAnimationError = *reinterpret_cast<const double*>(&pBlob[queryElements[23].dataOffset]);
const auto animationTime = *reinterpret_cast<const double*>(&pBlob[queryElements[24].dataOffset]);
const auto msFlipDelay = *reinterpret_cast<const double*>(&pBlob[queryElements[25].dataOffset]);
const auto msAllInputToPhotonLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[26].dataOffset]);
const auto msClickToPhotonLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[27].dataOffset]);
const auto msInstrumentedLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[28].dataOffset]);
*debugCsvFile << processName << ",";
*debugCsvFile << processId << ",";
*debugCsvFile << std::hex << "0x" << std::dec << swapChain << ",";
*debugCsvFile << TranslateGraphicsRuntime(graphicsRuntime) << ",";
*debugCsvFile << syncInterval << ",";
*debugCsvFile << presentFlags << ",";
*debugCsvFile << allowsTearing << ",";
*debugCsvFile << TranslatePresentMode(presentMode) << ",";
*debugCsvFile << TranslateFrameType(frameType) << ",";
*debugCsvFile << timeQpc << ","; // Time in QPC
*debugCsvFile << msBetweenSimStartTime << ",";
*debugCsvFile << msBetweenPresents << ",";
*debugCsvFile << msBetweenDisplayChange << ",";
*debugCsvFile << msInPresentApi << ",";
*debugCsvFile << msRenderPresentLatency << ",";
*debugCsvFile << msUntilDisplayed << ",";
*debugCsvFile << msPcLatency << ",";
*debugCsvFile << cpuStartQpc << ",";
*debugCsvFile << msBetweenAppStart << ",";
*debugCsvFile << msCpuBusy << ",";
*debugCsvFile << msCpuWait << ",";
*debugCsvFile << msGpuLatency << ",";
*debugCsvFile << msGpuTime << ",";
*debugCsvFile << msGpuBusy << ",";
*debugCsvFile << msGpuWait << ",";
*debugCsvFile << 0 << ",";
*debugCsvFile << msAnimationError << ",";
*debugCsvFile << animationTime << ",";
*debugCsvFile << msFlipDelay << ",";
*debugCsvFile << msAllInputToPhotonLatency << ",";
*debugCsvFile << msClickToPhotonLatency << ",";
*debugCsvFile << msInstrumentedLatency << std::endl;
}
}
catch (...) {
return;
}
}
class CsvParser {
public:
CsvParser();
bool Open(std::wstring const& path, uint32_t processId);
void Close();
bool VerifyBlobAgainstCsv(const std::string& processName, const unsigned int& processId,
PM_QUERY_ELEMENT(&queryElements)[29], pmapi::BlobContainer& blobs, std::optional<std::ofstream>& debugCsvFile);
bool ResetCsv();
private:
bool FindFirstRowWithPid(const unsigned int& processId);
bool ReadRow(bool gatherMetrics = false);
size_t GetColumnIndex(char const* header);
Header FindHeader(char const* header);
void CheckAll(size_t const* columnIndex, bool* ok, std::initializer_list<Header> const& headers);
void ConvertToMetricDataType(const char* data, Header columnId);
FILE* fp_ = nullptr;
size_t headerColumnIndex_[KnownHeaderCount] = {0};
char row_[1024] = {0};
size_t line_ = 0;
std::vector<char const*> cols_;
v2Metrics v2MetricRow_;
uint32_t processId_ = 0;
std::map<size_t, Header> activeColHeadersMap_;
};
CsvParser::CsvParser()
{}
bool CsvParser::VerifyBlobAgainstCsv(const std::string& processName, const unsigned int& processId,
PM_QUERY_ELEMENT(&queryElements)[29], pmapi::BlobContainer& blobs, std::optional<std::ofstream>& debugCsvFile)
{
if (debugCsvFile.has_value()) {
WriteToCSV(debugCsvFile, processName, processId, queryElements, blobs);
}
for (auto pBlob : blobs) {
// Read a row of blob data
//const auto appName = *reinterpret_cast<const char*>(&pBlob[queryElements[0].dataOffset]);
const auto swapChain = *reinterpret_cast<const uint64_t*>(&pBlob[queryElements[0].dataOffset]);
const auto graphicsRuntime = *reinterpret_cast<const PM_GRAPHICS_RUNTIME*>(&pBlob[queryElements[1].dataOffset]);
const auto syncInterval = *reinterpret_cast<const int32_t*>(&pBlob[queryElements[2].dataOffset]);
const auto presentFlags = *reinterpret_cast<const uint32_t*>(&pBlob[queryElements[3].dataOffset]);
const auto allowsTearing = *reinterpret_cast<const bool*>(&pBlob[queryElements[4].dataOffset]);
const auto presentMode = *reinterpret_cast<const PM_PRESENT_MODE*>(&pBlob[queryElements[5].dataOffset]);
const auto frameType = *reinterpret_cast<const PM_FRAME_TYPE*>(&pBlob[queryElements[6].dataOffset]);
const auto timeQpc = *reinterpret_cast<const uint64_t*>(&pBlob[queryElements[7].dataOffset]);
const auto msBetweenSimStartTime = *reinterpret_cast<const double*>(&pBlob[queryElements[8].dataOffset]);
const auto msBetweenPresents = *reinterpret_cast<const double*>(&pBlob[queryElements[9].dataOffset]);
const auto msBetweenDisplayChange = *reinterpret_cast<const double*>(&pBlob[queryElements[10].dataOffset]);
const auto msInPresentApi = *reinterpret_cast<const double*>(&pBlob[queryElements[11].dataOffset]);
const auto msRenderPresentLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[12].dataOffset]);
const auto msUntilDisplayed = *reinterpret_cast<const double*>(&pBlob[queryElements[13].dataOffset]);
const auto msPcLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[14].dataOffset]);
const auto cpuStartQpc = *reinterpret_cast<const uint64_t*>(&pBlob[queryElements[15].dataOffset]);
const auto msBetweenAppStart = *reinterpret_cast<const double*>(&pBlob[queryElements[16].dataOffset]);
const auto msCpuBusy = *reinterpret_cast<const double*>(&pBlob[queryElements[17].dataOffset]);
const auto msCpuWait = *reinterpret_cast<const double*>(&pBlob[queryElements[18].dataOffset]);
const auto msGpuLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[19].dataOffset]);
const auto msGpuTime = *reinterpret_cast<const double*>(&pBlob[queryElements[20].dataOffset]);
const auto msGpuBusy = *reinterpret_cast<const double*>(&pBlob[queryElements[21].dataOffset]);
const auto msGpuWait = *reinterpret_cast<const double*>(&pBlob[queryElements[22].dataOffset]);
const auto msAnimationError = *reinterpret_cast<const double*>(&pBlob[queryElements[23].dataOffset]);
const auto animationTime = *reinterpret_cast<const double*>(&pBlob[queryElements[24].dataOffset]);
const auto msFrameDelay = *reinterpret_cast<const double*>(&pBlob[queryElements[25].dataOffset]);
const auto msAllInputToPhotonLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[26].dataOffset]);
const auto msClickToPhotonLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[27].dataOffset]);
const auto msInstrumentedLatency = *reinterpret_cast<const double*>(&pBlob[queryElements[28].dataOffset]);
// Read rows until we find one with the process we are interested in
// or we are out of data.
for (;;) {
if (ReadRow(true)) {
if (v2MetricRow_.processId == processId_) {
break;
}
}
else
{
return true;
}
}
assert(v2MetricRow_.processId == processId_);
// Go through all of the active headers and validate results
for (const auto& pair : activeColHeadersMap_) {
bool columnsMatch = false;
switch (pair.second)
{
case Header_Application:
// Skip validation for application name
break;
case Header_ProcessID:
ValidateOrThrow(pair.second, line_, v2MetricRow_.processId, processId_);
break;
case Header_SwapChainAddress:
ValidateOrThrow(pair.second, line_, v2MetricRow_.swapChain, swapChain);
break;
case Header_Runtime:
ValidateOrThrow(pair.second, line_, v2MetricRow_.runtime, graphicsRuntime);
break;
case Header_SyncInterval:
ValidateOrThrow(pair.second, line_, v2MetricRow_.syncInterval, syncInterval);
break;
case Header_PresentFlags:
ValidateOrThrow(pair.second, line_, v2MetricRow_.presentFlags, presentFlags);
break;
case Header_AllowsTearing:
ValidateOrThrow(pair.second, line_, v2MetricRow_.allowsTearing, (uint32_t)allowsTearing);
break;
case Header_PresentMode:
ValidateOrThrow(pair.second, line_, v2MetricRow_.presentMode, presentMode);
break;
case Header_FrameType:
columnsMatch = ValidateFrameType(v2MetricRow_.frameType, frameType);
break;
case Header_TimeInSeconds:
ValidateOrThrow(pair.second, line_, v2MetricRow_.presentStartQPC, timeQpc);
break;
case Header_CPUStartQPC:
ValidateOrThrow(pair.second, line_, v2MetricRow_.cpuFrameQpc, cpuStartQpc);
break;
case Header_MsBetweenAppStart:
columnsMatch = ValidateMetricValue(v2MetricRow_.msBetweenAppStart, msBetweenAppStart);
break;
case Header_MsCPUBusy:
columnsMatch = ValidateMetricValue(v2MetricRow_.msCpuBusy, msCpuBusy);
break;
case Header_MsCPUWait:
columnsMatch = ValidateMetricValue(v2MetricRow_.msCpuWait, msCpuWait);
break;
case Header_MsGPULatency:
ValidateOrThrow(pair.second, line_, v2MetricRow_.msGpuLatency, msGpuLatency);
break;
case Header_MsGPUTime:
ValidateOrThrow(pair.second, line_, v2MetricRow_.msGpuTime, msGpuTime);
break;
case Header_MsGPUBusy:
ValidateOrThrow(pair.second, line_, v2MetricRow_.msGpuBusy, msGpuBusy);
break;
case Header_MsGPUWait:
ValidateOrThrow(pair.second, line_, v2MetricRow_.msGpuWait, msGpuWait);
break;
case Header_MsBetweenSimulationStart:
columnsMatch = ValidateMetricValue(v2MetricRow_.msBetweenSimStart, msBetweenSimStartTime);
break;
case Header_MsUntilDisplayed:
columnsMatch = ValidateMetricValue(v2MetricRow_.msUntilDisplayed, msUntilDisplayed);
break;
case Header_MsBetweenDisplayChange:
columnsMatch = ValidateMetricValue(v2MetricRow_.msBetweenDisplayChange, msBetweenDisplayChange);
break;
case Header_MsPCLatency:
columnsMatch = ValidateMetricValue(v2MetricRow_.msPcLatency, msPcLatency);
break;
case Header_MsAnimationError:
columnsMatch = ValidateMetricValue(v2MetricRow_.msAnimationError, msAnimationError);
break;
case Header_AnimationTime:
columnsMatch = ValidateMetricValue(v2MetricRow_.animationTime, animationTime);
break;
case Header_MsFlipDelay:
columnsMatch = ValidateMetricValue(v2MetricRow_.msFlipDelay, msFrameDelay);
break;
case Header_MsClickToPhotonLatency:
columnsMatch = ValidateMetricValue(v2MetricRow_.msClickToPhotonLatency, msClickToPhotonLatency);
break;
case Header_MsAllInputToPhotonLatency:
columnsMatch = ValidateMetricValue(v2MetricRow_.msAllInputToPhotonLatency, msAllInputToPhotonLatency);
break;
case Header_MsInstrumentedLatency:
columnsMatch = ValidateMetricValue(v2MetricRow_.msInstrumentedLatency, msInstrumentedLatency);
break;
default:
// Unknown header, skip validation
break;
}
}
}
return true;
}
bool CsvParser::FindFirstRowWithPid(const unsigned int& searchProcessId)
{
for (;;) {
if (!ReadRow(true)) {
break;
}
if (headerColumnIndex_[Header_ProcessID] != SIZE_MAX) {
auto processColIdx = headerColumnIndex_[Header_ProcessID];
char const* processIdString = nullptr;
if (processColIdx < cols_.size()) {
processIdString = cols_[Header_ProcessID];
unsigned int currentProcessId = 0;
int succeededCount = sscanf_s(processIdString, "%ud", ¤tProcessId);
if (searchProcessId == currentProcessId) {
return true;
}
}
}
}
return false;
}
bool CsvParser::ResetCsv()
{
// Rewind the file pointer and then read the header to get
// to the data
rewind(fp_);
ReadRow();
return true;
}
bool CsvParser::Open(std::wstring const& path, uint32_t processId) {
for (uint32_t i = 0; i < _countof(headerColumnIndex_); ++i) {
headerColumnIndex_[i] = SIZE_MAX;
}
cols_.clear();
if (_wfopen_s(&fp_, path.c_str(), L"r")) {
throw CsvFileException(std::format("Failed to open CSV file: {}",
pmon::util::str::ToNarrow(path)));
}
// Remove UTF-8 marker if there is one.
if (fread(row_, 3, 1, fp_) != 1 ||
row_[0] != -17 || // 0xef
row_[1] != -69 || // 0xbb
row_[2] != -65) { // 0xbf
fseek(fp_, 0, SEEK_SET);
}
// Read the header and ensure required columns are present
ReadRow();
for (size_t i = 0, n = cols_.size(); i < n; ++i) {
auto h = FindHeader(cols_[i]);
switch (h) {
case KnownHeaderCount:
case UnknownHeader:
// This is fine for when processing ETLs for testing the middleware
// as there are columns in the CSV that do not have corresponding
// metrics so we can just ignore them.
break;
default:
if ((size_t)h < KnownHeaderCount) {
if (headerColumnIndex_[(size_t)h] != SIZE_MAX) {
throw CsvFileException(std::format("Duplication column: {}", cols_[i]));
}
else {
headerColumnIndex_[(size_t)h] = i;
}
break;
}
else {
throw CsvFileException("Index outside of known headers");
}
}
}
bool columnsOK = true;
CheckAll(headerColumnIndex_, &columnsOK, { Header_Application,
Header_ProcessID,
Header_SwapChainAddress,
Header_PresentRuntime,
Header_SyncInterval,
Header_PresentFlags,
Header_AllowsTearing,
Header_PresentMode,
Header_FrameType,
Header_CPUStartQPC,
Header_MsBetweenAppStart,
Header_MsCPUBusy,
Header_MsCPUWait,
Header_MsGPULatency,
Header_MsGPUTime,
Header_MsGPUBusy,
Header_MsGPUWait,
Header_MsVideoBusy,
Header_MsUntilDisplayed,
Header_MsBetweenDisplayChange,
Header_MsAnimationError,
Header_AnimationTime,
Header_MsFlipDelay,
Header_MsClickToPhotonLatency,
Header_MsAllInputToPhotonLatency,
Header_MsBetweenSimulationStart,
Header_MsPCLatency});