upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/shims/acphal.cpp
diff options
context:
space:
mode:
authorandretuta <andreviniciusmerlia@gmail.com>2026-11-24 05:27:55 -0300
committerandretuta <andreviniciusmerlia@gmail.com>2026-11-24 05:27:55 -0300
commit0fe9c0bdfb844678209c0d0ffdd37d2533d1f57e (patch)
tree143420e46b24ebd381998ea651aa4a0a8b20d001 /runtime/shims/acphal.cpp
parente02ec36bf315de960a9db244e971bf00cfd66406 (diff)
acphal: recover SHAPE allocation and preserve XMA stream state
Diffstat (limited to 'runtime/shims/acphal.cpp')
-rw-r--r--runtime/shims/acphal.cpp189
1 files changed, 117 insertions, 72 deletions
diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp
index 05ceedd17..d273aaa85 100644
--- a/runtime/shims/acphal.cpp
+++ b/runtime/shims/acphal.cpp
@@ -31,6 +31,7 @@
31#include <map> 31#include <map>
32#include <memory> 32#include <memory>
33#include <mutex> 33#include <mutex>
34#include <new>
34#include <optional> 35#include <optional>
35#include <set> 36#include <set>
36#include <shared_mutex> 37#include <shared_mutex>
@@ -286,8 +287,17 @@ ApuRegion g_cached_heap;
286ApuRegion g_noncached_heap; 287ApuRegion g_noncached_heap;
287 288
288// Tracked SHAPE context arrays 289// Tracked SHAPE context arrays
290struct ShapeArrayFree {
291 void operator()(void* array) const noexcept { std::free(array); }
292};
293
294struct ShapeAllocation {
295 SHAPE_CONTEXTS* caller;
296 std::array<std::unique_ptr<void, ShapeArrayFree>, 6> arrays;
297};
298
289std::mutex g_shape_mutex; 299std::mutex g_shape_mutex;
290std::vector<void*> g_active_shape_arrays; 300std::vector<ShapeAllocation> g_shape_allocations;
291 301
292// Resolves a contiguous [apu, apu + len) byte range inside the APU heap. 302// Resolves a contiguous [apu, apu + len) byte range inside the APU heap.
293uint8_t* apu_span(uint32_t apu, std::size_t len) { 303uint8_t* apu_span(uint32_t apu, std::size_t len) {
@@ -391,8 +401,8 @@ struct XmaVoice {
391 std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder; 401 std::unique_ptr<LeonidaXma2Decoder, Xma2DecoderFree> decoder;
392#endif 402#endif
393 std::deque<int16_t> pcm; 403 std::deque<int16_t> pcm;
394 std::size_t skip = 0; // samples per channel to drop (start/loop subframe skip) 404 std::size_t loop_skip = 0; // samples per channel to drop after a rewind
395 std::optional<std::size_t> next_input_packet; 405 std::optional<uint32_t> exhausted_input;
396 bool ended = false; 406 bool ended = false;
397}; 407};
398 408
@@ -406,14 +416,14 @@ public:
406 ~XmaEngine() { unbind(); } 416 ~XmaEngine() { unbind(); }
407 417
408 void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) { 418 void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) {
419 // Construct with a size so MSVC's Debug iterator allocations can also fail
420 // through this call instead of the noexcept default constructor.
421 std::vector<std::unique_ptr<XmaVoiceSlot>> slots(count);
422 for (auto& slot : slots) slot = std::make_unique<XmaVoiceSlot>();
409 unbind(); 423 unbind();
410 std::unique_lock lock(table_mutex_); 424 std::unique_lock lock(table_mutex_);
411 array_ = array; 425 array_ = array;
412 voices_.clear(); 426 voices_.swap(slots);
413 voices_.reserve(count);
414 for (uint32_t i = 0; i < count; ++i) {
415 voices_.push_back(std::make_unique<XmaVoiceSlot>());
416 }
417 } 427 }
418 428
419 void unbind() { 429 void unbind() {
@@ -476,16 +486,15 @@ public:
476 486
477 { 487 {
478 std::lock_guard slot_lock(voices_[index]->mutex); 488 std::lock_guard slot_lock(voices_[index]->mutex);
479 const bool was_active = voices_[index]->voice.has_value(); 489 auto& voice = voices_[index]->voice;
480 // Clear error_status (26..30) and error flag (31). 490 // Clear error_status (26..30) and error flag (31).
481 ctx.set_field(2, 26, 6, 0); 491 ctx.set_field(2, 26, 6, 0);
482 492
483 XmaVoice voice; 493 if (!voice) {
484 voice.skip = static_cast<std::size_t>(ctx.field(1, 24, 3)) * kXmaSubframeSamples; 494 voice.emplace();
485 voices_[index]->voice.emplace(std::move(voice));
486 if (!was_active) {
487 active_count_.fetch_add(1, std::memory_order_relaxed); 495 active_count_.fetch_add(1, std::memory_order_relaxed);
488 } 496 }
497 voice->ended = false;
489 } 498 }
490 ensure_worker_and_wake(); 499 ensure_worker_and_wake();
491 } 500 }
@@ -566,19 +575,17 @@ private:
566 uint32_t current = ctx.field(4, 31, 1); 575 uint32_t current = ctx.field(4, 31, 1);
567 const uint32_t valid = ctx.field(0, 20, 2); 576 const uint32_t valid = ctx.field(0, 20, 2);
568 577
569 if (voice.next_input_packet || (valid & (1u << current)) == 0) { 578 if (valid == 0) {
570 const uint32_t other = 1u - current; 579 voice.ended = true;
571 if ((valid & (1u << other)) == 0) { 580 ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u);
572 voice.ended = true; 581 return !voice.pcm.empty();
573 ctx.set_field(2, 26, 5, kXmaErrorInputInvalid); 582 }
574 ctx.set_field(2, 31, 1, 1); 583 const uint32_t other = 1u - current;
575 return !voice.pcm.empty(); 584 const bool current_valid = (valid & (1u << current)) != 0;
576 } 585 const bool other_valid = (valid & (1u << other)) != 0;
586 if (!current_valid || (voice.exhausted_input == current && other_valid)) {
577 current = other; 587 current = other;
578 ctx.set_field(4, 31, 1, current); 588 ctx.set_field(4, 31, 1, current);
579 const auto next_bit = voice.next_input_packet.value_or(0) * kXmaPacketBits;
580 ctx.set_field(2, 0, 26, static_cast<uint32_t>(next_bit));
581 voice.next_input_packet.reset();
582 } 589 }
583 590
584 const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6); 591 const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6);
@@ -586,18 +593,25 @@ private:
586 const std::size_t packet = ctx.field(2, 0, 26) / kXmaPacketBits; 593 const std::size_t packet = ctx.field(2, 0, 26) / kXmaPacketBits;
587 const uint8_t* data = apu_span(address & ~0x7FFu, packets * kXmaPacketBytes); 594 const uint8_t* data = apu_span(address & ~0x7FFu, packets * kXmaPacketBytes);
588 if (!data || packet >= packets) { 595 if (!data || packet >= packets) {
589 ctx.set_field(0, 20 + current, 1, 0); 596 finish_input(ctx, voice, current, packet >= packets ? packet - packets : 0);
590 voice.next_input_packet = 0;
591 ctx.set_field(2, 0, 26, 0);
592 return true; 597 return true;
593 } 598 }
599 voice.exhausted_input.reset();
594 600
595 const uint8_t* packet_data = data + packet * kXmaPacketBytes; 601 const uint8_t* packet_data = data + packet * kXmaPacketBytes;
596 const uint8_t packet_skip = packet_data[3]; 602 const uint8_t packet_skip = packet_data[3];
597 std::vector<int16_t> pcm; 603 std::vector<int16_t> pcm;
598 decode_packet(ctx, voice, packet_data, pcm); 604 decode_packet(ctx, voice, packet_data, pcm);
599 const std::size_t skip_samples = std::min(voice.skip * channels, pcm.size()); 605 const std::size_t subframe_samples = kXmaSubframeSamples * channels;
600 voice.skip -= skip_samples / channels; 606 const std::size_t initial_skip = ctx.field(1, 24, 3);
607 const std::size_t skipped_subframes = std::min(initial_skip, pcm.size() / subframe_samples);
608 if (skipped_subframes != 0) {
609 ctx.set_field(1, 24, 3, static_cast<uint32_t>(initial_skip - skipped_subframes));
610 }
611 const std::size_t initial_samples = skipped_subframes * subframe_samples;
612 const std::size_t loop_samples = std::min(voice.loop_skip * channels, pcm.size() - initial_samples);
613 voice.loop_skip -= loop_samples / channels;
614 const std::size_t skip_samples = initial_samples + loop_samples;
601 voice.pcm.insert(voice.pcm.end(), pcm.begin() + static_cast<std::ptrdiff_t>(skip_samples), pcm.end()); 615 voice.pcm.insert(voice.pcm.end(), pcm.begin() + static_cast<std::ptrdiff_t>(skip_samples), pcm.end());
602 616
603 // XMA2 packet headers link packets from the same stream; 0xff ends the chain. 617 // XMA2 packet headers link packets from the same stream; 0xff ends the chain.
@@ -606,7 +620,7 @@ private:
606 const std::size_t loop_end = ctx.field(4, 0, 26); 620 const std::size_t loop_end = ctx.field(4, 0, 26);
607 if (loops > 0 && loop_end != 0 && packet == loop_end / kXmaPacketBits) { 621 if (loops > 0 && loop_end != 0 && packet == loop_end / kXmaPacketBits) {
608 next = ctx.field(3, 0, 26) / kXmaPacketBits; 622 next = ctx.field(3, 0, 26) / kXmaPacketBits;
609 voice.skip = static_cast<std::size_t>(ctx.field(1, 17, 3)) * kXmaSubframeSamples; 623 voice.loop_skip = static_cast<std::size_t>(ctx.field(1, 17, 3)) * kXmaSubframeSamples;
610#if defined(LEONIDA_HAVE_XMA2_DECODER) 624#if defined(LEONIDA_HAVE_XMA2_DECODER)
611 // A frame spilling out of the loop-end packet does not continue in the loop-start packet: 625 // A frame spilling out of the loop-end packet does not continue in the loop-start packet:
612 // start a fresh decoder there rather than decode the spliced bits. 626 // start a fresh decoder there rather than decode the spliced bits.
@@ -615,16 +629,24 @@ private:
615 if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u); 629 if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u);
616 } 630 }
617 if (next >= packets) { 631 if (next >= packets) {
618 ctx.set_field(0, 20 + current, 1, 0); 632 finish_input(ctx, voice, current, next - packets);
619 voice.next_input_packet = next - packets; 633 } else {
620 next = 0; 634 ctx.set_field(2, 0, 26, static_cast<uint32_t>(next * kXmaPacketBits));
621 } 635 }
622 ctx.set_field(2, 0, 26, static_cast<uint32_t>(next * kXmaPacketBits));
623 return true; 636 return true;
624 } 637 }
625 638
639 static void finish_input(XmaContextView ctx, XmaVoice& voice, uint32_t current,
640 std::size_t skip_packets) {
641 voice.exhausted_input = current;
642 // Publish the next offset before telling the title it can refill this input.
643 ctx.set_field(2, 0, 26, static_cast<uint32_t>(skip_packets * kXmaPacketBits));
644 ctx.set_field(0, 20 + current, 1, 0);
645 }
646
626 static void pump_voice(XmaContextView ctx, XmaVoice& voice) { 647 static void pump_voice(XmaContextView ctx, XmaVoice& voice) {
627 const uint32_t size = ctx.field(0, 22, 5); 648 const uint32_t size = ctx.field(0, 22, 5);
649 if (size == 0 || ctx.field(1, 31, 1) == 0) return;
628 auto* ring = apu_span(ctx.get(7), size * kXmaBlockBytes); 650 auto* ring = apu_span(ctx.get(7), size * kXmaBlockBytes);
629 if (!ring) return; 651 if (!ring) return;
630 652
@@ -918,58 +940,80 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) {
918 940
919 std::lock_guard lock(g_shape_mutex); 941 std::lock_guard lock(g_shape_mutex);
920 942
921 auto alloc_array = [](uint32_t count, size_t elem_size) -> void* { 943 ShapeAllocation pending{ctx, {}};
944 std::size_t array_index = 0;
945 auto alloc_array = [&](uint32_t count, size_t elem_size) -> void* {
922 if (count == 0) return nullptr; 946 if (count == 0) return nullptr;
923 void* ptr = std::calloc(count, elem_size); 947 void* ptr = std::calloc(count, elem_size);
924 if (ptr) g_active_shape_arrays.push_back(ptr); 948 if (!ptr) throw std::bad_alloc();
949 pending.arrays[array_index++].reset(ptr);
925 return ptr; 950 return ptr;
926 }; 951 };
927 952
928 ctx->srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>( 953 SHAPE_CONTEXTS result{};
929 alloc_array(ctx->numSrcContexts, sizeof(SHAPE_SRC_CONTEXT))); 954 result.numSrcContexts = ctx->numSrcContexts;
930 ctx->eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>( 955 result.numEqCompContexts = ctx->numEqCompContexts;
931 alloc_array(ctx->numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT))); 956 result.numFiltVolContexts = ctx->numFiltVolContexts;
932 ctx->filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>( 957 result.numDmaContexts = ctx->numDmaContexts;
933 alloc_array(ctx->numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT))); 958 result.numXmaContexts = ctx->numXmaContexts;
934 ctx->dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>( 959 result.numPcmContexts = ctx->numPcmContexts;
935 alloc_array(ctx->numDmaContexts, sizeof(SHAPE_DMA_CONTEXT))); 960 try {
936 ctx->xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>( 961 result.srcContextArray = static_cast<SHAPE_SRC_CONTEXT*>(
937 alloc_array(ctx->numXmaContexts, sizeof(SHAPE_XMA_CONTEXT))); 962 alloc_array(result.numSrcContexts, sizeof(SHAPE_SRC_CONTEXT)));
938 ctx->pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>( 963 result.eqCompContextArray = static_cast<SHAPE_EQCOMP_CONTEXT*>(
939 alloc_array(ctx->numPcmContexts, sizeof(SHAPE_PCM_CONTEXT))); 964 alloc_array(result.numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT)));
940 965 result.filtVolContextArray = static_cast<SHAPE_FILTVOL_CONTEXT*>(
941 // On PC there is no physical APU address translation for host context arrays; 966 alloc_array(result.numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT)));
942 // assign unique synthetic addresses from the APU base. 967 result.dmaContextArray = static_cast<SHAPE_DMA_CONTEXT*>(
943 ctx->apuSrcContextArray = {ctx->srcContextArray ? kApuBaseAddress : 0}; 968 alloc_array(result.numDmaContexts, sizeof(SHAPE_DMA_CONTEXT)));
944 ctx->apuEqCompContextArray = {ctx->eqCompContextArray ? kApuBaseAddress + 0x1000 : 0}; 969 result.xmaContextArray = static_cast<SHAPE_XMA_CONTEXT*>(
945 ctx->apuFiltVolContextArray = {ctx->filtVolContextArray ? kApuBaseAddress + 0x2000 : 0}; 970 alloc_array(result.numXmaContexts, sizeof(SHAPE_XMA_CONTEXT)));
946 ctx->apuDmaContextArray = {ctx->dmaContextArray ? kApuBaseAddress + 0x3000 : 0}; 971 result.pcmContextArray = static_cast<SHAPE_PCM_CONTEXT*>(
947 ctx->apuXmaContextArray = {ctx->xmaContextArray ? kApuBaseAddress + 0x4000 : 0}; 972 alloc_array(result.numPcmContexts, sizeof(SHAPE_PCM_CONTEXT)));
948 ctx->apuPcmContextArray = {ctx->pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; 973
949 974 // Assign synthetic APU addresses to the host-side context arrays.
950 g_xma_engine.bind(ctx->xmaContextArray, ctx->numXmaContexts); 975 result.apuSrcContextArray = {result.srcContextArray ? kApuBaseAddress : 0};
951 976 result.apuEqCompContextArray = {result.eqCompContextArray ? kApuBaseAddress + 0x1000 : 0};
952 trace_call("AcpHalAllocateShapeContexts", 977 result.apuFiltVolContextArray = {result.filtVolContextArray ? kApuBaseAddress + 0x2000 : 0};
953 ",\"src\":" + std::to_string(ctx->numSrcContexts) + 978 result.apuDmaContextArray = {result.dmaContextArray ? kApuBaseAddress + 0x3000 : 0};
954 ",\"xma\":" + std::to_string(ctx->numXmaContexts) + 979 result.apuXmaContextArray = {result.xmaContextArray ? kApuBaseAddress + 0x4000 : 0};
955 ",\"pcm\":" + std::to_string(ctx->numPcmContexts)); 980 result.apuPcmContextArray = {result.pcmContextArray ? kApuBaseAddress + 0x5000 : 0};
981
982 g_shape_allocations.reserve(g_shape_allocations.size() + 1);
983 g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts);
984 } catch (const std::bad_alloc&) {
985 return E_OUTOFMEMORY;
986 }
987
988 // Both the backing arrays and the engine's slots are now fully allocated.
989 g_shape_allocations.push_back(std::move(pending));
990 *ctx = result;
991 if (rt::startup_trace::enabled()) {
992 try {
993 trace_call("AcpHalAllocateShapeContexts",
994 ",\"src\":" + std::to_string(result.numSrcContexts) +
995 ",\"xma\":" + std::to_string(result.numXmaContexts) +
996 ",\"pcm\":" + std::to_string(result.numPcmContexts));
997 } catch (const std::bad_alloc&) {
998 // The allocation succeeded. A missing diagnostic does not invalidate it.
999 }
1000 }
956 return S_OK; 1001 return S_OK;
957} 1002}
958 1003
959// ---- AcpHalReleaseShapeContexts ---- 1004// ---- AcpHalReleaseShapeContexts ----
960 1005
961HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { 1006HRESULT __stdcall AcpHalReleaseShapeContexts(void* argument = nullptr) {
962 std::lock_guard lock(g_shape_mutex); 1007 std::lock_guard lock(g_shape_mutex);
963 // Stop and detach the XMA worker before freeing backing arrays. 1008 // Stop and detach the XMA worker before freeing backing arrays.
964 g_xma_engine.unbind(); 1009 g_xma_engine.unbind();
965 1010
966 // Free all recorded context allocations 1011 // Retail passes its IAcpHal handle. Only a pointer previously supplied to
967 for (void* p : g_active_shape_arrays) { 1012 // AllocateShapeContexts can safely be treated as a SHAPE_CONTEXTS output.
968 if (p) std::free(p); 1013 const auto allocation = std::find_if(g_shape_allocations.begin(), g_shape_allocations.end(),
969 } 1014 [argument](const ShapeAllocation& entry) { return entry.caller == argument; });
970 g_active_shape_arrays.clear(); 1015 if (allocation != g_shape_allocations.end()) {
971 1016 auto* ctx = allocation->caller;
972 if (ctx) {
973 ctx->srcContextArray = nullptr; 1017 ctx->srcContextArray = nullptr;
974 ctx->eqCompContextArray = nullptr; 1018 ctx->eqCompContextArray = nullptr;
975 ctx->filtVolContextArray = nullptr; 1019 ctx->filtVolContextArray = nullptr;
@@ -977,6 +1021,7 @@ HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) {
977 ctx->xmaContextArray = nullptr; 1021 ctx->xmaContextArray = nullptr;
978 ctx->pcmContextArray = nullptr; 1022 ctx->pcmContextArray = nullptr;
979 } 1023 }
1024 g_shape_allocations.clear();
980 1025
981 trace_call("AcpHalReleaseShapeContexts", ""); 1026 trace_call("AcpHalReleaseShapeContexts", "");
982 return S_OK; 1027 return S_OK;