upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/test/acphal_test.cpp
diff options
context:
space:
mode:
authorubiquitarianism <283527159+ubiquitarianism@users.noreply.github.com>2026-11-24 08:44:46 -0500
committerGitHub <noreply@github.com>2026-11-24 08:44:46 -0500
commitd0da7dade8b688f2e0f7f23f4155d6cbb438809e (patch)
treed54ffb708fa43a286a5c744884222a5926527502 /runtime/test/acphal_test.cpp
parent89e0ea9b55d072bdb72a3771c9336b2f2990ba75 (diff)
parent713eec5031a6a7d1b1626f090d742531007b28e5 (diff)
Merge pull request #404 from ubiquitarianism/feat/acphal-xma2-decoder
acphal: ACP message queue and background XMA ring decoding with the Rust XMA2 decoder (RT-ACPHAL-XMA2)
Diffstat (limited to 'runtime/test/acphal_test.cpp')
-rw-r--r--runtime/test/acphal_test.cpp628
1 files changed, 620 insertions, 8 deletions
diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp
index bd93f7040..be2c6f1e1 100644
--- a/runtime/test/acphal_test.cpp
+++ b/runtime/test/acphal_test.cpp
@@ -6,13 +6,44 @@
6 6
7#include <windows.h> 7#include <windows.h>
8 8
9#include <algorithm>
10#include <atomic>
9#include <cstddef> 11#include <cstddef>
10#include <cstdint> 12#include <cstdint>
11#include <cstdio> 13#include <cstdio>
14#include <cstdlib>
12#include <cstring> 15#include <cstring>
16#include <new>
17#include <thread>
18#include <vector>
13 19
14#include "shims.h" 20#include "shims.h"
15 21
22// Fail only the calling test thread's designated allocation.
23static thread_local int allocations_before_failure = -1;
24static std::atomic<bool> fail_worker_allocation{false};
25static std::atomic<bool> count_worker_allocations{false};
26static std::atomic<unsigned> worker_allocations{0};
27static DWORD test_thread_id;
28void* operator new(std::size_t size) {
29 if (allocations_before_failure == 0) {
30 allocations_before_failure = -1;
31 throw std::bad_alloc();
32 }
33 if (fail_worker_allocation.load() && GetCurrentThreadId() != test_thread_id &&
34 fail_worker_allocation.exchange(false)) {
35 throw std::bad_alloc();
36 }
37 if (count_worker_allocations.load() && GetCurrentThreadId() != test_thread_id) {
38 worker_allocations.fetch_add(1, std::memory_order_relaxed);
39 }
40 if (allocations_before_failure > 0) --allocations_before_failure;
41 if (void* memory = std::malloc(size ? size : 1)) return memory;
42 throw std::bad_alloc();
43}
44void operator delete(void* memory) noexcept { std::free(memory); }
45void operator delete(void* memory, std::size_t) noexcept { std::free(memory); }
46
16namespace { 47namespace {
17 48
18using AcpHalCreateFn = HRESULT(__stdcall*)(void**); 49using AcpHalCreateFn = HRESULT(__stdcall*)(void**);
@@ -66,9 +97,62 @@ static_assert(sizeof(TestShapeContexts) == 120, "TestShapeContexts is 120 bytes"
66static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38, 97static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38,
67 "xmaContextArray is at offset +0x38"); 98 "xmaContextArray is at offset +0x38");
68 99
100struct XmaWords {
101 uint32_t* data;
102
103 std::atomic_ref<uint32_t> operator[](std::size_t index) const {
104 return std::atomic_ref(data[index]);
105 }
106};
107
108// Synthetic XMA2 with one nonzero spectral coefficient per channel and frame.
109void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip,
110 uint32_t rate_index = 3, bool stereo = false) {
111 constexpr uint32_t scale_bands[] = {23, 24, 23, 23};
112 const uint32_t bands = scale_bands[rate_index];
113 const uint32_t channels = stereo ? 2u : 1u;
114 const uint32_t frame_bits = stereo ? 90 + 2 * bands : 59 + bands;
115 std::memset(packet, 0xFF, 2048);
116 std::size_t at = 0;
117 auto put = [&](uint32_t value, std::size_t width) {
118 for (std::size_t i = 0; i < width; ++i, ++at) {
119 const auto mask = static_cast<uint8_t>(0x80u >> (at % 8));
120 packet[at / 8] &= static_cast<uint8_t>(~mask);
121 if ((value >> (width - 1 - i)) & 1u) packet[at / 8] |= mask;
122 }
123 };
124 put((frames << 26) | (1u << 8) | packet_skip, 32);
125 for (uint32_t frame = 0; frame < frames; ++frame) {
126 put(frame_bits, 15);
127 put(0b10u, 2); // Fixed layout, one 512-sample subframe.
128 if (stereo) put(0, 1); // No optional decorrelation matrix.
129 put(0, 11); // Gain, trim, fill and subframe error flag.
130 if (stereo) put(0b010u, 3); // Two channels without decorrelation.
131 put((1u << channels) - 1, channels); // Coefficients are present in each channel.
132 put(1, 1); // Explicit vector coefficient count.
133 put(0, 8 * channels); // Use only run/level coding.
134 put(0, 6); // Quantizer adjustment.
135 if (stereo) put(0, 5); // No per-channel quantizer modifiers.
136 for (uint32_t channel = 0; channel < channels; ++channel) {
137 put(0, 2); // Scale factor step.
138 put((1u << bands) - 1, bands); // One zero delta per scale band.
139 }
140 for (uint32_t channel = 0; channel < channels; ++channel) {
141 put(0, 1); // Run/level table 0.
142 put(0b00u, 2); // Run 0, level 1.
143 put(channel == 0 ? 1u : 0u, 1);
144 put(0b0101011u, 7); // End of coefficients.
145 }
146 put(0, 1); // Frame padding bit.
147 put(frame + 1 < frames ? 1 : 0, 1);
148 }
149}
150
69} // namespace 151} // namespace
70 152
71int main() { 153int main(int argc, char** argv) {
154 std::setvbuf(stdout, nullptr, _IONBF, 0);
155 test_thread_id = GetCurrentThreadId();
72 std::printf("acphal_test: registered acphal.dll shim verification\n"); 156 std::printf("acphal_test: registered acphal.dll shim verification\n");
73 157
74 const auto create = reinterpret_cast<AcpHalCreateFn>( 158 const auto create = reinterpret_cast<AcpHalCreateFn>(
@@ -107,18 +191,44 @@ int main() {
107 return 1; 191 return 1;
108 } 192 }
109 193
194 // Heap configuration is process-wide, so CTest exercises this mode separately.
195 if (argc == 2 && std::strcmp(argv[1], "--noncached-only") == 0) {
196 check(create_heap(0, 0x6000u) == S_OK, "Create only the non-cached APU heap");
197 void* noncached = nullptr;
198 uint32_t noncached_address = 0;
199 check(alloc(&noncached, &noncached_address, 0x1000, 0x800, 2) == S_OK && noncached != nullptr,
200 "Allocate from the non-cached heap");
201 void* cached = noncached;
202 uint32_t cached_address = noncached_address;
203 check(alloc(&cached, &cached_address, 0x1000, 0x800, 1) == E_OUTOFMEMORY &&
204 cached == nullptr && cached_address == 0,
205 "A missing cached heap stays unavailable after explicit configuration");
206 check(map_apu(noncached_address) == noncached && map_virtual(noncached) == noncached_address,
207 "A failed cached allocation leaves the non-cached mapping unchanged");
208 free_mem(noncached);
209 std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures);
210 return g_failures != 0;
211 }
212
110 // 1. AcpHalCreate 213 // 1. AcpHalCreate
111 void* acp = nullptr; 214 void* acp = nullptr;
112 check(create(&acp) == S_OK && acp != nullptr, 215 check(create(&acp) == S_OK && acp != nullptr,
113 "AcpHalCreate returns S_OK with a non-null object"); 216 "AcpHalCreate returns S_OK with a non-null object");
114 check(create(nullptr) == E_POINTER, 217 check(create(nullptr) == E_POINTER,
115 "AcpHalCreate(nullptr) returns E_POINTER"); 218 "AcpHalCreate(nullptr) returns E_POINTER");
219 void* failed_hal = acp;
220 allocations_before_failure = 0;
221 const HRESULT create_failure = create(&failed_hal);
222 allocations_before_failure = -1;
223 check(create_failure == E_OUTOFMEMORY && failed_hal == nullptr,
224 "AcpHalCreate returns E_OUTOFMEMORY and clears the output");
116 225
117 if (acp) { 226 if (acp) {
118 using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); 227 using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
119 using Slot1Fn = HRESULT(__stdcall*)(void*); 228 using Slot1Fn = HRESULT(__stdcall*)(void*);
120 using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, const void*, uint32_t); 229 using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
121 using Slot3Fn = uint32_t(__stdcall*)(void*); 230 using Slot3Fn = uint32_t(__stdcall*)(void*, void*);
231 using Slot4Fn = uint32_t(__stdcall*)(void*);
122 using Slot5Fn = HRESULT(__stdcall*)(void*); 232 using Slot5Fn = HRESULT(__stdcall*)(void*);
123 233
124 auto vtable = *static_cast<void* const* const*>(acp); 234 auto vtable = *static_cast<void* const* const*>(acp);
@@ -139,8 +249,8 @@ int main() {
139 "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)"); 249 "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)");
140 250
141 // Slots 3 and 4: Message polling returns 0 251 // Slots 3 and 4: Message polling returns 0
142 check(reinterpret_cast<Slot3Fn>(vtable[3])(acp) == 0, "IAcpHal slot 3 returns 0"); 252 check(reinterpret_cast<Slot3Fn>(vtable[3])(acp, nullptr) == 0, "IAcpHal slot 3 returns 0");
143 check(reinterpret_cast<Slot3Fn>(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0"); 253 check(reinterpret_cast<Slot4Fn>(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0");
144 254
145 // Slot 1: Disconnect returns S_OK 255 // Slot 1: Disconnect returns S_OK
146 check(reinterpret_cast<Slot1Fn>(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK"); 256 check(reinterpret_cast<Slot1Fn>(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK");
@@ -150,8 +260,8 @@ int main() {
150 } 260 }
151 261
152 // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00) 262 // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00)
153 check(create_heap(4 * 1024 * 1024, 0x226e00) == S_OK, 263 check(create_heap(4 * 1024 * 1024 + 0x400, 0x226e00) == S_OK,
154 "ApuCreateHeap(4 MiB, 0x226e00) succeeds"); 264 "ApuCreateHeap succeeds with an unaligned cached heap size");
155 check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK, 265 check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK,
156 "ApuCreateHeap second call fails (heap already created)"); 266 "ApuCreateHeap second call fails (heap already created)");
157 267
@@ -252,11 +362,513 @@ int main() {
252 check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated"); 362 check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated");
253 check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated"); 363 check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated");
254 364
365 TestShapeContexts retry_ctx{};
366 retry_ctx.numXmaContexts = 2;
367 allocations_before_failure = 1; // The tracked allocation can grow, then voice slot allocation fails.
368 HRESULT allocation_result = E_UNEXPECTED;
369 try {
370 allocation_result = alloc_ctx(&retry_ctx);
371 } catch (const std::bad_alloc&) {
372 // An exception across the AcpHal boundary is a regression.
373 }
374 allocations_before_failure = -1;
375 check(allocation_result == E_OUTOFMEMORY && retry_ctx.xmaContextArray == nullptr,
376 "A failed XMA slot allocation returns E_OUTOFMEMORY without publishing a context");
377 check(alloc_ctx(&retry_ctx) == S_OK && retry_ctx.xmaContextArray != nullptr,
378 "SHAPE allocation can be retried after memory pressure");
379
255 // Release shape contexts 380 // Release shape contexts
381 std::memset(&ctx_all, 0x55, sizeof(ctx_all));
256 check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds"); 382 check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds");
257 check(ctx_all.xmaContextArray == nullptr, "xmaContextArray is reset to null"); 383 const auto* released_argument = reinterpret_cast<const uint8_t*>(&ctx_all);
384 check(std::all_of(released_argument, released_argument + sizeof(ctx_all),
385 [](uint8_t b) { return b == 0x55; }),
386 "SHAPE release does not write through an opaque or recycled argument");
258 check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds"); 387 check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds");
259 388
389 // 7. ACP command/message queue protocol (register, complete, overflow drops, disconnect, notify word)
390 {
391 #pragma pack(push, 1)
392 struct TestAcpMessage {
393 uint32_t kind;
394 uint32_t dropped;
395 uint32_t usec;
396 uint8_t data[16];
397 };
398 #pragma pack(pop)
399 static_assert(sizeof(TestAcpMessage) == 28, "ACP message is 28 bytes");
400
401 using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
402 using DisconnectFn = HRESULT(__stdcall*)(void*);
403 using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
404 using PopFn = uint32_t(__stdcall*)(void*, TestAcpMessage*);
405 using CountFn = uint32_t(__stdcall*)(void*);
406 using ReleaseFn = HRESULT(__stdcall*)(void*);
407
408 void* q_acp = nullptr;
409 check(create(&q_acp) == S_OK && q_acp != nullptr, "AcpHalCreate for queue test");
410 auto vt = *static_cast<void* const* const*>(q_acp);
411 const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]);
412 const auto fn_disconnect = reinterpret_cast<DisconnectFn>(vt[1]);
413 const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]);
414 const auto fn_pop = reinterpret_cast<PopFn>(vt[3]);
415 const auto fn_count = reinterpret_cast<CountFn>(vt[4]);
416 const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]);
417
418 check(fn_connect(q_acp, 0, 16) == E_INVALIDARG, "Connect(commands=0) returns E_INVALIDARG");
419 check(fn_disconnect(q_acp) == E_FAIL, "Disconnect before Connect returns E_FAIL");
420 check(fn_connect(q_acp, 16, 2) == S_OK, "Connect(16, 2) succeeds");
421
422 // Allocate a 4-byte notification word in APU memory.
423 void* notify_va = nullptr;
424 uint32_t notify_apu = 0;
425 check(alloc(&notify_va, &notify_apu, 16, 16, 1) == S_OK && notify_va != nullptr,
426 "ApuAlloc notification word succeeds");
427 *static_cast<uint32_t*>(notify_va) = 0;
428
429 const uint32_t reg_mask = 0x92u; // FLOWGRAPH_COMPLETED(0x02) | COMMAND_COMPLETED(0x10) | DISCONNECTED(0x80)
430 check(fn_submit(q_acp, 2, 0x1122334455667788ull, 0xffffffffu, &reg_mask, notify_apu) == S_OK,
431 "REGISTER_MESSAGES with id and notify word succeeds");
432 check(*static_cast<volatile uint32_t*>(notify_va) == 1u,
433 "SubmitCommand writes 1 to APU notification word");
434 check(fn_count(q_acp) == 1u, "COMMAND_COMPLETED queued after REGISTER_MESSAGES");
435
436 TestAcpMessage msg{};
437 check(fn_pop(q_acp, &msg) == 1u, "PopMessage retrieves COMMAND_COMPLETED");
438 uint32_t ack_cmd = 0;
439 uint64_t ack_id = 0;
440 std::memcpy(&ack_cmd, msg.data, 4);
441 std::memcpy(&ack_id, msg.data + 4, 8);
442 check(msg.kind == 0x10u && msg.dropped == 0u && ack_cmd == 2u && ack_id == 0x1122334455667788ull,
443 "COMMAND_COMPLETED payload carries command id and 64-bit token");
444
445 // Overflow queue of capacity 2 with 4 commands -> 2 dropped, reported on the 5th.
446 for (uint64_t tok = 1; tok <= 4; ++tok) {
447 check(fn_submit(q_acp, 12, tok, 0xffffffffu, nullptr, 0) == S_OK,
448 "SubmitCommand during overflow succeeds");
449 }
450 check(fn_count(q_acp) == 2u, "Message queue caps at capacity 2");
451 check(fn_pop(q_acp, &msg) == 1u && fn_pop(q_acp, &msg) == 1u,
452 "Drained the 2 queued messages");
453 check(fn_submit(q_acp, 12, 5, 0xffffffffu, nullptr, 0) == S_OK,
454 "SubmitCommand 5 after drain succeeds");
455 check(fn_pop(q_acp, &msg) == 1u && msg.dropped == 2u,
456 "Next queued message reports dropped == 2");
457
458 // LOAD_FLOWGRAPH posts FLOWGRAPH_COMPLETED carrying word(1).
459 const uint32_t fg_cfg[2] = {0, 0x42u};
460 check(fn_submit(q_acp, 1, 0, 0xffffffffu, fg_cfg, 0) == S_OK, "LOAD_FLOWGRAPH succeeds");
461 check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x02u, "FLOWGRAPH_COMPLETED queued");
462 uint32_t fg_id = 0;
463 std::memcpy(&fg_id, msg.data, 4);
464 check(fg_id == 0x42u, "FLOWGRAPH_COMPLETED carries flowgraph word");
465
466 const uint32_t command_completed_mask = 0x10u;
467 check(fn_submit(q_acp, 3, 0x100u, 0xffffffffu, &command_completed_mask, 0) == S_OK &&
468 fn_count(q_acp) == 0u,
469 "UNREGISTER_MESSAGES suppresses command-completed messages");
470
471 // Disconnect posts DISCONNECTED.
472 check(fn_disconnect(q_acp) == S_OK, "Disconnect succeeds when connected");
473 check(fn_count(q_acp) == 1u, "Disconnect queued DISCONNECTED message");
474 check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x80u, "Popped DISCONNECTED message");
475
476 free_mem(notify_va);
477 check(fn_release(q_acp) == S_OK, "Release queue AcpHal succeeds");
478 }
479
480 // 8. End-to-end XMA2 context ring decoding via background decoder thread
481 {
482 // Two synthetic XMA2 packets with three mono frames each. Each frame
483 // transmits one positive spectral coefficient so decoded PCM differs from fallback silence.
484 TestShapeContexts xma_ctx{};
485 xma_ctx.numXmaContexts = 4;
486 check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr,
487 "Allocate 4 XMA SHAPE contexts");
488
489 void* in_va = nullptr;
490 uint32_t in_apu = 0;
491 check(alloc(&in_va, &in_apu, 0x1000, 0x800, 1) == S_OK && in_va != nullptr,
492 "ApuAlloc 2-packet XMA2 input buffer");
493 auto* packets = static_cast<uint8_t*>(in_va);
494 write_xma_packet(packets, 3, 0);
495 write_xma_packet(packets + 2048, 3, 0);
496
497 void* out_va = nullptr;
498 uint32_t out_apu = 0;
499 check(alloc(&out_va, &out_apu, 0x400, 0x100, 2) == S_OK && out_va != nullptr,
500 "ApuAlloc 4-block XMA2 output ring");
501 std::memset(out_va, 0x55, 0x400);
502
503 // Configure voice index 1: 2 packets in input 0, input 0 valid, 4 output blocks,
504 // writable = 1, 48 kHz mono, read_bit = 32.
505 const XmaWords words{static_cast<uint32_t*>(xma_ctx.xmaContextArray) + 16};
506 words[0] = 2u | (1u << 20) | (4u << 22);
507 words[1] = (1u << 31) | (3u << 27);
508 words[2] = 32u;
509 words[5] = in_apu;
510 words[7] = out_apu;
511
512 using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
513 using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
514 using ReleaseFn = HRESULT(__stdcall*)(void*);
515
516 void* x_acp = nullptr;
517 check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for XMA decode test");
518 auto vt = *static_cast<void* const* const*>(x_acp);
519 const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]);
520 const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]);
521 const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]);
522
523 check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA decode test");
524
525 // ENABLE_XMA (cmd 5) on voice 1.
526 const uint32_t enable_arg = 1u;
527 worker_allocations.store(0);
528 count_worker_allocations.store(true);
529 check(fn_submit(x_acp, 5, 0xf1, 0xffffffffu, &enable_arg, 0) == S_OK,
530 "ENABLE_XMA voice 1 succeeds");
531
532 // Wait up to 500 ms for the background decoder thread to fill the 4-block ring.
533 for (int wait = 0; wait < 500 && ((words[1] >> 31) & 1u) == 1u; ++wait) {
534 Sleep(1);
535 }
536 const bool ring_full = (words[1] >> 31) == 0u;
537 check(ring_full, "Background XMA2 decoder fills ring and clears writable flag");
538 check(((words[0] >> 27) & 0x1Fu) == 0u,
539 "Write block wrapped back to 0 after filling 4 blocks");
540
541 const auto* ring_bytes = static_cast<const uint8_t*>(out_va);
542#if defined(LEONIDA_HAVE_XMA2_DECODER)
543 check(ring_full && std::any_of(ring_bytes, ring_bytes + 0x400,
544 [](uint8_t b) { return b != 0 && b != 0x55; }),
545 "The Rust decoder writes non-silent PCM");
546#else
547 check(ring_full && std::all_of(ring_bytes, ring_bytes + 0x400, [](uint8_t b) { return b == 0; }),
548 "The fallback writes silence");
549#endif
550
551 // Advance read pointer 4 blocks at a time until input exhausts and INPUT_INVALID fires.
552 const uint32_t advance_args[2] = {1u, 4u};
553 int written_blocks = ring_full ? 4 : 0;
554 bool advanced = true;
555 for (int step = 0; step < 6; ++step) {
556 advanced &= fn_submit(x_acp, 18, 0xf2 + static_cast<uint64_t>(step),
557 0xffffffffu, advance_args, 0) == S_OK;
558 // Wait until either ring fills again (writable == 0) or stream hits error bit.
559 for (int wait = 0; wait < 200; ++wait) {
560 const uint32_t w1 = words[1];
561 const uint32_t w2 = words[2];
562 if (((w1 >> 31) & 1u) == 0u || ((w2 >> 31) & 1u) == 1u) break;
563 Sleep(1);
564 }
565 if (((words[2] >> 31) & 1u) == 1u && ((words[1] >> 31) & 1u) == 1u) {
566 break;
567 }
568 if ((words[1] >> 31) != 0u) break;
569 written_blocks += 4;
570 }
571 check(advanced, "ADVANCE_XMA_READ succeeds");
572 check(written_blocks == 24, "Six frames write exactly 24 blocks before input exhaustion");
573 count_worker_allocations.store(false);
574 const unsigned allocation_count = worker_allocations.load();
575 std::printf("C++ worker allocations for six PCM frames: %u\n", allocation_count);
576 check(allocation_count > 0 && allocation_count < 16,
577 "PCM storage is reused across packets instead of allocating per sample block");
578 check(((words[0] >> 20) & 3u) == 0u, "XMA input buffer valid bits cleared on exhaustion");
579 check(((words[2] >> 31) & 1u) == 1u, "XMA error flag set on exhaustion");
580 check(((words[2] >> 26) & 0x1Fu) == 4u, "XMA error status is INPUT_INVALID (4)");
581
582 // DISABLE_XMA (cmd 7) on voice 1.
583 const uint32_t disable_arg = 1u;
584 check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &disable_arg, 0) == S_OK,
585 "DISABLE_XMA voice 1 succeeds");
586 check(fn_release(x_acp) == S_OK, "Release XMA AcpHal succeeds");
587 free_mem(in_va);
588 free_mem(out_va);
589 check(release_ctx(&xma_ctx) == S_OK, "Release XMA SHAPE contexts joins decoder cleanly");
590 }
591
592 // 8b. Loops are rounded to whole packets: the loop end packet plays in full and the read
593 // restarts at the packet holding the loop start. One 1-frame packet = 512 samples = 4 blocks.
594 {
595 TestShapeContexts xma_ctx{};
596 xma_ctx.numXmaContexts = 4;
597 check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr,
598 "Allocate 4 XMA SHAPE contexts for the packet loop test");
599
600 void* in_va = nullptr;
601 uint32_t in_apu = 0;
602 check(alloc(&in_va, &in_apu, 0x2000, 0x800, 2) == S_OK && in_va != nullptr &&
603 (in_apu & 0x7FFu) == 0 && map_apu(in_apu) == in_va,
604 "Non-cached XMA input keeps its requested alignment and round trips");
605 auto* packets = static_cast<uint8_t*>(in_va);
606 write_xma_packet(packets, 1, 1); // Packet 1 belongs to another stream.
607 write_xma_packet(packets + 0x800, 2, 0);
608 write_xma_packet(packets + 0x1000, 1, 0);
609
610 void* out_va = nullptr;
611 uint32_t out_apu = 0;
612 check(alloc(&out_va, &out_apu, 0x1000, 0x100, 2) == S_OK && out_va != nullptr,
613 "ApuAlloc 16-block loop output ring");
614
615 // Voice index 2.
616 const XmaWords words{static_cast<uint32_t*>(xma_ctx.xmaContextArray) + 32};
617
618 using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
619 using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
620 using ReleaseFn = HRESULT(__stdcall*)(void*);
621
622 void* x_acp = nullptr;
623 check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for packet loop test");
624 auto vt = *static_cast<void* const* const*>(x_acp);
625 const auto fn_connect = reinterpret_cast<ConnectFn>(vt[0]);
626 const auto fn_submit = reinterpret_cast<SubmitFn>(vt[2]);
627 const auto fn_release = reinterpret_cast<ReleaseFn>(vt[5]);
628 check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for packet loop test");
629
630 auto configure_voice = [&](uint32_t loops, uint32_t input_0_packets, uint32_t ring_size,
631 uint32_t write, uint32_t read) {
632 std::memset(out_va, 0x55, 0x1000);
633 const uint32_t input_1_packets = 3u - input_0_packets;
634 words[0] = input_0_packets | (loops << 12) |
635 ((input_1_packets != 0 ? 3u : 1u) << 20) | (ring_size << 22) | (write << 27);
636 words[1] = (1u << 31) | (3u << 27) | input_1_packets;
637 words[2] = 32u; // read at packet 0
638 words[3] = 32u; // loop start: packet 0
639 words[4] = 100u; // loop end: packet 0
640 words[5] = in_apu;
641 words[6] = in_apu + input_0_packets * 2048u;
642 words[7] = out_apu;
643 words[9] = read;
644 };
645
646 const uint32_t voice_index = 2u;
647 // Returns the number of blocks written before input exhaustion, or -1 on timeout.
648 auto run_blocks = [&](uint32_t loops, uint32_t input_0_packets = 3,
649 uint32_t initial_skip = 0, uint32_t loop_skip = 0) -> int {
650 configure_voice(loops, input_0_packets, 16, 0, 0);
651 words[1].fetch_or((initial_skip << 24) | (loop_skip << 17));
652 check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK,
653 "ENABLE_XMA voice 2 succeeds");
654 int wait = 0;
655 for (; wait < 1000 && ((words[2] >> 31) & 1u) == 0u; ++wait) {
656 Sleep(1);
657 }
658 const int blocks = ((words[2] >> 31) & 1u) != 0u
659 ? static_cast<int>((words[0] >> 27) & 0x1Fu)
660 : -1;
661 check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK,
662 "DISABLE_XMA voice 2 succeeds");
663 return blocks;
664 };
665
666 check(run_blocks(0) == 8, "Packets 0 and 2 write 8 blocks, skipping packet 1");
667 check(run_blocks(1) == 12, "One loop of packet 0 writes 12 blocks (packets 0, 0, 2)");
668 check(((words[0] >> 12) & 0xFFu) == 0u, "Loop count is consumed by the single loop");
669 const auto* ring_bytes = static_cast<const uint8_t*>(out_va);
670#if defined(LEONIDA_HAVE_XMA2_DECODER)
671 auto has_signal = [](const uint8_t* start) {
672 return std::any_of(start, start + 0x400, [](uint8_t b) { return b != 0 && b != 0x55; });
673 };
674 check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400) && has_signal(ring_bytes + 0x800),
675 "Rust produces signal before and after rewinding the loop");
676 check(std::memcmp(ring_bytes, ring_bytes + 0x400, 0x400) == 0,
677 "Rewind decodes the first packet from fresh decoder state");
678#endif
679 check(run_blocks(1, 3, 2, 1) == 9 && ((words[1] >> 24) & 7u) == 0,
680 "Initial and loop subframe skips consume 3 blocks and clear the initial skip");
681 check(run_blocks(0, 2) == 8,
682 "A skip to the end of input 0 continues at input 1");
683 check(run_blocks(0, 1) == 8,
684 "An overshooting skip starts at packet 1 of input 1");
685#if defined(LEONIDA_HAVE_XMA2_DECODER)
686 check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400),
687 "Rust produces signal on both sides of the buffer switch");
688#endif
689
690 configure_voice(255, 3, 4, 7, 9);
691 check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK,
692 "Enable infinite loop with out-of-range ring indices");
693 for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1);
694 check((words[1] >> 31) == 0u && ((words[0] >> 27) & 0x1Fu) == 1u,
695 "Ring stops at the normalized read index");
696 check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK,
697 "Disable infinite loop after filling bounded ring");
698 check(((words[0] >> 12) & 0xFFu) == 255u, "Infinite loop does not consume its loop count");
699 check(std::all_of(ring_bytes + 0x400, ring_bytes + 0x1000,
700 [](uint8_t b) { return b == 0x55; }),
701 "Output never writes beyond the configured four-block ring");
702
703 words[0] = 3u << 22; // three ring blocks
704 words[9] = 2u;
705 const uint32_t advance_args[2] = {2u, UINT32_MAX};
706 check(fn_submit(x_acp, 18, 0xf5, 0xffffffffu, advance_args, 0) == S_OK && words[9] == 2u,
707 "ADVANCE_XMA_READ wraps at the ring size without overflowing");
708
709 auto wait_for_ring = [&]() {
710 for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1);
711 return (words[1] >> 31) == 0u;
712 };
713 const uint32_t refill_read_args[2] = {voice_index, 4};
714
715 configure_voice(0, 3, 4, 0, 0);
716 words[0] = 1u | (1u << 20) | (4u << 22);
717 write_xma_packet(packets, 3, 0);
718 check(fn_submit(x_acp, 5, 0xf6, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(),
719 "First packet fills the ring and leaves queued PCM");
720 TestShapeContexts source_only{};
721 source_only.numSrcContexts = 1;
722 check(alloc_ctx(&source_only) == S_OK && source_only.srcContextArray != nullptr,
723 "A non-XMA allocation can coexist with the active XMA table");
724 words[0].fetch_or(1u << 20);
725 check(fn_submit(x_acp, 5, 0xf7, 0xffffffffu, &voice_index, 0) == S_OK,
726 "Re-enable while refilling the current input");
727 int refills = 0;
728 for (int i = 0; i < 5; ++i) {
729 if (fn_submit(x_acp, 18, 0xf8, 0xffffffffu, refill_read_args, 0) != S_OK || !wait_for_ring()) break;
730 ++refills;
731 }
732 check(refills == 5 && (words[2] >> 31) == 0u && ((words[0] >> 20) & 3u) == 0u,
733 "Refill and repeated enable preserve all six frames and consume the reused input");
734 check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &voice_index, 0) == S_OK,
735 "Disable the single-buffer refill voice");
736
737 // The next same-stream packet is in the first input's refill, after a short second input.
738 write_xma_packet(packets, 1, 2);
739 write_xma_packet(packets + 0x1000, 2, 0);
740 write_xma_packet(packets + 0x1800, 1, 0);
741 configure_voice(0, 1, 4, 0, 0);
742 words[1] = (words[1] & ~0xFFFu) | 1u;
743 check(fn_submit(x_acp, 5, 0xfa, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(),
744 "Voice fills the ring before the skip crosses two buffers");
745 words[5] = in_apu + 0x1000u;
746 words[0] = (words[0] & ~0xFFFu) | 2u | (1u << 20);
747 check(fn_submit(x_acp, 18, 0xfb, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(),
748 "The same-stream packet fills the ring after two buffer crossings");
749 check(((words[0] >> 20) & 3u) == 0u && (words[4] >> 31) == 0u,
750 "A skip across both buffers lands on the last packet of the reloaded input");
751 check(fn_submit(x_acp, 7, 0xfc, 0xffffffffu, &voice_index, 0) == S_OK,
752 "Disable the two-buffer refill voice");
753
754 // Both sides were empty. When both are refilled, the title's first input wins.
755 write_xma_packet(packets, 1, 0);
756 configure_voice(0, 3, 4, 0, 0);
757 words[0] = 1u | (1u << 20) | (4u << 22);
758 const uint32_t voice_bit = 1u << voice_index;
759 check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring(),
760 "ENABLE_XMAS starts the selected voice and exhausts the first input");
761 write_xma_packet(packets, 2, 0);
762 write_xma_packet(packets + 0x800, 1, 0);
763 words[6] = in_apu + 0x800u;
764 words[1].fetch_or(1u);
765 words[0].fetch_or(3u << 20);
766 check(fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(),
767 "A double refill supplies the next PCM blocks");
768 check(((words[0] >> 20) & 3u) == 2u && (words[4] >> 31) == 1u,
769 "A double refill plays input 0 before input 1");
770#if defined(LEONIDA_HAVE_XMA2_DECODER)
771 check(has_signal(ring_bytes), "Rust decodes non-silent PCM after a double refill");
772#endif
773
774 check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK,
775 "Reset the voice before exhausting both inputs");
776 write_xma_packet(packets, 1, 0);
777 write_xma_packet(packets + 0x800, 1, 0);
778 configure_voice(0, 1, 8, 0, 0);
779 words[1] = (words[1] & ~0xFFFu) | 1u;
780 check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring() &&
781 ((words[0] >> 20) & 3u) == 0u,
782 "The voice exhausts input 0 and then input 1");
783 write_xma_packet(packets, 2, 0);
784 words[0].fetch_or(3u << 20);
785 const uint32_t full_ring[2] = {voice_index, 8};
786 check(fn_submit(x_acp, 18, 0, 0xffffffffu, full_ring, 0) == S_OK && wait_for_ring() &&
787 ((words[0] >> 20) & 3u) == 2u,
788 "A double refill plays input 0 first even after exhausting input 1");
789
790 // Reconfigure the still-enabled slot and verify that no queued PCM or old format survives.
791 bool reconfigured = true;
792 for (uint32_t rate = 0; rate < 4; ++rate) {
793 const bool stereo = (rate & 1u) == 0;
794 write_xma_packet(packets, 1, 0, rate, stereo);
795 words[0] = 1u | (1u << 20) | (16u << 22);
796 words[2] = 32u;
797 words[4] = 0u;
798 words[9] = 12u;
799 std::memset(out_va, 0, 0x1000);
800 // Enable applies the new format before making the output writable.
801 words[1] = ((rate | (stereo ? 4u : 0u)) << 27);
802 reconfigured &= fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK;
803 reconfigured &= fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK;
804 for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1);
805 reconfigured &= (words[2] >> 31) == 1u && ((words[0] >> 27) & 0x1Fu) == (stereo ? 8u : 4u);
806#if defined(LEONIDA_HAVE_XMA2_DECODER)
807 reconfigured &= has_signal(ring_bytes);
808#endif
809 }
810 check(reconfigured, "Re-enabled voices select mono or stereo PCM at all four sample rates");
811 check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK,
812 "DISABLE_XMAS stops the selected voice");
813
814 configure_voice(0, 3, 4, 0, 0);
815 write_xma_packet(packets, 1, 1);
816 fail_worker_allocation.store(true);
817 check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK,
818 "Enable a voice before an injected worker allocation failure");
819 for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1);
820 check(!fail_worker_allocation.exchange(false) && (words[2] >> 31) != 0u,
821 "Worker allocation failure surfaces an XMA error without terminating the process");
822 check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(),
823 "A voice can run again after a worker allocation failure");
824
825 check(release_ctx(x_acp) == S_OK, "Release SHAPE contexts through the opaque AcpHal handle");
826 check(fn_release(x_acp) == S_OK, "Release packet loop AcpHal succeeds");
827 free_mem(in_va);
828 free_mem(out_va);
829 check(release_ctx(&xma_ctx) == S_OK, "Release packet loop SHAPE contexts");
830 }
831
832 // 9. ENABLE_XMA racing SHAPE allocation and release, including concurrent releases.
833 {
834 using RaceConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t);
835 using RaceSubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t);
836 using RaceReleaseFn = HRESULT(__stdcall*)(void*);
837
838 void* race_acp = nullptr;
839 check(create(&race_acp) == S_OK && race_acp != nullptr, "AcpHalCreate for XMA race test");
840 auto race_vt = *static_cast<void* const* const*>(race_acp);
841 const auto race_connect = reinterpret_cast<RaceConnectFn>(race_vt[0]);
842 const auto race_submit = reinterpret_cast<RaceSubmitFn>(race_vt[2]);
843 const auto race_release = reinterpret_cast<RaceReleaseFn>(race_vt[5]);
844 check(race_connect(race_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA race test");
845
846 constexpr int kRaceIterations = 20000;
847 std::atomic<int> bind_failures{0};
848 std::thread enabler([&]() {
849 const uint32_t enable_arg = 1u;
850 for (int i = 0; i < kRaceIterations; ++i) {
851 race_submit(race_acp, 5, 0xe000u + static_cast<uint64_t>(i), 0xffffffffu,
852 &enable_arg, 0);
853 }
854 });
855 std::thread releaser([&]() {
856 for (int i = 0; i < kRaceIterations; ++i) {
857 if (release_ctx(nullptr) != S_OK) ++bind_failures;
858 }
859 });
860 for (int i = 0; i < kRaceIterations; ++i) {
861 TestShapeContexts race_ctx{};
862 race_ctx.numXmaContexts = 4;
863 if (alloc_ctx(&race_ctx) != S_OK) ++bind_failures;
864 if (release_ctx(&race_ctx) != S_OK) ++bind_failures;
865 }
866 enabler.join();
867 releaser.join();
868 check(bind_failures == 0, "20000 bind/release cycles race ENABLE_XMA and independent releases");
869 check(race_release(race_acp) == S_OK, "Release race AcpHal succeeds");
870 }
871
260 std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); 872 std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures);
261 return g_failures ? 1 : 0; 873 return g_failures ? 1 : 0;
262} 874}