upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorandretuta <andreviniciusmerlia@gmail.com>2026-11-24 01:43:53 -0300
committerandretuta <andreviniciusmerlia@gmail.com>2026-11-24 01:43:53 -0300
commitddafa07b463c5405eeb1c31cf5e42dca5f8a6be0 (patch)
treea6261df921f91dacaa85925d4f8baddc27a814a1 /runtime
parentece4ba5b31ebc6f345c8e29eae1261f2f780057a (diff)
d3d12_xs: multi-event FramePacer TOKEN_ON_TIMEOUT and XboxPresentation proxy wiring
- Support origin (0), vblank (1), and flip (2) frame events and frame_wait_flag_token_on_timeout (flag 2, returning S_FALSE with a fresh consecutive token on timeout) in runtime/src/frame_pacer.h. - Add a decoupled PresentationHandler interface to d3d12_xs_device.{h,cpp} routing device slots 78-81 and queue PresentX/SuspendX/ResumeX slots (default 30/31/32, env-overridable via LEONIDA_XS_*_SLOT). - Add attach_xbox_presentation / detach_xbox_presentation in runtime/shims/xbox_present.{h,cpp}.
Diffstat (limited to 'runtime')
-rw-r--r--runtime/shims/d3d12_xs_device.cpp106
-rw-r--r--runtime/shims/d3d12_xs_device.h17
-rw-r--r--runtime/shims/xbox_present.cpp36
-rw-r--r--runtime/shims/xbox_present.h8
-rw-r--r--runtime/src/frame_pacer.h125
-rw-r--r--runtime/test/frame_pacer_test.cpp41
-rw-r--r--runtime/test/xs_proxy_mock_test.cpp93
7 files changed, 368 insertions, 58 deletions
diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp
index 1045b86fb..7f9a475f4 100644
--- a/runtime/shims/d3d12_xs_device.cpp
+++ b/runtime/shims/d3d12_xs_device.cpp
@@ -75,8 +75,19 @@ struct DeviceProxy {
75 std::atomic<std::uint32_t> frame_latency{1}; 75 std::atomic<std::uint32_t> frame_latency{1};
76 std::atomic<bool> frame_event_scheduled{false}; 76 std::atomic<bool> frame_event_scheduled{false};
77 std::atomic<std::uint64_t> frame_next_token{1}; 77 std::atomic<std::uint64_t> frame_next_token{1};
78 // Optional presentation wiring attached via set_presentation_handler (guarded by presentation_lock).
79 SRWLOCK presentation_lock = SRWLOCK_INIT;
80 PresentationHandler presentation{};
78}; 81};
79 82
83PresentationHandler snapshot_presentation(DeviceProxy* self) {
84 if (!self) return {};
85 AcquireSRWLockShared(&self->presentation_lock);
86 const PresentationHandler copy = self->presentation;
87 ReleaseSRWLockShared(&self->presentation_lock);
88 return copy;
89}
90
80constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles 91constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles
81 92
82struct HeapProxy { 93struct HeapProxy {
@@ -1190,6 +1201,38 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) {
1190 return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash 1201 return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash
1191} 1202}
1192 1203
1204struct XboxQueueSlotRoutes {
1205 unsigned present_x = 30; // PresentX(plane_count, planes, params)
1206 unsigned suspend_x = 31; // SuspendX(flags)
1207 unsigned resume_x = 32; // ResumeX()
1208};
1209
1210unsigned env_queue_slot(const char* name, unsigned fallback) {
1211 char value[32] = {};
1212 const DWORD length = GetEnvironmentVariableA(name, value, sizeof(value));
1213 if (length == 0 || length >= sizeof(value)) return fallback;
1214 errno = 0;
1215 char* end = nullptr;
1216 const unsigned long slot = std::strtoul(value, &end, 0);
1217 if (errno != 0 || end == value || *end != '\0' || slot < kQueuePublicSlots || slot >= kQueueSlots) {
1218 std::fprintf(stderr, "[rt] d3d12_xs: %s=%s is not a queue slot in %u..%u; the default is kept\n", name, value,
1219 kQueuePublicSlots, kQueueSlots - 1);
1220 return fallback;
1221 }
1222 return static_cast<unsigned>(slot);
1223}
1224
1225const XboxQueueSlotRoutes& xbox_queue_slot_routes() {
1226 static const XboxQueueSlotRoutes routes = [] {
1227 XboxQueueSlotRoutes r;
1228 r.present_x = env_queue_slot("LEONIDA_XS_PRESENT_X_SLOT", r.present_x);
1229 r.suspend_x = env_queue_slot("LEONIDA_XS_SUSPEND_X_SLOT", r.suspend_x);
1230 r.resume_x = env_queue_slot("LEONIDA_XS_RESUME_X_SLOT", r.resume_x);
1231 return r;
1232 }();
1233 return routes;
1234}
1235
1193template <ChildKind K, unsigned Slot> 1236template <ChildKind K, unsigned Slot>
1194std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, 1237std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3,
1195 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, 1238 std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7,
@@ -1210,6 +1253,23 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_
1210 } else { 1253 } else {
1211 note_child_slot<K>(Slot); 1254 note_child_slot<K>(Slot);
1212 if (Slot >= self->slot_count) { 1255 if (Slot >= self->slot_count) {
1256 if constexpr (K == ChildKind::queue) {
1257 const XboxQueueSlotRoutes& qroutes = xbox_queue_slot_routes();
1258 if (Slot == qroutes.present_x || Slot == qroutes.suspend_x || Slot == qroutes.resume_x) {
1259 const PresentationHandler p = snapshot_presentation(self->device);
1260 if (Slot == qroutes.present_x && p.present_x) {
1261 return hr_to_u64(p.present_x(p.context, static_cast<UINT>(a1),
1262 reinterpret_cast<const void*>(a2),
1263 reinterpret_cast<const void*>(a3)));
1264 }
1265 if (Slot == qroutes.suspend_x && p.suspend_x) {
1266 return hr_to_u64(p.suspend_x(p.context, static_cast<UINT>(a1)));
1267 }
1268 if (Slot == qroutes.resume_x && p.resume_x) {
1269 return hr_to_u64(p.resume_x(p.context));
1270 }
1271 }
1272 }
1213 bool expected = false; 1273 bool expected = false;
1214 if (ChildStats<K>::beyond_warned[Slot].compare_exchange_strong(expected, true, 1274 if (ChildStats<K>::beyond_warned[Slot].compare_exchange_strong(expected, true,
1215 std::memory_order_relaxed)) { 1275 std::memory_order_relaxed)) {
@@ -1376,8 +1436,12 @@ HRESULT proxy_create_command_queue(DeviceProxy* self, const D3D12_COMMAND_QUEUE_
1376// 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. 1436// 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces.
1377HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us, 1437HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std::uint64_t interval_us,
1378 std::uint64_t latency, std::uint64_t flags) { 1438 std::uint64_t latency, std::uint64_t flags) {
1379 (void)output; 1439 const PresentationHandler p = snapshot_presentation(self);
1380 (void)flags; 1440 if (p.set_frame_interval) {
1441 return p.set_frame_interval(p.context, reinterpret_cast<IUnknown*>(output),
1442 static_cast<UINT>(interval_us), static_cast<UINT>(latency),
1443 static_cast<UINT>(flags));
1444 }
1381 self->frame_interval_us.store(static_cast<std::uint32_t>(interval_us), std::memory_order_relaxed); 1445 self->frame_interval_us.store(static_cast<std::uint32_t>(interval_us), std::memory_order_relaxed);
1382 self->frame_latency.store(static_cast<std::uint32_t>(latency ? latency : 1), std::memory_order_relaxed); 1446 self->frame_latency.store(static_cast<std::uint32_t>(latency ? latency : 1), std::memory_order_relaxed);
1383 return S_OK; 1447 return S_OK;
@@ -1386,22 +1450,25 @@ HRESULT proxy_set_frame_interval_x(DeviceProxy* self, std::uint64_t output, std:
1386// Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin. 1450// Xbox device slot 79 (public HLE): ScheduleFrameEventX(event, offset_us, pEvent, flags); our pacer has only the origin.
1387HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us, 1451HRESULT proxy_schedule_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t offset_us,
1388 std::uint64_t flags) { 1452 std::uint64_t flags) {
1389 (void)event; 1453 const PresentationHandler p = snapshot_presentation(self);
1390 (void)offset_us; 1454 if (p.schedule_frame_event) {
1391 (void)flags; 1455 return p.schedule_frame_event(p.context, static_cast<UINT>(event), static_cast<UINT>(offset_us),
1456 static_cast<UINT>(flags));
1457 }
1392 self->frame_event_scheduled.store(true, std::memory_order_relaxed); 1458 self->frame_event_scheduled.store(true, std::memory_order_relaxed);
1393 return S_OK; 1459 return S_OK;
1394} 1460}
1395 1461
1396// Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). It returns at once with 1462// Xbox device slot 80 (public HLE): WaitFrameEventX(event, timeout_ms, pEvent, flags, &token). When a presenter is
1397// a fresh non-zero token (the first-frame choice): there is no vblank source behind the device before a presenter, and 1463// attached, forwards directly to it; otherwise returns at once with a fresh non-zero token so boot tests cannot stall.
1398// a zero wait cannot stall the title. A null token pointer is E_POINTER, as a _Out_ parameter.
1399HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms, 1464HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::uint64_t timeout_ms,
1400 std::uint64_t flags, std::uint64_t token_word) { 1465 std::uint64_t flags, std::uint64_t token_word) {
1401 (void)event;
1402 (void)timeout_ms;
1403 (void)flags;
1404 auto* token = reinterpret_cast<std::uint64_t*>(token_word); 1466 auto* token = reinterpret_cast<std::uint64_t*>(token_word);
1467 const PresentationHandler p = snapshot_presentation(self);
1468 if (p.wait_frame_event) {
1469 return p.wait_frame_event(p.context, static_cast<UINT>(event), static_cast<DWORD>(timeout_ms),
1470 static_cast<UINT>(flags), token);
1471 }
1405 if (!token) return E_POINTER; 1472 if (!token) return E_POINTER;
1406 std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); 1473 std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed);
1407 if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token 1474 if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token
@@ -1901,6 +1968,14 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64
1901 log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5); 1968 log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5);
1902 return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); 1969 return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5));
1903 } 1970 }
1971 if (Slot == 81) {
1972 const PresentationHandler p = snapshot_presentation(self);
1973 if (p.get_frame_statistics) {
1974 log_xbox_route_once(Slot, "GetFrameStatisticsX", a1, a2, a3, a4, a5);
1975 return hr_to_u64(p.get_frame_statistics(p.context, a1, static_cast<UINT>(a2),
1976 reinterpret_cast<UINT*>(a3), reinterpret_cast<void*>(a4)));
1977 }
1978 }
1904 if (Slot == routes.queue_x) { 1979 if (Slot == routes.queue_x) {
1905 log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); 1980 log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5);
1906 return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast<const D3D12_COMMAND_QUEUE_DESC*>(a1), 1981 return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast<const D3D12_COMMAND_QUEUE_DESC*>(a1),
@@ -2064,6 +2139,15 @@ void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler) {
2064 g_console_descriptor_heap.store(handler, std::memory_order_release); 2139 g_console_descriptor_heap.store(handler, std::memory_order_release);
2065} 2140}
2066 2141
2142bool set_presentation_handler(void* device, const PresentationHandler* handler) {
2143 auto* proxy = static_cast<DeviceProxy*>(device_proxy_primary(device));
2144 if (!proxy) return false;
2145 AcquireSRWLockExclusive(&proxy->presentation_lock);
2146 proxy->presentation = handler ? *handler : PresentationHandler{};
2147 ReleaseSRWLockExclusive(&proxy->presentation_lock);
2148 return true;
2149}
2150
2067ID3D12Device* device_proxy_real_device(const void* device) { 2151ID3D12Device* device_proxy_real_device(const void* device) {
2068 if (!is_device_proxy(device)) return nullptr; 2152 if (!is_device_proxy(device)) return nullptr;
2069 return static_cast<const DeviceProxy*>(device)->real; 2153 return static_cast<const DeviceProxy*>(device)->real;
diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h
index 20ed4afc1..5cebaddbc 100644
--- a/runtime/shims/d3d12_xs_device.h
+++ b/runtime/shims/d3d12_xs_device.h
@@ -117,6 +117,23 @@ using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12
117 REFIID riid, void** out); 117 REFIID riid, void** out);
118void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); 118void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler);
119 119
120// Presentation wiring: connects device frame-event slots (78/79/80/81: SetFrameIntervalX, ScheduleFrameEventX,
121// WaitFrameEventX, GetFrameStatisticsX) and queue presentation slots (PresentX, SuspendX, ResumeX, default 30/31/32,
122// configurable via LEONIDA_XS_PRESENT_X_SLOT / LEONIDA_XS_SUSPEND_X_SLOT / LEONIDA_XS_RESUME_X_SLOT) to an external
123// presenter such as rt::d3d12::XboxPresentation without coupling d3d12_xs_device to Vulkan headers. Passing nullptr
124// detaches the handler and restores the default mock/fallback behavior.
125struct PresentationHandler {
126 void* context = nullptr;
127 HRESULT (*set_frame_interval)(void* context, IUnknown* output, UINT interval_us, UINT latency, UINT flags) = nullptr;
128 HRESULT (*schedule_frame_event)(void* context, UINT event, UINT offset_us, UINT flags) = nullptr;
129 HRESULT (*wait_frame_event)(void* context, UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token) = nullptr;
130 HRESULT (*get_frame_statistics)(void* context, std::uint64_t token, UINT type_mask, UINT* count, void* out) = nullptr;
131 HRESULT (*present_x)(void* context, UINT plane_count, const void* planes, const void* params) = nullptr;
132 HRESULT (*suspend_x)(void* context, UINT flags) = nullptr;
133 HRESULT (*resume_x)(void* context) = nullptr;
134};
135bool set_presentation_handler(void* device, const PresentationHandler* handler);
136
120// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue 137// True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue
121// proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and 138// proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and
122// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67 and 76. Slot 10 is intentionally false: the 139// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67 and 76. Slot 10 is intentionally false: the
diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp
index dd5f810cf..024b82170 100644
--- a/runtime/shims/xbox_present.cpp
+++ b/runtime/shims/xbox_present.cpp
@@ -1,6 +1,7 @@
1#include "xbox_present.h" 1#include "xbox_present.h"
2 2
3#include "d3d12_trace.h" 3#include "d3d12_trace.h"
4#include "d3d12_xs_device.h"
4 5
5#include "../src/vulkan_present.h" 6#include "../src/vulkan_present.h"
6 7
@@ -314,4 +315,39 @@ HRESULT XboxPresentation::ResumeX() {
314 return S_OK; 315 return S_OK;
315} 316}
316 317
318bool attach_xbox_presentation(void* device_proxy, XboxPresentation* presentation) {
319 if (!presentation) return rt::d3d12_xs::set_presentation_handler(device_proxy, nullptr);
320 rt::d3d12_xs::PresentationHandler handler{};
321 handler.context = presentation;
322 handler.set_frame_interval = [](void* ctx, IUnknown* output, UINT interval_us, UINT latency, UINT flags) {
323 return static_cast<XboxPresentation*>(ctx)->SetFrameIntervalX(output, interval_us, latency, flags);
324 };
325 handler.schedule_frame_event = [](void* ctx, UINT event, UINT offset_us, UINT flags) {
326 return static_cast<XboxPresentation*>(ctx)->ScheduleFrameEventX(event, offset_us, flags);
327 };
328 handler.wait_frame_event = [](void* ctx, UINT event, DWORD timeout_ms, UINT flags, std::uint64_t* token) {
329 return static_cast<XboxPresentation*>(ctx)->WaitFrameEventX(event, timeout_ms, flags, token);
330 };
331 handler.get_frame_statistics = [](void* ctx, std::uint64_t token, UINT type_mask, UINT* count, void* out) {
332 return static_cast<XboxPresentation*>(ctx)->GetFrameStatisticsX(
333 token, type_mask, count, static_cast<leonida::FrameStatistic*>(out));
334 };
335 handler.present_x = [](void* ctx, UINT plane_count, const void* planes, const void* params) {
336 return static_cast<XboxPresentation*>(ctx)->PresentX(
337 plane_count, static_cast<const XboxPresentPlaneParameters*>(planes),
338 static_cast<const XboxPresentParameters*>(params));
339 };
340 handler.suspend_x = [](void* ctx, UINT flags) {
341 return static_cast<XboxPresentation*>(ctx)->SuspendX(flags);
342 };
343 handler.resume_x = [](void* ctx) {
344 return static_cast<XboxPresentation*>(ctx)->ResumeX();
345 };
346 return rt::d3d12_xs::set_presentation_handler(device_proxy, &handler);
347}
348
349bool detach_xbox_presentation(void* device_proxy) {
350 return rt::d3d12_xs::set_presentation_handler(device_proxy, nullptr);
351}
352
317} // namespace rt::d3d12 353} // namespace rt::d3d12
diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h
index 60a317bee..007049d5d 100644
--- a/runtime/shims/xbox_present.h
+++ b/runtime/shims/xbox_present.h
@@ -199,5 +199,13 @@ private:
199}; 199};
200 200
201inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin; 201inline constexpr UINT xbox_frame_event_origin = leonida::frame_event_origin;
202inline constexpr UINT xbox_frame_event_vblank = leonida::frame_event_vblank;
203inline constexpr UINT xbox_frame_event_flip = leonida::frame_event_flip;
204inline constexpr UINT xbox_frame_wait_token_on_timeout = leonida::frame_wait_flag_token_on_timeout;
205
206// Wires an XboxPresentation into a d3d12_xs device proxy's frame-event slots (78–81) and queue PresentX/SuspendX/
207// ResumeX slots (default 30/31/32, configurable via LEONIDA_XS_*_SLOT). Passing nullptr detaches the presentation.
208bool attach_xbox_presentation(void* device_proxy, XboxPresentation* presentation);
209bool detach_xbox_presentation(void* device_proxy);
202 210
203} // namespace rt::d3d12 211} // namespace rt::d3d12
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h
index fa9c20df1..41b7c5b83 100644
--- a/runtime/src/frame_pacer.h
+++ b/runtime/src/frame_pacer.h
@@ -102,8 +102,13 @@ private:
102 std::function<void()> wake_; 102 std::function<void()> wake_;
103}; 103};
104 104
105// Provisional definitions of ours: the real constants and layouts of the console API are unmeasured. 105// Frame event kinds (0: origin, 1: vblank, 2: flip) and wait flags.
106inline constexpr std::uint32_t frame_event_origin = 0; 106inline constexpr std::uint32_t frame_event_origin = 0;
107inline constexpr std::uint32_t frame_event_vblank = 1;
108inline constexpr std::uint32_t frame_event_flip = 2;
109inline constexpr std::uint32_t frame_event_count = 3;
110// Issue a consecutive frame token even when WaitFrameEventX(origin, ...) times out (returns S_FALSE).
111inline constexpr std::uint32_t frame_wait_flag_token_on_timeout = 2;
107// Statistics types (bit mask). Interval and render entries are never produced here. 112// Statistics types (bit mask). Interval and render entries are never produced here.
108inline constexpr std::uint32_t stat_frame_interval = 0x01; 113inline constexpr std::uint32_t stat_frame_interval = 0x01;
109inline constexpr std::uint32_t stat_frame_event = 0x02; 114inline constexpr std::uint32_t stat_frame_event = 0x02;
@@ -177,38 +182,42 @@ public:
177 latency_ = std::max(latency, 1u); 182 latency_ = std::max(latency, 1u);
178 epoch_us_ = clock_.now_us(); 183 epoch_us_ = clock_.now_us();
179 interval_set_ = true; 184 interval_set_ = true;
180 offset_us_ = std::min(offset_us_, period_us - 1); 185 for (std::uint32_t k = 0; k < frame_event_count; ++k) {
181 last_origin_ = 0; // origin 0 is the epoch itself, which has passed 186 event_offset_us_[k] = std::min(event_offset_us_[k], period_us - 1);
187 last_event_tick_[k] = 0; // tick 0 is the epoch itself, which has passed
188 }
182 cv_.notify_all(); 189 cv_.notify_all();
183 return pacer_hr::ok; 190 return pacer_hr::ok;
184 } 191 }
185 192
186 // ScheduleFrameEventX(event, offset, ..., flags). Only the origin event exists here. 193 // ScheduleFrameEventX(event, offset, ..., flags). Supports origin (0), vblank (1), and flip (2).
187 std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) { 194 std::int32_t schedule_frame_event(std::uint32_t event, std::uint32_t offset_us, std::uint32_t flags) {
188 (void)flags; 195 (void)flags;
189 if (event != frame_event_origin) return pacer_hr::invalid_arg; 196 if (event >= frame_event_count) return pacer_hr::invalid_arg;
190 std::lock_guard guard(mutex_); 197 std::lock_guard guard(mutex_);
191 if (suspended_ || !interval_set_) return pacer_hr::invalid_state; 198 if (suspended_ || !interval_set_) return pacer_hr::invalid_state;
192 if (offset_us >= period_us_) return pacer_hr::invalid_arg; 199 if (offset_us >= period_us_) return pacer_hr::invalid_arg;
193 offset_us_ = offset_us; 200 event_offset_us_[event] = offset_us;
194 armed_ = true; 201 event_armed_[event] = true;
195 // The first origin is the next one that has not come yet: origin n is due at epoch + n * period + offset. 202 // The first event is the next one that has not come yet: tick n is due at epoch + n * period + offset.
196 const std::uint64_t now = clock_.now_us(); 203 const std::uint64_t now = clock_.now_us();
197 last_origin_ = now >= epoch_us_ + offset_us_ ? std::int64_t((now - epoch_us_ - offset_us_) / period_us_) : 0; 204 last_event_tick_[event] =
205 now >= epoch_us_ + offset_us ? std::int64_t((now - epoch_us_ - offset_us) / period_us_) : 0;
198 cv_.notify_all(); 206 cv_.notify_all();
199 return pacer_hr::ok; 207 return pacer_hr::ok;
200 } 208 }
201 209
202 // WaitFrameEventX(event, timeout, ..., flags, &token). Blocks until the next origin, and while `latency` frames 210 // WaitFrameEventX(event, timeout, ..., flags, &token). Origin waits block until the next origin tick and while
203 // are in flight. pacer_hr::timeout when `timeout_ms` passes first (infinite_timeout_ms: never); the token is left 211 // `latency` frames are in flight, issuing a consecutive token on success (or on timeout with
204 // alone then. invalid_state when nothing is registered, the pacer is suspended, or one of those happens while waiting. 212 // frame_wait_flag_token_on_timeout, returning S_FALSE). Vblank/flip waits pace independently per event kind and
213 // leave `*token` untouched.
205 std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags, 214 std::int32_t wait_frame_event(std::uint32_t event, std::uint32_t timeout_ms, std::uint32_t flags,
206 std::uint64_t* token) { 215 std::uint64_t* token) {
207 (void)flags; 216 if (event >= frame_event_count) return pacer_hr::invalid_arg;
208 if (event != frame_event_origin || !token) return pacer_hr::invalid_arg; 217 if (event == frame_event_origin && !token) return pacer_hr::invalid_arg;
209 std::unique_lock lock(mutex_); 218 std::unique_lock lock(mutex_);
210 ++waiters_; 219 ++waiters_;
211 const std::int32_t result = wait_locked(lock, timeout_ms, token); 220 const std::int32_t result = wait_locked(lock, event, timeout_ms, flags, token);
212 if (--waiters_ == 0) cv_.notify_all(); 221 if (--waiters_ == 0) cv_.notify_all();
213 return result; 222 return result;
214 } 223 }
@@ -302,7 +311,7 @@ public:
302 const std::uint64_t now = clock_.now_us(); 311 const std::uint64_t now = clock_.now_us();
303 retire_locked(now); 312 retire_locked(now);
304 last_presented_ = std::max(last_presented_, token); 313 last_presented_ = std::max(last_presented_, token);
305 if (!interval_set_ || !armed_ || uncapped_) { // not paced or uncapped: shows at once 314 if (!interval_set_ || !any_armed_locked() || uncapped_) { // not paced or uncapped: shows at once
306 for (Record& r : records_) 315 for (Record& r : records_)
307 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } 316 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; }
308 return; 317 return;
@@ -330,7 +339,7 @@ public:
330 // the origin event not armed or the cap off it is not paced: it shows at once and is not counted. 339 // the origin event not armed or the cap off it is not paced: it shows at once and is not counted.
331 void note_untokened_present() { 340 void note_untokened_present() {
332 std::lock_guard guard(mutex_); 341 std::lock_guard guard(mutex_);
333 if (!interval_set_ || !armed_ || uncapped_) return; 342 if (!interval_set_ || !any_armed_locked() || uncapped_) return;
334 const std::uint64_t now = clock_.now_us(); 343 const std::uint64_t now = clock_.now_us();
335 retire_locked(now); 344 retire_locked(now);
336 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; 345 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0;
@@ -344,7 +353,8 @@ public:
344 void suspend() { 353 void suspend() {
345 std::lock_guard guard(mutex_); 354 std::lock_guard guard(mutex_);
346 suspended_ = true; 355 suspended_ = true;
347 interval_set_ = armed_ = false; 356 interval_set_ = false;
357 for (bool& a : event_armed_) a = false;
348 pending_.clear(); 358 pending_.clear();
349 cv_.notify_all(); 359 cv_.notify_all();
350 } 360 }
@@ -352,7 +362,8 @@ public:
352 void resume() { 362 void resume() {
353 std::lock_guard guard(mutex_); 363 std::lock_guard guard(mutex_);
354 suspended_ = false; 364 suspended_ = false;
355 interval_set_ = armed_ = false; 365 interval_set_ = false;
366 for (bool& a : event_armed_) a = false;
356 cv_.notify_all(); 367 cv_.notify_all();
357 } 368 }
358 369
@@ -366,7 +377,7 @@ public:
366 // Frames that were flipped mid-scan because of ImmediateThresholdPercent. 377 // Frames that were flipped mid-scan because of ImmediateThresholdPercent.
367 std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; } 378 std::uint64_t immediate_presents() const { std::lock_guard guard(mutex_); return immediate_presents_; }
368 std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; } 379 std::uint32_t period_us() const { std::lock_guard guard(mutex_); return period_us_; }
369 bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && armed_; } 380 bool registered() const { std::lock_guard guard(mutex_); return interval_set_ && any_armed_locked(); }
370 381
371 // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown 382 // The fps cap off (LEONIDA_PRESENT_UNCAP; see the top comment): waits never block and presents count as shown
372 // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume. 383 // at once. Registration and suspension keep meaning what they did; the flag survives suspend/resume.
@@ -399,45 +410,67 @@ private:
399 } 410 }
400 } 411 }
401 412
402 std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t timeout_ms, std::uint64_t* token) { 413 bool any_armed_locked() const {
414 return event_armed_[0] || event_armed_[1] || event_armed_[2];
415 }
416
417 std::uint64_t issue_token_locked(std::uint64_t origin_us, std::uint64_t due_us) {
418 const std::uint64_t tok = ++issued_;
419 Record record;
420 record.token = tok;
421 record.origin_us = origin_us;
422 record.due_us = due_us;
423 records_.push_back(record);
424 if (records_.size() > 64) records_.pop_front();
425 return tok;
426 }
427
428 std::int32_t wait_locked(std::unique_lock<std::mutex>& lock, std::uint32_t event, std::uint32_t timeout_ms,
429 std::uint32_t flags, std::uint64_t* token) {
430 const bool is_origin = (event == frame_event_origin);
431 const bool token_on_timeout = (flags & frame_wait_flag_token_on_timeout) != 0;
403 const std::uint64_t start = clock_.now_us(); 432 const std::uint64_t start = clock_.now_us();
404 const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline 433 const std::uint64_t give_up = timeout_ms == infinite_timeout_ms ? no_deadline
405 : start + std::uint64_t(timeout_ms) * 1000; 434 : start + std::uint64_t(timeout_ms) * 1000;
406 for (;;) { 435 for (;;) {
407 if (shutdown_ || suspended_ || !interval_set_ || !armed_) return pacer_hr::invalid_state; 436 if (shutdown_ || suspended_ || !interval_set_) return pacer_hr::invalid_state;
437 if (is_origin ? !event_armed_[frame_event_origin]
438 : (!event_armed_[event] && !event_armed_[frame_event_origin])) {
439 return pacer_hr::invalid_state;
440 }
408 const std::uint64_t now = clock_.now_us(); 441 const std::uint64_t now = clock_.now_us();
409 retire_locked(now); 442 retire_locked(now);
410 if (uncapped_) { // no vblank grid and no latency throttle: a token at once, due now 443 if (uncapped_) { // no vblank grid and no latency throttle
411 *token = ++issued_; 444 if (is_origin) *token = issue_token_locked(now, now);
412 Record record;
413 record.token = *token;
414 record.origin_us = now;
415 record.due_us = now;
416 records_.push_back(record);
417 if (records_.size() > 64) records_.pop_front();
418 return pacer_hr::ok; 445 return pacer_hr::ok;
419 } 446 }
420 const std::uint64_t first = epoch_us_ + offset_us_; // origin 0 447 const std::uint32_t offset = event_offset_us_[event];
421 const std::int64_t next = last_origin_ + 1; 448 const std::uint64_t first = epoch_us_ + offset; // tick 0
449 const std::int64_t next = last_event_tick_[event] + 1;
422 const std::uint64_t next_us = first + std::uint64_t(next) * period_us_; 450 const std::uint64_t next_us = first + std::uint64_t(next) * period_us_;
423 std::uint64_t wake = next_us; 451 std::uint64_t wake = next_us;
424 if (now >= next_us) { 452 if (now >= next_us) {
425 if (pending_.size() < latency_) { 453 if (!is_origin || pending_.size() < latency_) {
426 const std::int64_t newest = std::int64_t((now - first) / period_us_); 454 const std::int64_t newest = std::int64_t((now - first) / period_us_);
427 const std::int64_t origin = std::max(next, newest); 455 const std::int64_t tick = std::max(next, newest);
428 last_origin_ = origin; 456 last_event_tick_[event] = tick;
429 *token = ++issued_; 457 if (is_origin) {
430 Record record; 458 const std::uint64_t origin_us = first + std::uint64_t(tick) * period_us_;
431 record.token = *token; 459 const std::uint64_t due_us = origin_us - offset + period_us_;
432 record.origin_us = first + std::uint64_t(origin) * period_us_; 460 *token = issue_token_locked(origin_us, due_us);
433 record.due_us = record.origin_us - offset_us_ + period_us_; 461 }
434 records_.push_back(record);
435 if (records_.size() > 64) records_.pop_front();
436 return pacer_hr::ok; 462 return pacer_hr::ok;
437 } 463 }
438 wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown 464 wake = pending_.front().flip_us; // blocked by the latency: until the oldest frame is shown
439 } 465 }
440 if (give_up != no_deadline && now >= give_up) return pacer_hr::timeout; 466 if (give_up != no_deadline && now >= give_up) {
467 if (is_origin && token_on_timeout) {
468 // Frame started early on timeout: issue a consecutive token without consuming the tick.
469 *token = issue_token_locked(now, next_us - offset + period_us_);
470 return pacer_hr::false_;
471 }
472 return token_on_timeout ? pacer_hr::false_ : pacer_hr::timeout;
473 }
441 clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up)); 474 clock_.wait(lock, cv_, give_up == no_deadline ? wake : std::min(wake, give_up));
442 } 475 }
443 } 476 }
@@ -450,13 +483,13 @@ private:
450 483
451 bool suspended_ = false; 484 bool suspended_ = false;
452 bool interval_set_ = false; 485 bool interval_set_ = false;
453 bool armed_ = false; 486 bool event_armed_[frame_event_count] = {false, false, false};
454 bool uncapped_ = false; 487 bool uncapped_ = false;
455 std::uint32_t period_us_ = 0; 488 std::uint32_t period_us_ = 0;
456 std::uint32_t latency_ = 1; 489 std::uint32_t latency_ = 1;
457 std::uint32_t offset_us_ = 0; 490 std::uint32_t event_offset_us_[frame_event_count] = {0, 0, 0};
458 std::uint64_t epoch_us_ = 0; 491 std::uint64_t epoch_us_ = 0;
459 std::int64_t last_origin_ = 0; // origin 0 is the epoch itself, which has passed 492 std::int64_t last_event_tick_[frame_event_count] = {0, 0, 0}; // tick 0 is the epoch itself, which has passed
460 std::uint64_t issued_ = 0; 493 std::uint64_t issued_ = 0;
461 std::uint64_t last_presented_ = 0; 494 std::uint64_t last_presented_ = 0;
462 std::uint64_t immediate_presents_ = 0; 495 std::uint64_t immediate_presents_ = 0;
diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp
index 8d089acda..b14148f87 100644
--- a/runtime/test/frame_pacer_test.cpp
+++ b/runtime/test/frame_pacer_test.cpp
@@ -586,6 +586,47 @@ int main() {
586 EXPECT(ms.count() >= 45 && ms.count() < 1000); 586 EXPECT(ms.count() >= 45 && ms.count() < 1000);
587 } 587 }
588 588
589 // TOKEN_ON_TIMEOUT (flag 2) and multi-event pacing (origin poll + blocking flip/vblank wait).
590 {
591 ManualFrameClock clock;
592 FramePacer pacer(clock);
593 EXPECT(pacer.set_frame_interval(period, 3, 0) == pacer_hr::ok);
594 EXPECT(pacer.schedule_frame_event(frame_event_origin, 0, 0) == pacer_hr::ok);
595 EXPECT(pacer.schedule_frame_event(frame_event_vblank, 0, 0) == pacer_hr::ok);
596 EXPECT(pacer.schedule_frame_event(frame_event_flip, 0, 0) == pacer_hr::ok);
597
598 // Origin poll with timeout 0 and TOKEN_ON_TIMEOUT issues a consecutive token and returns S_FALSE.
599 std::uint64_t tok1 = 0;
600 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, frame_wait_flag_token_on_timeout, &tok1) ==
601 pacer_hr::false_);
602 EXPECT(tok1 == 1);
603 EXPECT(pacer.check_present_token(tok1) == pacer_hr::ok);
604
605 // A blocking flip wait paces to the next tick and preserves the caller's token unchanged.
606 auto flip_wait = std::async(std::launch::async, [&] {
607 std::uint64_t preserved = tok1;
608 const std::int32_t hr = pacer.wait_frame_event(frame_event_flip, infinite_timeout_ms, 0, &preserved);
609 return Result{hr, preserved};
610 });
611 EXPECT(blocked(flip_wait));
612 clock.advance_us(period);
613 const Result fr = flip_wait.get();
614 EXPECT(fr.hr == pacer_hr::ok && fr.token == tok1);
615
616 // Second flip wait blocks for the following tick; vblank wait on tick 1 succeeds immediately (independent).
617 EXPECT(pacer.wait_frame_event(frame_event_vblank, 0, 0, nullptr) == pacer_hr::ok);
618 auto flip_wait2 = std::async(std::launch::async, [&] {
619 return Result{pacer.wait_frame_event(frame_event_flip, infinite_timeout_ms, 0, nullptr), 0};
620 });
621 EXPECT(blocked(flip_wait2));
622 clock.advance_us(period);
623 EXPECT(flip_wait2.get().hr == pacer_hr::ok);
624
625 // Origin wait at tick 2 advances consecutively after the early-started token 1.
626 std::uint64_t tok2 = 0;
627 EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &tok2) == pacer_hr::ok && tok2 == 2);
628 }
629
589 std::printf("frame_pacer_test: all cases pass\n"); 630 std::printf("frame_pacer_test: all cases pass\n");
590 return 0; 631 return 0;
591} 632}
diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp
index 6af7ad804..fd6019396 100644
--- a/runtime/test/xs_proxy_mock_test.cpp
+++ b/runtime/test/xs_proxy_mock_test.cpp
@@ -1239,6 +1239,96 @@ int check_console_command_list() {
1239 return 0; 1239 return 0;
1240} 1240}
1241 1241
1242// ---- 11. Presentation handler wiring (device slots 78–81 + queue PresentX/SuspendX/ResumeX) ----
1243
1244struct MockPresenter {
1245 int interval_calls = 0;
1246 UINT last_interval = 0;
1247 int schedule_calls = 0;
1248 UINT last_event = 0;
1249 int wait_calls = 0;
1250 UINT last_flags = 0;
1251 int stats_calls = 0;
1252 int present_calls = 0;
1253 UINT last_planes = 0;
1254 int suspend_calls = 0;
1255 int resume_calls = 0;
1256};
1257
1258int check_presentation_wiring() {
1259 Mock* mock = nullptr;
1260 void* device = make_device(mock, 11, true);
1261 EXPECT(device != nullptr);
1262 void* queue = make_queue(device);
1263 EXPECT(queue != nullptr);
1264
1265 MockPresenter p{};
1266 xs::PresentationHandler h{};
1267 h.context = &p;
1268 h.set_frame_interval = [](void* ctx, IUnknown*, UINT us, UINT, UINT) -> HRESULT {
1269 auto* m = static_cast<MockPresenter*>(ctx);
1270 ++m->interval_calls;
1271 m->last_interval = us;
1272 return S_OK;
1273 };
1274 h.schedule_frame_event = [](void* ctx, UINT ev, UINT, UINT) -> HRESULT {
1275 auto* m = static_cast<MockPresenter*>(ctx);
1276 ++m->schedule_calls;
1277 m->last_event = ev;
1278 return S_OK;
1279 };
1280 h.wait_frame_event = [](void* ctx, UINT, DWORD, UINT flags, std::uint64_t* tok) -> HRESULT {
1281 auto* m = static_cast<MockPresenter*>(ctx);
1282 ++m->wait_calls;
1283 m->last_flags = flags;
1284 if (tok) *tok = 77;
1285 return S_FALSE;
1286 };
1287 h.get_frame_statistics = [](void* ctx, std::uint64_t, UINT, UINT* count, void*) -> HRESULT {
1288 auto* m = static_cast<MockPresenter*>(ctx);
1289 ++m->stats_calls;
1290 if (count) *count = 0;
1291 return S_FALSE;
1292 };
1293 h.present_x = [](void* ctx, UINT plane_count, const void*, const void*) -> HRESULT {
1294 auto* m = static_cast<MockPresenter*>(ctx);
1295 ++m->present_calls;
1296 m->last_planes = plane_count;
1297 return S_OK;
1298 };
1299 h.suspend_x = [](void* ctx, UINT) -> HRESULT {
1300 ++static_cast<MockPresenter*>(ctx)->suspend_calls;
1301 return S_OK;
1302 };
1303 h.resume_x = [](void* ctx) -> HRESULT {
1304 ++static_cast<MockPresenter*>(ctx)->resume_calls;
1305 return S_OK;
1306 };
1307
1308 EXPECT(xs::set_presentation_handler(device, &h));
1309 EXPECT(hr_of(raw(device, 78, 0, 33333, 2, 0)) == S_OK && p.interval_calls == 1 && p.last_interval == 33333);
1310 EXPECT(hr_of(raw(device, 79, 2, 0, 0, 0)) == S_OK && p.schedule_calls == 1 && p.last_event == 2);
1311 std::uint64_t tok = 0;
1312 EXPECT(hr_of(raw(device, 80, 0, 0, 0, 2, word(&tok))) == S_FALSE && tok == 77 && p.wait_calls == 1 &&
1313 p.last_flags == 2);
1314 UINT count = 3;
1315 EXPECT(hr_of(raw(device, 81, 77, 0x1a, word(&count), 0)) == S_FALSE && count == 0 && p.stats_calls == 1);
1316
1317 // Queue slots 30/31/32 route to PresentX / SuspendX / ResumeX while attached.
1318 EXPECT(hr_of(raw(queue, 30, 1, 0x1000, 0x2000)) == S_OK && p.present_calls == 1 && p.last_planes == 1);
1319 EXPECT(hr_of(raw(queue, 31, 0)) == S_OK && p.suspend_calls == 1);
1320 EXPECT(hr_of(raw(queue, 32)) == S_OK && p.resume_calls == 1);
1321
1322 // Detaching restores default E_NOTIMPL refusal on beyond-PC queue slots.
1323 EXPECT(xs::set_presentation_handler(device, nullptr));
1324 EXPECT(hr_of(raw(queue, 30, 1, 0, 0)) == E_NOTIMPL && p.present_calls == 1);
1325
1326 EXPECT(release(queue) == 0);
1327 EXPECT(release(device) == 0 && mock->refs == 0);
1328 std::printf("%s: presentation handler wiring (slots 78-81 and queue 30-32) passed\n", g_label);
1329 return 0;
1330}
1331
1242int main(int argc, char** argv) { 1332int main(int argc, char** argv) {
1243 no_dialogs(); 1333 no_dialogs();
1244 std::setvbuf(stdout, nullptr, _IONBF, 0); 1334 std::setvbuf(stdout, nullptr, _IONBF, 0);
@@ -1249,7 +1339,8 @@ int main(int argc, char** argv) {
1249 } 1339 }
1250 if (argc != 1) return 2; 1340 if (argc != 1) return 2;
1251 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || 1341 if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() ||
1252 check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list()) 1342 check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list() ||
1343 check_presentation_wiring())
1253 return 1; 1344 return 1;
1254 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); 1345 std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news);
1255 return 0; 1346 return 0;