Repository navigation
Expand file tree
/
Copy pathdev_control.hpp
More file actions
1232 lines (1226 loc) · 74.2 KB
/
Copy pathdev_control.hpp
File metadata and controls
1232 lines (1226 loc) · 74.2 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) 2026
* SPDX-License-Identifier: MIT
*/
// Composed after the production configuration and monitor adapters. All calls
// belong to the selected ReShade frame callback, including with Home closed.
namespace dev_control {
using Json = presets::Json;
inline Json last_request;
inline Json last_receipt;
inline bool Allowed(std::string_view key) {
constexpr std::string_view base[] = {
"NeuralUplift", "NRDisableRelease", "NRHookPoint", "NRPasses", "NRFollowInputRes", "NRResolutionScale", "NREditReuse",
"NRAdaptiveEnabled", "NRAdaptiveTargetFPS", "NRAdaptiveMinScale", "NRAdaptiveLevelCount", "NRAdaptiveLimitedResidency",
presets::ADAPTIVE_RESOURCE_STRATEGY_KEY,
"NRControlMaskEnabled",
"NRControlMaskMode", "NRControlMaskBlendMode", "NRControlMaskRed", "NRControlMaskGreen",
"NRControlMaskBlue", "NRControlMaskDepthNear", "NRControlMaskDepthFar",
"NRControlMaskMotionEnabled", "NRControlMaskMotionStart", "NRControlMaskMotionEnd"};
if (std::find(std::begin(base), std::end(base), key) != std::end(base)) return true;
if (key.size() < 8 || !key.starts_with("NRPass") || key[6] < '2' || key[6] > '4') return false;
constexpr std::string_view suffixes[] = {
"Stage", "ResolutionMode", "ResolutionScale", "ControlMaskFollowPass1", "ControlMaskMode",
"ControlMaskBlendMode", "ControlMaskRed", "ControlMaskGreen", "ControlMaskBlue",
"ControlMaskDepthNear", "ControlMaskDepthFar", "ControlMaskMotionEnabled",
"ControlMaskMotionStart", "ControlMaskMotionEnd"};
return std::find(std::begin(suffixes), std::end(suffixes), key.substr(7)) != std::end(suffixes);
}
inline Json Identity() {
gpu_comparison::Identity identity;
comparison_ui::CaptureSettings(&identity);
return {{"configuration_generation", identity.configuration_generation}, {"config_epoch", identity.config_epoch},
{"settings_hash", identity.settings_hash}, {"resolution_hash", identity.resolution_hash},
{"route", identity.route}, {"fg", identity.fg},
{"experiments", {{"adaptive_feature_mode", static_cast<uint32_t>(adaptive_feature_mode.load())},
{"bridge_adaptive_experiment", bridge_adaptive_experiment.load()},
{"edit_reuse_adaptive_experiment", edit_reuse_adaptive_experiment.load()},
{"edit_reuse_fg_experiment", edit_reuse_fg_experiment.load()},
{"edit_reuse_adaptive_evidence", "requested_enabled_not_activation"}}}};
}
inline Json ProcessIdentityState() {
FILETIME created{}, exited{}, kernel{}, user{};
const bool process_known = GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user) != FALSE;
return {{"pid", GetCurrentProcessId()},
{"process_created", process_known ? Json(std::to_string((uint64_t{created.dwHighDateTime} << 32) | created.dwLowDateTime)) : Json(nullptr)}};
}
inline Json Snapshot() {
auto state = ProcessIdentityState();
state.update({{"version", kAddonVersion}, {"available", false}, {"reason", "runtime_busy"}});
const auto roi = screenshot::GetInlineRestoreStatus();
state["inline_restore_roi"] = {{"capture_id", roi.capture_id}, {"status", roi.status},
{"reason", roi.reason}, {"serial", roi.serial}};
RuntimeTryLock lock(runtime_mutex);
if (!lock.owns_lock()) return state;
const auto identity = Identity();
const auto now = SteadyNowNs();
Json settings = Json::object();
for (const auto& group : kSettingSections) {
for (const auto* setting : group) {
if (Allowed(setting->key)) settings[setting->key] = preset_ui::ReadSetting(setting->key);
}
}
for (const auto& setting : preset_ui::kExtraSettings) {
if (Allowed(setting.key)) settings[setting.key] = preset_ui::ReadSetting(setting.key);
}
const auto plan = RequestedStagePlan();
Json passes = Json::array();
Json masks = Json::array();
for (uint32_t pass = 0; pass < plan.pass_count; ++pass) {
passes.push_back({{"pass", pass + 1}, {"requested", stage_plan::Name(plan.requested[pass])},
{"effective", plan.valid ? Json(stage_plan::Name(plan.effective[pass])) : Json(nullptr)}});
const auto mask = ResolveControlMaskParameters(pass);
masks.push_back({{"pass", pass + 1}, {"mode", mask.mode}, {"blend_mode", mask.blend_mode},
{"rgb", mask.rgb}, {"depth_near", mask.depth_near}, {"depth_far", mask.depth_far},
{"motion_enabled", mask.motion_enabled}, {"motion_start", mask.motion_start}, {"motion_end", mask.motion_end},
{"evidence", "resolved_configuration_not_execution"}});
}
Json stages = Json::array();
for (size_t index = 0; index < stage_telemetry.size(); ++index) {
const auto& stats = stage_telemetry[index];
const auto& observed = stats.last_evaluate;
Json completion{{"current", false}};
const gpu_timers::Stats* latest = nullptr;
if (plan.valid) {
for (uint32_t group = 0; group < plan.group_count; ++group) {
if (static_cast<size_t>(plan.groups[group].stage) != index) continue;
for (const auto* sample : {&gpu_timers::stage_stats[index], &gpu_timers::execution_stats[index], &gpu_timers::completed_stats[index]}) {
if (CurrentCompletedGroup(*sample, plan.groups[group], now)
&& (latest == nullptr || latest->sequence < sample->sequence)) latest = sample;
}
}
}
if (latest != nullptr) {
Json completed_passes = Json::array();
for (const auto& pass : latest->passes) {
if (pass.id >= kMaxNrPasses || pass.state != gpu_timers::SampleState::VALID) continue;
completed_passes.push_back({{"pass", pass.id + 1}, {"width", pass.width}, {"height", pass.height},
{"model_request", pass.model}, {"internal_model", nullptr}});
}
completion = {{"current", true}, {"sequence", latest->sequence}, {"recorded_ns", latest->recorded_ns},
{"completed_ns", latest->measured_ns}, {"width", latest->width}, {"height", latest->height},
{"passes", std::move(completed_passes)}};
}
stages.push_back({{"stage", stage_plan::Name(static_cast<stage_plan::Stage>(index))},
{"groups", stats.groups}, {"evaluates", stats.evaluates}, {"accepted", stats.accepted},
{"last_evaluate", {{"sequence", observed.sequence}, {"observed_ns", observed.observed_ns},
{"api_returned", observed.api_returned}, {"result", static_cast<uint32_t>(observed.result)},
{"pass", observed.pass + 1}, {"requested", stage_plan::Name(observed.requested)},
{"planned", stage_plan::Name(observed.planned)}, {"gpu_complete", false}}},
{"completion", std::move(completion)}});
}
const auto adaptive = CopyAdaptiveStatus();
Json sizes = Json::object();
for (const auto& [name, values] : {std::pair{"upper", &adaptive.upper}, {"requested", &adaptive.requested}, {"applied", &adaptive.applied}}) {
sizes[name] = Json::array();
for (uint32_t pass = 0; pass < plan.pass_count; ++pass) {
sizes[name].push_back({{"pass", pass + 1}, {"width", (*values)[pass].width}, {"height", (*values)[pass].height}});
}
}
const auto output = output_framerate::Read(MatchRuntimeOutput(monitor_runtime.load()), now);
const auto fg_environment = ReadEditReuseFgEnvironmentLocked();
Json native_evaluate = nullptr;
if (edit_reuse_enabled.load() && edit_reuse_fg_experiment.load()) {
const auto observed = fg::native_options::frame_source::Snapshot().evaluations;
native_evaluate = {{"feature_order", {sl::kFeatureDLSS, sl::kFeatureDLSS_RR, sl::kFeatureDLSS_G, "other"}},
{"feature_calls", {observed.features[0].enters, observed.features[1].enters,
observed.features[2].enters, observed.features[3].enters}},
{"ngx_fg_calls", observed.ngx_fg_calls}, {"ngx_fg_under_dlssg", observed.ngx_fg_under_dlssg},
{"evidence", "cpu_calls_only"}};
}
edit_fg_observation::Snapshot fg_observed;
edit_fg_observation::CopySnapshot(&fg_observed);
const auto resource_identity = [](const edit_fg_observation::ResourceIdentity& resource) {
return Json{{"raw", resource.raw}, {"canonical", resource.canonical},
{"canonical_available", resource.canonical != 0}};
};
const auto recording_identity = [](const edit_fg_observation::RecordingIdentity& recording) {
Json identity{{"raw", recording.raw}, {"list_id", recording.list_id}, {"generation", recording.generation},
{"identity_available", recording.list_id != 0 && recording.generation != 0}};
if (recording.reshade_base != 0) {
identity["reshade_base"] = recording.reshade_base;
}
return identity;
};
const auto source_observation = [&](const edit_fg_observation::SrCopyback& source) {
return Json{{"handle", source.source_handle}, {"generation", source.source_generation},
{"sequence", source.sr_sequence}, {"reused", source.reused},
{"output", resource_identity(source.output)}, {"size", {source.width, source.height}}, {"format", source.format},
{"recording", recording_identity(source.recording)},
{"environment_provider", source.environment_provider}, {"environment_context", source.environment_context},
{"environment_generation", source.environment_generation}};
};
const char* fg_observation_state = "disabled";
switch (fg_observed.state) {
case edit_fg_observation::State::DISABLED: break;
case edit_fg_observation::State::ARMED: fg_observation_state = "armed"; break;
case edit_fg_observation::State::CAPTURING: fg_observation_state = "capturing"; break;
case edit_fg_observation::State::STOPPED: fg_observation_state = "stopped"; break;
}
Json fg_observation_events = Json::array();
for (uint32_t index = 0; index < fg_observed.count; ++index) {
#if defined(NR_NEXUS_TEST_FG_OUTPUT_PROBE)
// The dedicated output probe needs its SDK receipts, not a second full
// metadata trace. Keep a labeled prefix within the unchanged pipe limit.
if (index == 16) break;
#endif
const auto& observed = fg_observed.events[index];
Json event{{"sequence", observed.sequence}, {"observed_ns", observed.observed_ns},
{"thread_id", observed.thread_id}};
switch (observed.kind) {
case edit_fg_observation::Kind::SOURCE_SUCCESS:
event["kind"] = "source_success";
event["source"] = {{"handle", observed.sr.source_handle},
{"generation", observed.sr.source_generation}, {"sequence", observed.sr.sr_sequence}};
break;
case edit_fg_observation::Kind::SR_COPYBACK:
event["kind"] = "sr_copyback_recorded";
event["source"] = source_observation(observed.sr);
break;
case edit_fg_observation::Kind::NATIVE_FG_ENTRY: {
const auto& native = observed.native_fg;
event["kind"] = "native_fg_entry";
event["call_id"] = observed.call_id;
event["native"] = {{"handle", native.handle}, {"environment_generation", native.generation},
{"slot", native.slot}, {"c_export", native.c_export},
{"recording", recording_identity(native.recording)},
{"backbuffer", resource_identity(native.backbuffer)}, {"hudless", resource_identity(native.hudless)},
{"ui", resource_identity(native.ui)}, {"ui_alpha", resource_identity(native.ui_alpha)},
{"ui_mode", native.has_ui_mode ? Json(native.ui_mode) : Json(nullptr)},
{"frame_id", native.has_frame_id ? Json(native.frame_id) : Json(nullptr)}};
break;
}
case edit_fg_observation::Kind::XEFG_TAG_ENTRY: {
const auto& tag = observed.xefg_tag;
event["kind"] = "xefg_tag_entry";
event["call_id"] = observed.call_id;
event["tag"] = {{"sdk_context", tag.sdk_context}, {"sdk_slot", tag.sdk_slot},
{"context_identity", tag.context_identity},
{"epoch", tag.epoch}, {"generation", tag.generation}, {"present_id", tag.present_id},
{"type", tag.type}, {"validity", tag.validity}, {"resource", resource_identity(tag.resource)},
{"recording", recording_identity(tag.recording)}, {"base", {tag.base_x, tag.base_y}},
{"size", {tag.width, tag.height}}, {"resource_state", tag.resource_state},
{"ui_mode", tag.ui_mode}, {"ui_composition", tag.ui_composition}};
break;
}
case edit_fg_observation::Kind::XEFG_PRESENT_ENTRY: {
const auto& present = observed.xefg_present;
event["kind"] = "xefg_present_entry";
event["call_id"] = observed.call_id;
event["present"] = {{"sdk_context", present.sdk_context}, {"context_identity", present.context_identity},
{"epoch", present.epoch}, {"generation", present.generation},
{"present_id", present.has_present_id ? Json(present.present_id) : Json(nullptr)},
{"repeated", present.repeated}, {"proxy", resource_identity(present.proxy)},
{"backbuffer", resource_identity(present.backbuffer)}, {"method", present.method},
{"interval", present.interval}, {"flags", present.flags}};
break;
}
case edit_fg_observation::Kind::XEFG_CONSTANTS: {
const auto& constants = observed.xefg_constants;
event["kind"] = "xefg_constants";
event["call_id"] = observed.call_id;
event["api_result"] = observed.api_result;
event["api_return_ns"] = observed.api_return_ns;
event["constants"] = {{"sdk_slot", constants.sdk_slot}, {"sdk_context", constants.sdk_context},
{"context_identity", constants.context_identity}, {"epoch", constants.epoch},
{"present_id", constants.present_id},
{"frame_time_ms", constants.has_frame_time ? Json(constants.frame_time_ms) : Json(nullptr)}};
break;
}
case edit_fg_observation::Kind::SR_QUEUE_SUBMISSION: {
const auto& submission = observed.queue_submission;
const auto& execution = submission.execution;
event["kind"] = "sr_queue_submission";
event["submission"] = {{"queue", submission.queue}, {"list", submission.list},
{"list_id", submission.list_id}, {"generation", submission.generation},
{"submission_index", submission.submission_index}, {"batch_index", submission.batch_index},
{"first_submission", submission.first_submission}, {"execute_entry_ns", execution.execute_entry_ns},
{"execute_return_ns", execution.execute_return_ns}, {"forward_calls", execution.forward_calls},
{"signal_fence", execution.signal_fence}, {"signal_value", execution.signal_value},
{"signal_succeeded", execution.signal_fence != 0 ? Json(execution.signal_succeeded) : Json(nullptr)}};
break;
}
case edit_fg_observation::Kind::NATIVE_FG_RETURN:
case edit_fg_observation::Kind::XEFG_TAG_RETURN:
case edit_fg_observation::Kind::XEFG_PRESENT_RETURN:
switch (observed.kind) {
case edit_fg_observation::Kind::NATIVE_FG_RETURN: event["kind"] = "native_fg_return"; break;
case edit_fg_observation::Kind::XEFG_TAG_RETURN: event["kind"] = "xefg_tag_return"; break;
default: event["kind"] = "xefg_present_return"; break;
}
event["call_id"] = observed.call_id;
event["api_result"] = observed.api_result;
event["api_return_ns"] = observed.api_return_ns;
if (observed.kind == edit_fg_observation::Kind::XEFG_PRESENT_RETURN) {
const auto& status = observed.present_status;
const bool valid = status.queried && status.api_result == 0;
event["sdk_present_status"] = {{"queried", status.queried},
{"api_result", status.queried ? Json(status.api_result) : Json(nullptr)},
{"frames_presented", valid ? Json(status.frames_presented) : Json(nullptr)},
{"frame_gen_result", valid ? Json(status.frame_gen_result) : Json(nullptr)},
{"enabled", valid ? Json(status.enabled) : Json(nullptr)}};
}
break;
}
fg_observation_events.push_back(std::move(event));
}
const auto device_observation = [](const fg::xefg::BridgeDeviceObservation& observed) {
return Json{{"object_present", observed.object_present}, {"swapchain_unwrapped", observed.swapchain_unwrapped},
{"swapchain_result", observed.swapchain_result}, {"device11_result", observed.device11_result},
{"device12_result", observed.device12_result}, {"returned_device_request", observed.returned_device_request},
{"returned_device_identity", observed.returned_device_identity},
{"device11_interface_result", observed.device11_interface_result},
{"device12_interface_result", observed.device12_interface_result},
{"device11_interface_identity", observed.device11_interface_identity},
{"device12_interface_identity", observed.device12_interface_identity}};
};
Json edit_off_sources = Json::array();
Json edit_device_observation = nullptr;
Json edit_off_events = nullptr;
if (edit_reuse_adaptive_experiment.load()) {
const auto trace = fg::xefg::CopyBridgeEvents();
Json events = Json::array();
for (uint32_t index = 0; index < trace.count; ++index) {
const auto& event = trace.events[index];
const char* kind = "unobserved";
switch (event.kind) {
case fg::xefg::BridgeEventKind::ENABLE_BEGIN: kind = "enable_begin"; break;
case fg::xefg::BridgeEventKind::ENABLE_END: kind = "enable_end"; break;
case fg::xefg::BridgeEventKind::LINK_REVOKED: kind = "link_revoked"; break;
case fg::xefg::BridgeEventKind::LINK_OBSERVED: kind = "link_observed"; break;
}
const char* method = "unobserved";
switch (event.source_entry.method) {
case fg::xefg::BridgePresentMethod::UNOBSERVED: break;
case fg::xefg::BridgePresentMethod::PRESENT: method = "Present"; break;
case fg::xefg::BridgePresentMethod::PRESENT1: method = "Present1"; break;
}
events.push_back({{"kind", kind}, {"sequence", event.sequence}, {"observed_ns", event.observed_ns},
{"sdk_return_ns", event.sdk_return_ns}, {"thread_id", event.thread_id},
{"context_identity", event.context_identity}, {"declaration", event.declaration}, {"epoch", event.epoch},
{"link_generation", event.link_generation}, {"source_swapchain", event.source_swapchain},
{"source_swapchain_generation", event.source_swapchain_generation},
{"source", {{"handle", event.source.handle}, {"generation", event.source.generation},
{"device11", event.source.device11}, {"device12", event.source.device12}}},
{"reason", event.reason}, {"enabled_request", event.enabled_request}, {"sdk_status", event.sdk_status},
{"off_observed", event.off_observed},
{"source_entry", {{"method", method}, {"return_address", event.source_entry.return_address},
{"thread_id", event.source_entry.thread_id}, {"proxy_entry_depth", event.source_entry.proxy_entry_depth},
{"interval", event.source_entry.interval}, {"flags", event.source_entry.flags}}}});
}
edit_off_events = {{"last_sequence", trace.last_sequence}, {"overwritten", trace.overwritten},
{"events", std::move(events)}};
const auto observed = fg::xefg::QueryBridgeOff({});
edit_device_observation = {{"query_reason", observed.reason}, {"sdk_context", observed.context},
{"sdk_proxy", observed.proxy}, {"context_identity", observed.context_identity},
{"context_epoch", observed.epoch}, {"init_kind", observed.init_kind},
{"application_device11", observed.application_device11}, {"proxy_device11", observed.proxy_device11},
{"application_device_observation", device_observation(observed.application)},
{"proxy_device_observation", device_observation(observed.proxy_device)}};
for (const auto& [handle, source] : create_contracts) {
if (source.source_device12_identity == nullptr) continue;
const auto off = EditReuseXefgOffLocked(handle);
edit_off_sources.push_back({{"source_handle", reinterpret_cast<uintptr_t>(handle)},
{"source_generation", source.source_generation},
{"device12", reinterpret_cast<uintptr_t>(source.source_device12_identity.Get())},
{"available", off.available}, {"reason", off.reason}, {"source_link_reason", off.source_link_reason},
{"context_identity", off.context_identity}, {"context_epoch", off.epoch},
{"sdk_context", off.context}, {"sdk_proxy", off.proxy}, {"init_kind", off.init_kind},
{"application_device11", off.application_device11}, {"proxy_device11", off.proxy_device11},
{"application_device_observation", device_observation(off.application)},
{"proxy_device_observation", device_observation(off.proxy_device)},
{"source_link_generation", off.source_link_generation}, {"uses_source_link", off.uses_source_link},
{"source_swapchain", off.source_swapchain}, {"source_swapchain_generation", off.source_swapchain_generation},
{"source_present_thread_id", off.source_present_thread_id},
{"source_present_proxy_entry_depth", off.source_present_proxy_entry_depth},
{"provider_matches", off.MatchesOutput(output)}});
}
}
Json edit_sources = Json::array();
Json caches = Json::array();
for (const auto& [handle, feature] : features) {
for (uint32_t pass = 0; pass < kMaxNrPasses; ++pass) {
const auto& edit = feature.slots[pass].edit_reuse;
if (edit == nullptr) continue;
edit_sources.push_back({{"source_handle", reinterpret_cast<uintptr_t>(handle)},
{"source_generation", feature.source_generation}, {"source_frame", feature.sr_sequence},
{"source_type_confirmed", feature.source_type_confirmed},
{"source_feature", static_cast<uint32_t>(feature.source_feature)}, {"pass", pass + 1},
{"working_size", {edit->width, edit->height}}, {"output_size", {edit->output_width, edit->output_height}},
{"anchor_generation", edit->anchor_generation}, {"source_sequence", edit->source_sequence},
{"reuse_count", edit->reuse_count}, {"valid", edit->valid}, {"reused", edit->reused},
{"evidence", "recorded_edit_cache_state_not_gpu_completion"}});
}
const auto& cache = feature.adaptive_cache;
if (cache == nullptr) continue;
Json slots = Json::array();
for (size_t index = 0; index < cache->count; ++index) {
const auto& tier = cache->tiers[index];
const auto& current = (index == cache->active ? feature : tier.state);
Json models = Json::array();
for (uint32_t pass = 0; pass < kMaxNrPasses; ++pass) {
const auto& model = current.slots[pass];
if (model.handle == nullptr) continue;
models.push_back({{"pass", pass + 1}, {"handle", reinterpret_cast<uintptr_t>(model.handle)},
{"parameters", reinterpret_cast<uintptr_t>(model.parameters)},
{"create_input", {model.create_input_width, model.create_input_height}},
{"create_output", {model.create_output_width, model.create_output_height}}});
}
slots.push_back({{"slot", index}, {"active", index == cache->active}, {"ready", tier.ready},
{"logical_size", {current.input_width, current.input_height}}, {"models", std::move(models)}});
}
Json sampling = nullptr;
if (feature.adaptive_session != nullptr) {
const auto& session = *feature.adaptive_session;
double median = 0., mad = 0.;
const bool statistics_valid = session.GpuStatistics(now, &median, &mad);
sampling = {{"paired_sampling", session.paired_sampling}, {"sampling_generation", session.sampling_generation},
{"gpu_count", session.gpu_count},
{"latest_recorded_ns", session.gpu_count != 0 ? Json(session.gpu_recorded_ns[session.gpu_count - 1]) : Json(nullptr)},
{"statistics_valid", statistics_valid}, {"median_us", statistics_valid ? Json(median) : Json(nullptr)},
{"mad_us", statistics_valid ? Json(mad) : Json(nullptr)}, {"evidence", "controller_per_source_gpu_chain"}};
}
caches.push_back({{"source_handle", reinterpret_cast<uintptr_t>(handle)}, {"physical_slot_count", cache->count},
{"active_slot", cache->active}, {"source_frame", feature.sr_sequence},
{"trial", feature.adaptive_session != nullptr ? Json(feature.adaptive_session->trial) : Json(nullptr)},
{"sampling", std::move(sampling)}, {"slots", std::move(slots)}});
}
if (identity != Identity()) {
state["reason"] = "configuration_changed";
return state;
}
state.update({{"available", true}, {"reason", "observed"}, {"sampled_ns", now}, {"identity", identity},
{"settings", std::move(settings)}, {"configuration_generation", identity["configuration_generation"]},
{"config_epoch", identity["config_epoch"]}, {"presents", presents_observed.load()},
{"successful_source_frames", SourceSuccessfulEvaluations()},
{"nr_features_created", nr_features_created},
{"edit_reuse", {{"requested", edit_reuse_enabled.load()}, {"refreshes", edit_reuse_refreshes.load()},
{"reuses", edit_reuse_reuses.load()}, {"fallbacks", edit_reuse_fallbacks.load()},
{"sources", std::move(edit_sources)},
{"fg_environment", {{"available", fg_environment.available}, {"reason", fg_environment.reason},
{"provider", fg_environment.provider}, {"context", fg_environment.context},
{"generation", fg_environment.generation},
{"evidence", "fg_environment_metadata_not_source_handoff"}}},
{"fg_observation", {{"enabled", fg_observed.enabled}, {"state", fg_observation_state},
{"reason", fg_observed.stop_reason}, {"request_generation", fg_observed.request_generation},
{"source_frames", fg_observed.source_frames}, {"event_count", fg_observed.count},
{"overflow", fg_observed.overflow},
{"source_copyback_observed", fg_observed.source_copyback_observed},
{"source", source_observation(fg_observed.source)}, {"events", std::move(fg_observation_events)},
{"evidence", "cpu_call_and_recording_observations_not_gpu_completion_or_pixel_handoff"},
{"resource_identity_scope", "IUnknown_after_known_ReShade_unwrap;Streamline_faces_remain_distinct"},
{"first_source_prefix_complete", false}}},
{"xefg_off_sources", std::move(edit_off_sources)},
{"xefg_device_observation", std::move(edit_device_observation)},
{"xefg_off_events", std::move(edit_off_events)},
{"evidence", "process_counters_not_activation_or_gpu_completion"}}},
{"experiments", {{"adaptive_feature_mode", identity["experiments"]["adaptive_feature_mode"]},
{"bridge_adaptive_experiment", identity["experiments"]["bridge_adaptive_experiment"]},
{"bridge_adaptive_evidence", "requested_enabled_not_activation"},
{"edit_reuse_adaptive_experiment", identity["experiments"]["edit_reuse_adaptive_experiment"]},
{"edit_reuse_adaptive_evidence", identity["experiments"]["edit_reuse_adaptive_evidence"]},
{"edit_reuse_fg_experiment", identity["experiments"]["edit_reuse_fg_experiment"]},
{"edit_reuse_fg_evidence", "requested_enabled_not_activation"},
{"evidence", "requested_mode_not_activation"}}},
{"adaptive_caches", std::move(caches)},
{"output_framerate", {{"available", output.available}, {"reason", output_framerate::ReasonText(output.reason)},
{"source", output_framerate::SourceText(output.source)}, {"source_generation", output.source_generation},
{"identity", output.identity}, {"fg_off", output.fg_off},
{"configuration_generation", output.configuration_generation}, {"window_serial", output.window_serial},
{"window_begin_ns", output.window_begin_ns}, {"window_end_ns", output.window_end_ns},
{"fps", output.available ? Json(output.fps) : Json(nullptr)},
{"fps_mad", output.available ? Json(output.fps_mad) : Json(nullptr)},
{"requested_multiplier", output.requested_multiplier != 0 ? Json(output.requested_multiplier) : Json(nullptr)},
{"observed_multiplier", output.available && output.observed_multiplier > 0. ? Json(output.observed_multiplier) : Json(nullptr)}}},
{"disabled_resources_released", disabled_resources_released.load()}, {"overlay_open", hud_overlay_open.load()},
{"plan", {{"valid", plan.valid}, {"reason", stage_plan::ReasonText(plan.reason)}, {"passes", std::move(passes)}}},
{"stages", std::move(stages)}, {"resolved_masks", std::move(masks)},
{"adaptive", {{"reason", adaptive_resolution::ReasonText(adaptive.reason)}, {"generation", adaptive.generation},
{"coefficient", adaptive.coefficient}, {"ready_levels", adaptive.ready_levels},
{"prepared_levels", adaptive.prepared_levels}, {"upper", sizes["upper"]},
{"requested", sizes["requested"]}, {"applied", sizes["applied"]},
{"output_fps", output.available && adaptive.output_fps > 0. ? Json(adaptive.output_fps) : Json(nullptr)},
{"gpu_ms", adaptive.gpu_ms > 0. ? Json(adaptive.gpu_ms) : Json(nullptr)},
{"measurement_scope", "last_controller_observation"},
{"preparation_cpu_ms", adaptive.preparation_cpu_ms},
{"preparation_vram_delta_bytes", adaptive.preparation_vram_delta_bytes},
{"peak_process_vram_bytes", adaptive.peak_process_vram_bytes}}}});
if (!native_evaluate.is_null()) {
state["edit_reuse"]["native_evaluate"] = std::move(native_evaluate);
}
#if defined(NR_NEXUS_TEST_FG_OUTPUT_PROBE)
const auto probe = fg_output_probe::CopySnapshot();
const auto& native_probe = probe.native;
Json xefg_probes = Json::array();
for (const auto& context : probe.xefg) {
if (!context.observed) continue;
xefg_probes.push_back({{"sequence", context.observed_sequence}, {"registered", context.registered},
{"stopped", context.stopped}, {"reason", context.reason}, {"sdk_slot", context.sdk_slot},
{"module_base", context.module_base}, {"sdk_context", context.sdk_context},
{"context_identity", context.context_identity}, {"init_epoch", context.init_epoch},
{"init_generation", context.init_generation}, {"current_epoch", context.current_epoch},
{"current_generation", context.current_generation}, {"debug_export", context.debug_export},
{"init_result", context.init_result_available ? Json(context.init_result) : Json(nullptr)},
{"show_result", context.show_called ? Json(context.show_result) : Json(nullptr)},
{"tag_result", context.tag_called ? Json(context.tag_result) : Json(nullptr)},
{"debug_applied", context.debug_applied},
{"active", context.registered && !context.stopped && context.debug_applied
&& fg_environment.available && fg_environment.provider == 2
&& fg_environment.context == context.context_identity},
{"destroy_result", context.destroy_called ? Json(context.destroy_result) : Json(nullptr)}});
}
const auto& marker = fg_output_marker_window;
state["edit_reuse"]["fg_observation"]["serialized_event_limit"] = 16;
state["edit_reuse"]["fg_output_probe"] = {
{"dedicated_validation_build", true}, {"evidence", "sdk_display_configuration_and_marker_recording_not_output_pixels"},
{"sequence", probe.sequence}, {"overflow", probe.overflow}, {"xefg", std::move(xefg_probes)},
{"native", {{"observed", native_probe.observed}, {"active", native_probe.active},
{"sequence", native_probe.observed_sequence}, {"success_generation", native_probe.after_success_generation},
{"reason", native_probe.reason}, {"stopped", native_probe.stopped},
{"version_supported", native_probe.version_supported},
{"viewport", native_probe.observed ? Json(native_probe.viewport) : Json(nullptr)},
{"struct_version", native_probe.observed ? Json(native_probe.struct_version) : Json(nullptr)},
{"mode", native_probe.version_supported ? Json(native_probe.mode) : Json(nullptr)},
{"num_frames", native_probe.version_supported ? Json(native_probe.num_frames) : Json(nullptr)},
{"original_flags", native_probe.version_supported ? Json(native_probe.original_flags) : Json(nullptr)},
{"forwarded_flags", native_probe.version_supported ? Json(native_probe.forwarded_flags) : Json(nullptr)},
{"flag_forwarded", native_probe.flag_forwarded},
{"api_result", native_probe.observed ? Json(native_probe.result) : Json(nullptr)}}},
{"marker", {{"request_generation", marker.request_generation}, {"enabled", marker.enabled},
{"bound", marker.bound}, {"stopped", marker.stopped}, {"reason", marker.reason},
{"frame_limit", marker.MAX_FRAMES}, {"recorded", marker.recorded},
{"refreshes", marker.refreshes}, {"reuses", marker.reuses},
{"first_sequence", marker.first_sequence}, {"last_sequence", marker.last_sequence},
{"last_recorded_ns", marker.last_recorded_ns}, {"source", marker.binding.source},
{"source_generation", marker.binding.source_generation}, {"provider", marker.binding.provider},
{"context", marker.binding.context}, {"environment_generation", marker.binding.environment_generation},
{"roi_position", "source_width/4,source_height/3"}, {"roi_size", {128, 64}},
{"encoding", "scRGB_FP16_or_PQ_RGB10A2_after_commit_alpha_preserved"}}}};
#endif
return state;
}
inline Json Execute(const Json& request) {
const auto id = request.find("id");
if (!request.is_object() || id == request.end() || !id->is_string()
|| id->get_ref<const std::string&>().empty() || id->get_ref<const std::string&>().size() > 96
|| !std::all_of(id->get_ref<const std::string&>().begin(), id->get_ref<const std::string&>().end(),
[](unsigned char value) { return std::isalnum(value) || value == '-' || value == '_' || value == '.'; })) {
return {{"ok", false}, {"status", "rejected"}, {"reason", "invalid_request_id"}};
}
const auto operation = request.find("op");
if (operation == request.end() || !operation->is_string()) {
return {{"id", *id}, {"ok", false}, {"status", "rejected"}, {"reason", "invalid_operation"}};
}
if (*operation == "native_ui_alpha_preflight") {
const auto action = request.find("action");
if (action == request.end() || !action->is_string()
|| (*action != "arm" && *action != "status" && *action != "stop")) {
return {{"id", *id}, {"ok", false}, {"status", "rejected"}, {"reason", "invalid_action"}};
}
const bool nr_disabled = !enabled.load() && !shutting_down.load();
if (*action == "arm" && !nr_disabled) {
return {{"id", *id}, {"ok", false}, {"status", "rejected"}, {"reason", "requires_nr_disabled"}};
}
auto result = native_ui_alpha_observation::Control(action->get_ref<const std::string&>(), nr_disabled);
result["id"] = *id;
result["ok"] = true;
result["status"] = "observed";
result["state"] = ProcessIdentityState();
return result;
}
#if defined(NR_NEXUS_DEV_CONTROL) && defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
const bool xefg_operation = *operation == "xefg_present_probe";
const auto xefg_snapshot = [&]() {
const auto observed = xefg_present_probe::CopySnapshot();
Json bindings = Json::array(), events = Json::array();
for (const auto& binding : observed.bindings) {
if (binding.init_serial == 0) continue;
Json queues = Json::array();
for (uint32_t index = 0; index < std::min<uint32_t>(binding.buffer_count, xefg_present_probe::kMaxBuffers); ++index) {
queues.push_back(binding.queues[index]);
}
const auto& tag = binding.tag_control;
const bool tag_generation = binding.live && binding.bound && !binding.resizing
&& tag.context_generation == binding.context_generation && tag.buffer_generation == binding.buffer_generation;
bindings.push_back({{"init_serial", binding.init_serial}, {"slot", binding.key.slot}, {"module", binding.key.module},
{"handle", binding.key.handle}, {"factory", binding.key.factory}, {"hwnd", binding.key.window},
{"module_path", binding.key.module_path}, {"module_path_available", !binding.key.module_path.empty()},
{"width", binding.created.width}, {"height", binding.created.height}, {"format_dxgi", binding.created.format},
{"application_swapchain", binding.key.application_swapchain}, {"context", binding.context},
{"context_epoch", binding.context_epoch}, {"context_generation", binding.context_generation},
{"native_swapchain", binding.created.swapchain}, {"create_queue", binding.created.queue},
{"device", binding.created.device}, {"native_method_module", binding.created.method_module},
{"hooks_ready", binding.created.hooks_ready}, {"buffer_count", binding.buffer_count},
{"buffer_generation", binding.buffer_generation}, {"present_queues", std::move(queues)},
{"tag_control", {{"same_generation", tag_generation}, {"entered", tag.entered}, {"returned", tag.returned},
{"external_calls", tag.external_calls}, {"external_false_calls", tag.external_false_calls},
{"conflicts", tag.conflicts}, {"own_true_call", tag.own_true_call}, {"own_window_conflicts", tag.own_window_conflicts},
{"last_entry", tag.last_entry}, {"last_return", tag.last_return}, {"tag_in_flight", tag.in_flight},
{"value_available", tag_generation && tag.value_available},
{"observed_value", tag_generation && tag.value_available ? Json(tag.enabled) : Json(nullptr)},
{"own_on_window_valid", tag_generation && tag.value_available && tag.enabled && tag.in_flight == 0
&& tag.own_true_call != 0 && tag.own_window_conflicts == 0}}},
{"live", binding.live}, {"bound", binding.bound}, {"resizing", binding.resizing}, {"reason", binding.reason},
{"present_api_calls", binding.present_calls}, {"successful_present_api_calls", binding.successful_present_calls},
{"test_api_calls", binding.test_calls}, {"last_present_serial", binding.last_present_serial},
{"last_present_index", binding.last_present_index}, {"last_present_result", binding.last_present_result}});
}
constexpr std::array<const char*, 8> names{"init_begin", "init_return", "create_return", "present_before", "present_return",
"resize_before", "resize_return", "invalidated"};
const auto count = std::min<uint64_t>(observed.sequence, observed.events.size());
for (uint64_t sequence = observed.sequence - count + 1; sequence <= observed.sequence && count != 0; ++sequence) {
const auto& event = observed.events[(sequence - 1) % observed.events.size()];
events.push_back({{"kind", names[static_cast<size_t>(event.kind)]}, {"sequence", event.sequence},
{"init_serial", event.init_serial}, {"buffer_generation", event.buffer_generation}, {"present_serial", event.present_serial},
{"swapchain", event.swapchain}, {"queue", event.queue}, {"thread_id", event.thread_id}, {"method", event.method},
{"buffer_index", event.index}, {"flags", event.flags}, {"result", event.result}, {"reason", event.reason}});
}
const auto& pending = observed.pending;
const auto& debug = observed.debug_calls;
Json debug_calls = Json::array();
const auto debug_count = std::min<uint64_t>(debug.entered, debug.calls.size());
for (uint64_t call_id = debug.entered - debug_count + 1; call_id <= debug.entered && debug_count != 0; ++call_id) {
const auto& call = debug.calls[(call_id - 1) % debug.calls.size()];
debug_calls.push_back({{"call_id", call.call_id}, {"enter_sequence", call.enter_sequence},
{"return_sequence", call.return_sequence}, {"feature", call.feature}, {"value", call.value}, {"argument", call.argument},
{"own_job_id", call.own_job_id}, {"source", call.own_job_id != 0 ? "nexus_apply_tag" : "external"},
{"caller_address", call.caller_address}, {"caller_module", call.caller_module},
{"caller_path", call.caller_path}, {"caller_path_available", !call.caller_path.empty()},
{"native_present_serial", call.native_present_serial},
{"entered_ms", call.entered_ms}, {"returned_ms", call.returned_ms},
{"entered_thread", call.entered_thread}, {"returned_thread", call.returned_thread},
{"returned", call.returned}, {"result", call.result},
{"target", {{"slot", call.target.slot}, {"module", call.target.module}, {"handle", call.target.handle},
{"init_serial", call.target.init_serial}, {"context", call.target.context},
{"context_generation", call.target.context_generation}, {"buffer_generation", call.target.buffer_generation}}}});
}
const auto calibration = xefg_present_probe::CopyCalibration();
const auto control = xefg_present_probe::CopyControl();
constexpr std::array<const char*, 4> control_actions{"baseline", "arm", "poll", "stop"};
constexpr std::array<const char*, 8> control_phases{"idle", "queued", "waiting_lifecycle", "sdk_entered",
"returned", "cancelled", "expired", "rejected"};
const auto capture = screenshot::CopyXefgCaptureStatus();
return Json{{"enabled", true}, {"stopped", observed.stopped}, {"evidence", xefg_present_probe::kEvidence},
{"present_serial_kind", "api_call_not_physical_frame_or_source_id"},
{"gpu_copy_enabled", calibration.active}, {"sdk_debug_called", calibration.api_sequence != 0},
{"pending", {{"active", pending.active}, {"init_serial", pending.serial}, {"slot", pending.key.slot},
{"module", pending.key.module}, {"handle", pending.key.handle}, {"factory", pending.key.factory}, {"hwnd", pending.key.window},
{"owner_thread", pending.owner_thread}, {"candidates", pending.candidates}, {"creates_inflight", pending.creates_inflight},
{"ambiguous", pending.ambiguous}, {"factory_hooks_ready", pending.factory_hooks_ready}}},
{"rejected_creates", observed.rejected_creates}, {"stale_returns", observed.stale_returns}, {"overflow", observed.overflow},
{"event_capacity", observed.events.size()}, {"event_sequence", observed.sequence}, {"bindings", std::move(bindings)},
{"events", std::move(events)},
{"debug_calls", {{"scope", "observed_export_calls_not_getter_or_pixels"},
{"capacity", debug.calls.size()}, {"sequence", debug.sequence}, {"entered", debug.entered},
{"returned", debug.returned}, {"in_flight", debug.in_flight}, {"overwritten", debug.overwritten},
{"overwritten_unreturned", debug.overwritten_unreturned}, {"stale_returns", debug.stale_returns},
{"calls", std::move(debug_calls)}}},
{"control", {{"job_id", control.job_id}, {"request_id", control.request_id},
{"action", control_actions[static_cast<size_t>(control.action)]},
{"phase", control_phases[static_cast<size_t>(control.phase)]}, {"finished", control.finished},
{"accepted", control.accepted}, {"cancel_requested", control.cancel_requested},
{"sdk_entered", control.sdk_entered}, {"sdk_returned", control.sdk_returned},
{"api_result_available", control.api_result_available}, {"result", control.result},
{"queued_thread", control.queued_thread}, {"worker_thread", control.worker_thread},
{"lifecycle_thread", control.lifecycle_thread}, {"sdk_entered_thread", control.sdk_entered_thread},
{"sdk_returned_thread", control.sdk_returned_thread}, {"queued_ms", control.queued_ms},
{"waiting_ms", control.waiting_ms}, {"lifecycle_ms", control.lifecycle_ms},
{"sdk_entered_ms", control.sdk_entered_ms}, {"sdk_returned_ms", control.sdk_returned_ms},
{"finished_ms", control.finished_ms}, {"reason", control.reason},
{"target", {{"slot", control.target.slot}, {"module", control.target.module}, {"handle", control.target.handle},
{"init_serial", control.target.init_serial}, {"context", control.target.context},
{"context_generation", control.target.context_generation}, {"buffer_generation", control.target.buffer_generation}}}}},
{"calibration", {{"init_serial", calibration.target.init_serial}, {"baseline_known", calibration.baseline_known},
{"baseline_value", false}, {"previous_state", "Unknown"}, {"original_restore", "NotClaimed"},
{"baseline_result", calibration.baseline_result}, {"tag_result", calibration.tag_result},
{"restore_result", calibration.restore_result}, {"tag_enabled", calibration.tag_enabled},
{"active", calibration.active}, {"restore_pending", calibration.restore_pending}, {"cancelled", calibration.cancelled},
{"generation", calibration.generation}, {"api_sequence", calibration.api_sequence},
{"requested", calibration.requested}, {"attempted", calibration.attempted}, {"accepted", calibration.accepted},
{"submitted", calibration.submitted}, {"deadline_ms", calibration.deadline_ms},
{"reason", calibration.reason}, {"classification", "Unknown"}}},
{"capture", {{"capture_id", capture.capture_id}, {"status", capture.status}, {"reason", capture.reason},
{"recorded", capture.recorded}, {"written", capture.written}, {"blocked", capture.blocked},
{"last_serial", capture.last_serial}, {"drained", capture.drained}}}};
};
if (xefg_operation && request.value("action", Json(nullptr)) == "status") {
return {{"id", *id}, {"ok", true}, {"status", "observed"}, {"state", ProcessIdentityState()}, {"probe", xefg_snapshot()}};
}
#endif
const bool marker_operation = *operation == "fg_output_marker";
const bool consumer_operation = *operation == "fg_consumer_capture";
const bool benchmark_operation = *operation == "sr_benchmark";
const bool handoff_capture_operation = *operation == "present_handoff_capture";
const bool fg_observation_operation = *operation == "fg_execution_observation";
const auto fg_observation_action = (fg_observation_operation ? request.value("action", Json(nullptr)) : Json(nullptr));
const bool compact_operation = marker_operation || consumer_operation || benchmark_operation || handoff_capture_operation
|| fg_observation_operation
#if defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
|| xefg_operation
#endif
;
const auto consumer_snapshot = []() {
const auto capture = screenshot::CopyFgConsumerStatus();
return Json{{"capture_id", capture.capture_id}, {"status", capture.status},
{"reason", capture.reason}, {"serial", capture.serial}};
};
const auto marker_snapshot = []() {
const auto& marker = fg_output_marker_window;
const auto now = SteadyNowNs();
return Json{{"request_generation", marker.request_generation}, {"enabled", marker.enabled},
{"bound", marker.bound}, {"stopped", marker.stopped}, {"reason", marker.reason},
{"expired", marker.enabled && (now < marker.armed_ns || now - marker.armed_ns >= marker.MAX_DURATION_NS)},
{"frame_limit", marker.MAX_FRAMES}, {"duration_ms", marker.MAX_DURATION_NS / 1'000'000},
{"recorded", marker.recorded}, {"refreshes", marker.refreshes}, {"reuses", marker.reuses},
{"first_sequence", marker.first_sequence}, {"last_sequence", marker.last_sequence},
{"source", marker.binding.source}, {"source_generation", marker.binding.source_generation},
{"provider", marker.binding.provider}, {"context", marker.binding.context},
{"environment_generation", marker.binding.environment_generation},
{"evidence", "marker_recording_not_GPU_completion_or_FG_pixels"}};
};
if (marker_operation && request.value("action", Json(nullptr)) == "status") {
RuntimeTryLock lock(runtime_mutex);
if (!lock.owns_lock()) {
return {{"id", *id}, {"ok", false}, {"status", "rejected"}, {"reason", "runtime_busy"},
{"state", ProcessIdentityState()}};
}
return {{"id", *id}, {"ok", true}, {"status", "observed"}, {"marker", marker_snapshot()},
{"state", ProcessIdentityState()}};
}
if (consumer_operation && request.value("action", Json(nullptr)) == "status") {
return {{"id", *id}, {"ok", true}, {"status", "observed"}, {"capture", consumer_snapshot()},
{"state", ProcessIdentityState()}};
}
if (benchmark_operation && request.value("action", Json(nullptr)) == "status") {
return {{"id", *id}, {"ok", true}, {"status", "observed"}, {"capture", control_mask_capture::benchmark::Status()},
{"state", ProcessIdentityState()}};
}
if (handoff_capture_operation && request.value("action", Json(nullptr)) == "status") {
return {{"id", *id}, {"ok", true}, {"status", "observed"}, {"capture", present_handoff_capture::Status()},
{"state", ProcessIdentityState()}};
}
if (*operation == "status" || (fg_observation_action == "status" && request.size() == 3)) {
auto state = Snapshot();
Json response{{"id", *id}, {"ok", true}, {"status", "observed"}, {"state", state},
{"identity", state.value("identity", Json(nullptr))},
{"receipt", request.contains("query_id") && last_request.is_object()
&& request["query_id"] == last_request["id"] ? last_receipt : Json(nullptr)}};
if (!response["receipt"].is_null() && state.value("available", false)) {
auto& observation = response["state"]["edit_reuse"]["fg_observation"];
if (!observation["events"].empty() && response.dump().size() > dev_control_pipe::internal::MAX_FRAME_BYTES) {
observation["events"] = Json::array();
observation["events_in_status_without_receipt"] = true;
}
}
return response;
}
if (*operation != "set" && *operation != "adaptive_feature_experiment"
&& *operation != "bridge_adaptive_experiment" && *operation != "edit_reuse_adaptive_experiment"
&& *operation != "edit_reuse_fg_experiment"
&& *operation != "reset_nr"
&& !compact_operation
&& *operation != "inline_restore_roi") {
return {{"id", *id}, {"ok", false}, {"status", "rejected"}, {"reason", "invalid_operation"}};
}
if (last_request.is_object() && last_request["id"] == *id) {
if (request == last_request) return last_receipt;
if (compact_operation) {
return {{"id", *id}, {"ok", false}, {"status", "rejected"}, {"reason", "request_id_reused"},
{"state", ProcessIdentityState()}};
}
return {{"id", *id}, {"ok", false}, {"status", "rejected"}, {"reason", "request_id_reused"}};
}
Json response{{"id", *id}, {"ok", false}, {"status", "rejected"}, {"reason", "invalid_setting"},
{"message", ""}, {"changes", Json::object()}};
if (*operation == "reset_nr") {
response["configuration_generation_before"] = configuration_generation.load();
}
const auto finish = [&]() {
if (*operation == "reset_nr") {
response["configuration_generation_after"] = configuration_generation.load();
}
if (compact_operation) {
response["state"] = ProcessIdentityState();
} else {
response["state"] = Snapshot();
if (response["state"].value("available", false)) {
// Status can contain both the current state and this cached receipt.
// Keep bounded events in the current status, rather than duplicating
// them into every mutation receipt under the same 64 KiB pipe limit.
auto& observed = response["state"]["edit_reuse"]["fg_observation"];
observed["events"] = Json::array();
observed["events_in_status_only"] = true;
response["state"]["edit_reuse"].erase("native_evaluate");
}
response["identity"] = response["state"].value("identity", Json(nullptr));
}
last_request = request;
last_receipt = response;
Log(reshade::log::level::info, NR_NEXUS_NAME " development control: id=" + id->get<std::string>()
+ " status=" + response["status"].get<std::string>() + " reason=" + response["reason"].get<std::string>());
return response;
};
if (fg_observation_operation) {
response["reason"] = "invalid_fg_observation_action";
if (request.size() != 3 || (fg_observation_action != "arm" && fg_observation_action != "stop")) return finish();
if (fg_observation_action == "arm") {
response["request_generation"] = edit_fg_observation::Arm();
} else {
edit_fg_observation::Stop("requested_stop");
}
response.update({{"ok", true}, {"status", "accepted"}, {"reason", "fg_observation_request_accepted"}});
return finish();
}
const bool configuration_busy = shutting_down.load() || slider_pending != nullptr || stage_edit::pending || resolution_edit::pending
|| stage_edit_request.setting != nullptr || !resolution_edit_request.empty() || profile_ui::Busy()
|| profile_ui::pending_action != profile_ui::Action::NONE || preset_ui::manager_geometry.was_open;
if (handoff_capture_operation) {
const auto action = request.value("action", Json(nullptr));
const auto capture_id = request.find("capture_id");
response["reason"] = "invalid_capture_request";
if (capture_id == request.end() || !capture_id->is_string()) return finish();
const auto& name = capture_id->get_ref<const std::string&>();
if (action == "stop") {
const bool stopped = present_handoff_capture::Stop(name);
response["ok"] = stopped;
response["status"] = (stopped ? "stopping" : "rejected");
response["reason"] = (stopped ? "explicit_stop" : "capture_not_active");
} else if (action == "arm") {
const auto directory = request.find("run_directory");
const auto start_on_real_guides = request.value("start_on_real_guides", Json(false));
if (directory == request.end() || !directory->is_string() || !start_on_real_guides.is_boolean()) return finish();
if (shutting_down.load()) {
response["reason"] = "shutting_down";
} else {
const auto& path = directory->get_ref<const std::string&>();
try {
const std::string_view reason = present_handoff_capture::Arm(
std::filesystem::path(std::u8string(path.begin(), path.end())), name, start_on_real_guides.get<bool>());
response["ok"] = (reason == "queued");
response["status"] = (reason == "queued" ? "queued" : "rejected");
response["reason"] = reason;
} catch (...) {
response["reason"] = "capture_arm_failed";
}
}
}
response["capture"] = present_handoff_capture::Status();
return finish();
}
if (benchmark_operation) {
namespace benchmark = control_mask_capture::benchmark;
const auto action = request.value("action", Json(nullptr));
const auto environment = [] {
const auto xefg = fg::xefg::QueryEnabledContext();
int64_t xefg_last_proxy_present_ns = 0;
{
// ObserveXeFG runs at the real proxy Present return, even on a failed or OFF status.
std::shared_lock lock(output_framerate::internal::state.mutex);
xefg_last_proxy_present_ns = output_framerate::internal::state.xefg_ns;
}
return Json{{"sampled_ns", SteadyNowNs()}, {"native_fg_calls", benchmark::native_fg_calls.load()},
{"native_fg_successes", benchmark::native_fg_successes.load()},
{"native_fg_declaration", static_cast<uint32_t>(native_fg_declaration.load())},
{"native_fg_owns", native_fg_owns.load()}, {"xefg_enabled", fg::xefg::Enabled()},
{"xefg_owns", fg::xefg::OwnsStream()}, {"xefg_context", xefg.context_identity},
{"xefg_context_state", xefg.reason}, {"xefg_nr_submissions", fg::xefg::SubmittedFrames()},
{"xefg_last_proxy_present_ns", xefg_last_proxy_present_ns}};
};
const auto settings = [] {
auto captured = preset_ui::Capture(presets::Scope::FULL, Json::object()).settings;
captured["NeuralUplift"] = enabled.load();
captured["NREditReuse"] = edit_reuse_enabled.load();
return captured;
};
response["reason"] = "invalid_benchmark_request";
bool applied = false;
if (action == "arm") {
const auto frames = request.find("max_frames");
const auto seconds = request.find("seconds");
if (frames == request.end() || seconds == request.end() || !frames->is_number_unsigned()
|| !seconds->is_number_unsigned() || *frames < 1 || *frames > 8192 || *seconds < 1 || *seconds > 180) return finish();
if (configuration_busy || !gpu_timers_enabled.load() || !queue_tracking_active.load()) {
response["reason"] = configuration_busy ? "configuration_busy" : "requires_gpu_timers_and_queue_tracking";
return finish();
}
applied = benchmark::Arm(frames->get<uint32_t>(), seconds->get<uint32_t>(), environment(), settings());
} else if (action == "mark") {
const auto label = request.find("label");
if (label == request.end() || !label->is_string()) return finish();
const auto& value = label->get_ref<const std::string&>();
if (value.empty() || value.size() > 32 || !std::all_of(value.begin(), value.end(), [](unsigned char c) {
return std::isalnum(c) || c == '-' || c == '_';
})) return finish();
applied = benchmark::Mark(value, environment(), settings());
} else if (action == "stop") {
applied = benchmark::Stop("requested_stop", environment());
} else {
return finish();
}
response.update({{"ok", applied}, {"status", applied ? "accepted" : "rejected"},
{"reason", applied ? "benchmark_request_accepted" : "benchmark_state_conflict"}, {"capture", benchmark::Status()}});
return finish();
}
if (*operation == "reset_nr") {
response["reason"] = "invalid_reset_request";
if (request.size() != 2) return finish();
if (configuration_busy) {
response["reason"] = "configuration_busy";
return finish();
}
DWORD foreground_process = 0;
GetWindowThreadProcessId(GetForegroundWindow(), &foreground_process);
if (foreground_process != GetCurrentProcessId()) {
response["reason"] = "not_foreground";
return finish();
}
RecreateFeatures();
response.update({{"ok", true}, {"status", "accepted"}, {"reason", "nr_reset_requested"},
{"evidence", "reset_requested_not_model_or_gpu_completion"}});
return finish();
}
#if defined(NR_NEXUS_TEST_XEFG_PRESENT_PROBE)
if (xefg_operation) {
response["reason"] = "invalid_calibration_request";
const auto complete = [&]() {
response["probe"] = xefg_snapshot();
return finish();
};
const auto queue = [&](xefg_present_probe::ControlAction action, const xefg_present_probe::Target& target,
bool tag_enabled = false, uint32_t samples = 0, uint32_t duration_ms = 0) {
const auto job_id = xefg_present_probe::QueueControl(id->get_ref<const std::string&>(), action, target,
tag_enabled, samples, duration_ms);
if (job_id == 0) {
response.update({{"ok", false}, {"status", "blocked"}, {"reason", "control_busy_or_stopped"}});
return false;
}
const bool scheduled = screenshot::ScheduleXefgControl();
const auto control = xefg_present_probe::CopyControl();
const bool entered = control.cancel_requested && control.sdk_entered && !control.finished;
response.update({{"ok", scheduled && !entered}, {"status", scheduled && !entered ? "queued" : "blocked"},
{"job_id", job_id}, {"reason", !scheduled ? "worker_unavailable" : entered ? "sdk_call_in_flight" : "control_job_queued"}});
return scheduled && !entered;
};
const auto action = request.value("action", Json(nullptr));
if (action == "poll" || action == "stop") {
const auto current = xefg_present_probe::CopyCalibration();
const auto control = xefg_present_probe::CopyControl();
const auto target = (xefg_present_probe::ControlBusy(control) ? control.target : current.target);
if (!request.contains("init_serial") || !request["init_serial"].is_number_unsigned()
|| target.init_serial == 0 || request["init_serial"].get<uint64_t>() != target.init_serial) return complete();
if (action == "stop") {
screenshot::CancelXefgCapture("explicit_async_stop");
}
queue(action == "stop" ? xefg_present_probe::ControlAction::STOP : xefg_present_probe::ControlAction::POLL, target);
return complete();
}
if (action != "baseline" && action != "arm") return complete();
const auto object = request.find("target");
if (object == request.end() || !object->is_object()) return complete();
for (const char* key : {"slot", "module", "handle", "init_serial", "context", "context_generation", "buffer_generation"}) {
const auto value = object->find(key);
if (value == object->end() || !value->is_number_unsigned()) return complete();
}
if ((*object)["slot"] > 1) return complete();
const xefg_present_probe::Target target{.slot = (*object)["slot"].get<uint32_t>(),
.module = (*object)["module"].get<uintptr_t>(), .handle = (*object)["handle"].get<uintptr_t>(),
.init_serial = (*object)["init_serial"].get<uint64_t>(), .context = (*object)["context"].get<uintptr_t>(),
.context_generation = (*object)["context_generation"].get<uint64_t>(), .buffer_generation = (*object)["buffer_generation"].get<uint64_t>()};
if (xefg_present_probe::ControlBusy(xefg_present_probe::CopyControl())) {
response["reason"] = "control_busy";
return complete();
}
if (configuration_busy || enabled.load() || !disabled_resources_released.load() || !screenshot::CopyXefgCaptureStatus().drained) {
response["reason"] = "nr_off_and_idle_required";
return complete();
}
if (action == "baseline") {
queue(xefg_present_probe::ControlAction::BASELINE, target);
return complete();
}
if (!request.contains("tag_enabled") || !request["tag_enabled"].is_boolean()
|| !request.contains("samples") || !request["samples"].is_number_unsigned()
|| request["samples"] < 1 || request["samples"] > xefg_present_probe::kMaxSamplesPerWindow
|| !request.contains("duration_ms") || !request["duration_ms"].is_number_unsigned()
|| request["duration_ms"] < 100 || request["duration_ms"] > 3000
|| !request.contains("output_directory") || !request["output_directory"].is_string()
|| !request.contains("capture_id") || !request["capture_id"].is_string()) return complete();
std::array<screenshot::CaptureRect, 2> rois{};
size_t index = 0;
for (const char* name : {"nr_roi", "sdk_roi"}) {
const auto roi = request.find(name);
if (roi == request.end() || !roi->is_object()) return complete();
for (const char* key : {"x", "y", "width", "height"}) {
if (!roi->contains(key) || !(*roi)[key].is_number_unsigned() || (*roi)[key] > UINT32_MAX) return complete();
}
rois[index++] = {.x = (*roi)["x"].get<uint32_t>(), .y = (*roi)["y"].get<uint32_t>(),
.width = (*roi)["width"].get<uint32_t>(), .height = (*roi)["height"].get<uint32_t>()};
}
const auto& directory = request["output_directory"].get_ref<const std::string&>();
if (!screenshot::RequestXefgCapture(std::filesystem::path(std::u8string(directory.begin(), directory.end())),
request["capture_id"].get_ref<const std::string&>(), rois, present_generation)) return complete();
xefg_present_probe::ConfigureCapture({.prepare = screenshot::PrepareXefgPresent, .returned = screenshot::ReturnXefgPresent,
.install = +[](ID3D12CommandQueue* queue, ID3D12GraphicsCommandList* list) {
return InstallCommandListStateHooks(list) && InstallQueueCompletionHooks(queue) && queue_tracking_active.load();
}, .cancel = screenshot::CancelXefgCapture, .ready = screenshot::ReserveXefgRecording, .release = screenshot::ReleaseXefgRecording});
if (!queue(xefg_present_probe::ControlAction::ARM, target, request["tag_enabled"].get<bool>(),
request["samples"].get<uint32_t>(), request["duration_ms"].get<uint32_t>())) {
screenshot::CancelXefgCapture("control_queue_rejected");
}
return complete();
}
#endif
if (consumer_operation) {
response["reason"] = "invalid_consumer_request";
const auto directory = request.find("output_directory");
const auto capture_id = request.find("capture_id");
const auto roi = request.find("roi");
if (request.value("action", Json(nullptr)) != "arm"
|| directory == request.end() || !directory->is_string()
|| capture_id == request.end() || !capture_id->is_string() || roi == request.end() || !roi->is_object()) return finish();
for (const char* key : {"x", "y", "width", "height"}) {
const auto value = roi->find(key);
if (value == roi->end() || !value->is_number_integer() || *value < 0 || *value > UINT32_MAX) return finish();
}
if (configuration_busy) {
response["reason"] = "configuration_busy";
return finish();
}
bool route_ready = false;
{
RuntimeTryLock lock(runtime_mutex);
if (!lock.owns_lock()) {
response["reason"] = "runtime_busy";
} else {