upleb.uk

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

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorandretuta <andreviniciusmerlia@gmail.com>2026-11-24 06:47:57 -0300
committerandretuta <andreviniciusmerlia@gmail.com>2026-11-24 06:47:57 -0300
commit713eec5031a6a7d1b1626f090d742531007b28e5 (patch)
tree7ce295f22d11d9cf78471e8d1cc93be3cf955054
parent4e9407a409641b644393a66b41d35e431f1c5ddb (diff)
acphal: stabilize APU mappings and reuse XMA PCM storagefeat/acphal-xma2-decoder
-rw-r--r--runtime/CMakeLists.txt1
-rw-r--r--runtime/shims/acphal.cpp61
-rw-r--r--runtime/test/acphal_test.cpp53
3 files changed, 88 insertions, 27 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 98b10ed2a..e3d2b8eba 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -1205,6 +1205,7 @@ if(BUILD_TESTING)
1205 endif() 1205 endif()
1206 if(WIN32 AND TARGET acphal_test) 1206 if(WIN32 AND TARGET acphal_test)
1207 add_test(NAME acphal COMMAND acphal_test) 1207 add_test(NAME acphal COMMAND acphal_test)
1208 add_test(NAME acphal_noncached_only COMMAND acphal_test --noncached-only)
1208 endif() 1209 endif()
1209 if(WIN32 AND TARGET cpu_emulation_test) 1210 if(WIN32 AND TARGET cpu_emulation_test)
1210 add_test(NAME cpu_emulation COMMAND cpu_emulation_test) 1211 add_test(NAME cpu_emulation COMMAND cpu_emulation_test)
diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp
index 4b516cf8f..f1c33ddd9 100644
--- a/runtime/shims/acphal.cpp
+++ b/runtime/shims/acphal.cpp
@@ -390,25 +390,28 @@ struct XmaContextView {
390 return (get(index) >> shift) & mask; 390 return (get(index) >> shift) & mask;
391 } 391 }
392 392
393 void set_field(std::size_t index, uint32_t shift, uint32_t bits, uint32_t value) const { 393 uint32_t set_field(std::size_t index, uint32_t shift, uint32_t bits, uint32_t value) const {
394 const uint32_t raw_mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u); 394 const uint32_t raw_mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u);
395 const uint32_t mask = raw_mask << shift; 395 const uint32_t mask = raw_mask << shift;
396 const uint32_t field_value = (value << shift) & mask; 396 const uint32_t field_value = (value << shift) & mask;
397 std::atomic_ref word(words[index]); 397 std::atomic_ref word(words[index]);
398 uint32_t previous = word.load(); 398 uint32_t previous = word.load();
399 while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {} 399 while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {}
400 return previous;
400 } 401 }
401 402
402}; 403};
403 404
404struct XmaVoice { 405struct XmaVoice {
405 explicit XmaVoice(uint32_t format_bits) : format(format_bits) {} 406 explicit XmaVoice(uint32_t format_bits) : pcm(0), format(format_bits) {}
406 std::size_t channels() const { return 1u + (format >> 2); } 407 std::size_t channels() const { return 1u + (format >> 2); }
408 std::size_t queued_samples() const { return pcm.size() - pcm_read; }
407 409
408#if defined(LEONIDA_HAVE_XMA2_DECODER) 410#if defined(LEONIDA_HAVE_XMA2_DECODER)
409 std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder; 411 std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder;
410#endif 412#endif
411 std::deque<int16_t> pcm; 413 std::vector<int16_t> pcm;
414 std::size_t pcm_read = 0;
412 std::size_t loop_skip = 0; // samples per channel to drop after a rewind 415 std::size_t loop_skip = 0; // samples per channel to drop after a rewind
413 uint32_t format; // SHAPE word 1 bits 27..29, rate and channel layout 416 uint32_t format; // SHAPE word 1 bits 27..29, rate and channel layout
414 bool ended = false; 417 bool ended = false;
@@ -503,6 +506,7 @@ public:
503 active_count_.fetch_add(1, std::memory_order_relaxed); 506 active_count_.fetch_add(1, std::memory_order_relaxed);
504 } else if (voice->format != format) { 507 } else if (voice->format != format) {
505 voice->pcm.clear(); 508 voice->pcm.clear();
509 voice->pcm_read = 0;
506 voice->loop_skip = 0; 510 voice->loop_skip = 0;
507 voice->format = format; 511 voice->format = format;
508#if defined(LEONIDA_HAVE_XMA2_DECODER) 512#if defined(LEONIDA_HAVE_XMA2_DECODER)
@@ -550,10 +554,9 @@ private:
550 return XmaContextView{array_[index].words}; 554 return XmaContextView{array_[index].words};
551 } 555 }
552 556
553 // Fills `pcm` (interleaved s16) for one 2048-byte packet. Without the Rust decoder, or when it 557 // Appends interleaved s16 for one 2048-byte packet. Without the Rust decoder, or when it
554 // fails, the packet becomes silence for its frame count (header bits 26..31) so timing holds. 558 // fails, the packet becomes silence for its frame count (header bits 26..31) so timing holds.
555 static void decode_packet(XmaVoice& voice, const uint8_t* bytes, 559 static void decode_packet(XmaVoice& voice, const uint8_t* bytes) {
556 std::vector<int16_t>& pcm) {
557 const std::size_t channels = voice.channels(); 560 const std::size_t channels = voice.channels();
558#if defined(LEONIDA_HAVE_XMA2_DECODER) 561#if defined(LEONIDA_HAVE_XMA2_DECODER)
559 if (!voice.decoder) { 562 if (!voice.decoder) {
@@ -569,13 +572,13 @@ private:
569 const std::unique_ptr<LeonidaXma2PcmBlock, Xma2PcmFree> block(raw); 572 const std::unique_ptr<LeonidaXma2PcmBlock, Xma2PcmFree> block(raw);
570 const int16_t* samples = leonida_xma2_pcm_data(block.get()); 573 const int16_t* samples = leonida_xma2_pcm_data(block.get());
571 const std::size_t count = leonida_xma2_pcm_sample_count(block.get()); 574 const std::size_t count = leonida_xma2_pcm_sample_count(block.get());
572 if (count != 0) pcm.assign(samples, samples + count); 575 if (count != 0) voice.pcm.insert(voice.pcm.end(), samples, samples + count);
573 return; 576 return;
574 } 577 }
575 voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence. 578 voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence.
576 } 579 }
577#endif 580#endif
578 pcm.assign(static_cast<std::size_t>(bytes[0] >> 2) * kXmaFrameSamples * channels, 0); 581 voice.pcm.resize(voice.pcm.size() + static_cast<std::size_t>(bytes[0] >> 2) * kXmaFrameSamples * channels);
579 } 582 }
580 583
581 // Decodes the packet at the read offset of the current input buffer and queues its PCM. 584 // Decodes the packet at the read offset of the current input buffer and queues its PCM.
@@ -591,7 +594,7 @@ private:
591 if (valid == 0) { 594 if (valid == 0) {
592 voice.ended = true; 595 voice.ended = true;
593 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u); 596 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
594 return !voice.pcm.empty(); 597 return voice.queued_samples() != 0;
595 } 598 }
596 if ((valid & (1u << current)) == 0) { 599 if ((valid & (1u << current)) == 0) {
597 current ^= 1u; 600 current ^= 1u;
@@ -609,20 +612,28 @@ private:
609 612
610 const uint8_t* packet_data = data + packet * kXmaPacketBytes; 613 const uint8_t* packet_data = data + packet * kXmaPacketBytes;
611 const uint8_t packet_skip = packet_data[3]; 614 const uint8_t packet_skip = packet_data[3];
612 // The sized constructor can propagate even an MSVC Debug allocation failure. 615 // Decoding is only requested when less than a ring block remains. Keep that
613 std::vector<int16_t> pcm(0); 616 // tail and reuse the packet storage as the voice consumes subsequent packets.
614 decode_packet(voice, packet_data, pcm); 617 voice.pcm.erase(voice.pcm.begin(), voice.pcm.begin() + static_cast<std::ptrdiff_t>(voice.pcm_read));
618 voice.pcm_read = 0;
619 const std::size_t packet_start = voice.pcm.size();
620 decode_packet(voice, packet_data);
621 const std::size_t packet_samples = voice.pcm.size() - packet_start;
615 const std::size_t subframe_samples = kXmaSubframeSamples * channels; 622 const std::size_t subframe_samples = kXmaSubframeSamples * channels;
616 const std::size_t initial_skip = ctx.field(1, 24, 3); 623 const std::size_t initial_skip = ctx.field(1, 24, 3);
617 const std::size_t skipped_subframes = std::min(initial_skip, pcm.size() / subframe_samples); 624 const std::size_t skipped_subframes = std::min(initial_skip, packet_samples / subframe_samples);
625 const std::size_t initial_samples = skipped_subframes * subframe_samples;
626 const std::size_t loop_samples = std::min(voice.loop_skip * channels, packet_samples - initial_samples);
627 const std::size_t skip_samples = initial_samples + loop_samples;
628 if (skip_samples != 0) {
629 const auto first = voice.pcm.begin() + static_cast<std::ptrdiff_t>(packet_start);
630 voice.pcm.erase(first, first + static_cast<std::ptrdiff_t>(skip_samples));
631 }
632 // Update the context only after the PCM append succeeds.
618 if (skipped_subframes != 0) { 633 if (skipped_subframes != 0) {
619 ctx.set_field(1, 24, 3, static_cast<uint32_t>(initial_skip - skipped_subframes)); 634 ctx.set_field(1, 24, 3, static_cast<uint32_t>(initial_skip - skipped_subframes));
620 } 635 }
621 const std::size_t initial_samples = skipped_subframes * subframe_samples;
622 const std::size_t loop_samples = std::min(voice.loop_skip * channels, pcm.size() - initial_samples);
623 voice.loop_skip -= loop_samples / channels; 636 voice.loop_skip -= loop_samples / channels;
624 const std::size_t skip_samples = initial_samples + loop_samples;
625 voice.pcm.insert(voice.pcm.end(), pcm.begin() + static_cast<std::ptrdiff_t>(skip_samples), pcm.end());
626 637
627 // XMA2 packet headers link packets from the same stream; 0xff ends the chain. 638 // XMA2 packet headers link packets from the same stream; 0xff ends the chain.
628 std::size_t next = packet_skip == 0xFFu ? packets : packet + 1 + packet_skip; 639 std::size_t next = packet_skip == 0xFFu ? packets : packet + 1 + packet_skip;
@@ -651,8 +662,10 @@ private:
651 // Publish the next offset before telling the title it can refill this input. 662 // Publish the next offset before telling the title it can refill this input.
652 ctx.set_field(2, 0, 26, static_cast<uint32_t>(skip_packets * kXmaPacketBits)); 663 ctx.set_field(2, 0, 26, static_cast<uint32_t>(skip_packets * kXmaPacketBits));
653 const uint32_t other = 1u - current; 664 const uint32_t other = 1u - current;
654 if (ctx.field(0, 20 + other, 1) != 0) ctx.set_field(4, 31, 1, other); 665 const uint32_t retired = ctx.set_field(0, 20 + current, 1, 0);
655 ctx.set_field(0, 20 + current, 1, 0); 666 // Take the other input if it was queued at retirement. Otherwise a double
667 // refill of the empty pair starts at input 0. A lone input can still run.
668 ctx.set_field(4, 31, 1, (retired & (1u << (20 + other))) != 0 ? other : 0u);
656 } 669 }
657 670
658 static void pump_voice(XmaContextView ctx, XmaVoice& voice) { 671 static void pump_voice(XmaContextView ctx, XmaVoice& voice) {
@@ -663,19 +676,18 @@ private:
663 676
664 for (uint32_t blocks = 0; blocks < size && ctx.field(1, 31, 1) == 1; ++blocks) { 677 for (uint32_t blocks = 0; blocks < size && ctx.field(1, 31, 1) == 1; ++blocks) {
665 int decode_guard = 0; 678 int decode_guard = 0;
666 while (voice.pcm.size() < kXmaSamplesPerBlock && decode_guard++ < 16) { 679 while (voice.queued_samples() < kXmaSamplesPerBlock && decode_guard++ < 16) {
667 if (!decode_one_packet(ctx, voice)) break; 680 if (!decode_one_packet(ctx, voice)) break;
668 } 681 }
669 if (voice.pcm.empty()) return; 682 if (voice.queued_samples() == 0) return;
670 683
671 const uint32_t write = ctx.field(0, 27, 5) % size; 684 const uint32_t write = ctx.field(0, 27, 5) % size;
672 uint8_t* out = ring + write * kXmaBlockBytes; 685 uint8_t* out = ring + write * kXmaBlockBytes;
673 686
674 for (std::size_t i = 0; i < kXmaSamplesPerBlock; ++i) { 687 for (std::size_t i = 0; i < kXmaSamplesPerBlock; ++i) {
675 int16_t sample = 0; 688 int16_t sample = 0;
676 if (!voice.pcm.empty()) { 689 if (voice.pcm_read != voice.pcm.size()) {
677 sample = voice.pcm.front(); 690 sample = voice.pcm[voice.pcm_read++];
678 voice.pcm.pop_front();
679 } 691 }
680 const uint16_t raw = static_cast<uint16_t>(sample); 692 const uint16_t raw = static_cast<uint16_t>(sample);
681 out[2 * i] = static_cast<uint8_t>(raw & 0xFFu); 693 out[2 * i] = static_cast<uint8_t>(raw & 0xFFu);
@@ -1111,6 +1123,7 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress,
1111 1123
1112 if (!target->base) { 1124 if (!target->base) {
1113 if (!prefer_noncached) { 1125 if (!prefer_noncached) {
1126 if (g_apu_heap_created) return E_OUTOFMEMORY;
1114 // Lazy default cached heap if ApuCreateHeap wasn't called yet 1127 // Lazy default cached heap if ApuCreateHeap wasn't called yet
1115 constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024; 1128 constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024;
1116 target->base = VirtualAlloc(nullptr, kDefaultHeapSize, 1129 target->base = VirtualAlloc(nullptr, kDefaultHeapSize,
diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp
index 3ef8df4cd..be2c6f1e1 100644
--- a/runtime/test/acphal_test.cpp
+++ b/runtime/test/acphal_test.cpp
@@ -22,6 +22,8 @@
22// Fail only the calling test thread's designated allocation. 22// Fail only the calling test thread's designated allocation.
23static thread_local int allocations_before_failure = -1; 23static thread_local int allocations_before_failure = -1;
24static std::atomic<bool> fail_worker_allocation{false}; 24static std::atomic<bool> fail_worker_allocation{false};
25static std::atomic<bool> count_worker_allocations{false};
26static std::atomic<unsigned> worker_allocations{0};
25static DWORD test_thread_id; 27static DWORD test_thread_id;
26void* operator new(std::size_t size) { 28void* operator new(std::size_t size) {
27 if (allocations_before_failure == 0) { 29 if (allocations_before_failure == 0) {
@@ -32,6 +34,9 @@ void* operator new(std::size_t size) {
32 fail_worker_allocation.exchange(false)) { 34 fail_worker_allocation.exchange(false)) {
33 throw std::bad_alloc(); 35 throw std::bad_alloc();
34 } 36 }
37 if (count_worker_allocations.load() && GetCurrentThreadId() != test_thread_id) {
38 worker_allocations.fetch_add(1, std::memory_order_relaxed);
39 }
35 if (allocations_before_failure > 0) --allocations_before_failure; 40 if (allocations_before_failure > 0) --allocations_before_failure;
36 if (void* memory = std::malloc(size ? size : 1)) return memory; 41 if (void* memory = std::malloc(size ? size : 1)) return memory;
37 throw std::bad_alloc(); 42 throw std::bad_alloc();
@@ -145,7 +150,7 @@ void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip,
145 150
146} // namespace 151} // namespace
147 152
148int main() { 153int main(int argc, char** argv) {
149 std::setvbuf(stdout, nullptr, _IONBF, 0); 154 std::setvbuf(stdout, nullptr, _IONBF, 0);
150 test_thread_id = GetCurrentThreadId(); 155 test_thread_id = GetCurrentThreadId();
151 std::printf("acphal_test: registered acphal.dll shim verification\n"); 156 std::printf("acphal_test: registered acphal.dll shim verification\n");
@@ -186,6 +191,25 @@ int main() {
186 return 1; 191 return 1;
187 } 192 }
188 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
189 // 1. AcpHalCreate 213 // 1. AcpHalCreate
190 void* acp = nullptr; 214 void* acp = nullptr;
191 check(create(&acp) == S_OK && acp != nullptr, 215 check(create(&acp) == S_OK && acp != nullptr,
@@ -500,6 +524,8 @@ int main() {
500 524
501 // ENABLE_XMA (cmd 5) on voice 1. 525 // ENABLE_XMA (cmd 5) on voice 1.
502 const uint32_t enable_arg = 1u; 526 const uint32_t enable_arg = 1u;
527 worker_allocations.store(0);
528 count_worker_allocations.store(true);
503 check(fn_submit(x_acp, 5, 0xf1, 0xffffffffu, &enable_arg, 0) == S_OK, 529 check(fn_submit(x_acp, 5, 0xf1, 0xffffffffu, &enable_arg, 0) == S_OK,
504 "ENABLE_XMA voice 1 succeeds"); 530 "ENABLE_XMA voice 1 succeeds");
505 531
@@ -544,6 +570,11 @@ int main() {
544 } 570 }
545 check(advanced, "ADVANCE_XMA_READ succeeds"); 571 check(advanced, "ADVANCE_XMA_READ succeeds");
546 check(written_blocks == 24, "Six frames write exactly 24 blocks before input exhaustion"); 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");
547 check(((words[0] >> 20) & 3u) == 0u, "XMA input buffer valid bits cleared on exhaustion"); 578 check(((words[0] >> 20) & 3u) == 0u, "XMA input buffer valid bits cleared on exhaustion");
548 check(((words[2] >> 31) & 1u) == 1u, "XMA error flag set on exhaustion"); 579 check(((words[2] >> 31) & 1u) == 1u, "XMA error flag set on exhaustion");
549 check(((words[2] >> 26) & 0x1Fu) == 4u, "XMA error status is INPUT_INVALID (4)"); 580 check(((words[2] >> 26) & 0x1Fu) == 4u, "XMA error status is INPUT_INVALID (4)");
@@ -647,9 +678,9 @@ int main() {
647#endif 678#endif
648 check(run_blocks(1, 3, 2, 1) == 9 && ((words[1] >> 24) & 7u) == 0, 679 check(run_blocks(1, 3, 2, 1) == 9 && ((words[1] >> 24) & 7u) == 0,
649 "Initial and loop subframe skips consume 3 blocks and clear the initial skip"); 680 "Initial and loop subframe skips consume 3 blocks and clear the initial skip");
650 check(run_blocks(0, 2) == 8 && (words[4] >> 31) == 1u, 681 check(run_blocks(0, 2) == 8,
651 "A skip to the end of input 0 continues at input 1"); 682 "A skip to the end of input 0 continues at input 1");
652 check(run_blocks(0, 1) == 8 && (words[4] >> 31) == 1u, 683 check(run_blocks(0, 1) == 8,
653 "An overshooting skip starts at packet 1 of input 1"); 684 "An overshooting skip starts at packet 1 of input 1");
654#if defined(LEONIDA_HAVE_XMA2_DECODER) 685#if defined(LEONIDA_HAVE_XMA2_DECODER)
655 check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400), 686 check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400),
@@ -740,6 +771,22 @@ int main() {
740 check(has_signal(ring_bytes), "Rust decodes non-silent PCM after a double refill"); 771 check(has_signal(ring_bytes), "Rust decodes non-silent PCM after a double refill");
741#endif 772#endif
742 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
743 // Reconfigure the still-enabled slot and verify that no queued PCM or old format survives. 790 // Reconfigure the still-enabled slot and verify that no queued PCM or old format survives.
744 bool reconfigured = true; 791 bool reconfigured = true;
745 for (uint32_t rate = 0; rate < 4; ++rate) { 792 for (uint32_t rate = 0; rate < 4; ++rate) {