From cfcedb58e2802c5cd38afd1cbde877ae9d71c2a5 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 03:53:37 -0300 Subject: acphal: decode XMA contexts with runtime/xma_decoder when cargo is available Replace the hand-written C++ XMA2/WMA Pro decoder with the Rust decoder already on main. runtime/CMakeLists.txt builds it at configure time when cargo is on PATH and links it into gta6rt and acphal_test (LEONIDA_HAVE_XMA2_DECODER); without cargo, if that build fails, or with the cl.exe fallback, XMA voices output silence for each packet's frame count. The ring engine decodes whole 2048-byte packets: the read offset and the loop points are used per packet, so a loop plays its end packet in full and restarts with a fresh decoder at the packet holding the loop start. The C ABI gains leonida_xma2_decoder_create_hardware (no first-frame drop, no 64-sample start skip), since the context carries its own skip. Tested: acphal_test 129 checks (silence) and 125 checks (Rust decoder, gnullvm build), 0 failures, 3 runs each, clang 23 / mingw x64; cargo fmt and cargo test (gnullvm); pytest build/docs suites 204 passed. Co-Authored-By: Claude Opus 5.5 --- runtime/xma_decoder/src/lib.rs | 44 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) (limited to 'runtime/xma_decoder/src') diff --git a/runtime/xma_decoder/src/lib.rs b/runtime/xma_decoder/src/lib.rs index 1b435a0ce..cda2721fb 100644 --- a/runtime/xma_decoder/src/lib.rs +++ b/runtime/xma_decoder/src/lib.rs @@ -58,6 +58,28 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create( sample_rate: u32, channels: u32, out_decoder: *mut *mut LeonidaXma2Decoder, +) -> i32 { + unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new) } +} + +/// Like `leonida_xma2_decoder_create`, but decodes like the console's XMA hardware: the first +/// frame is kept and there is no 64-sample start skip; the caller applies the context's skip. +/// # Safety +/// Same as `leonida_xma2_decoder_create`. +#[no_mangle] +pub unsafe extern "C" fn leonida_xma2_decoder_create_hardware( + sample_rate: u32, + channels: u32, + out_decoder: *mut *mut LeonidaXma2Decoder, +) -> i32 { + unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new_hardware) } +} + +unsafe fn create_with( + sample_rate: u32, + channels: u32, + out_decoder: *mut *mut LeonidaXma2Decoder, + make: impl FnOnce(u32, usize) -> Result, ) -> i32 { if out_decoder.is_null() { return LEONIDA_XMA2_INVALID_ARGUMENT; @@ -68,8 +90,8 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create( } match catch_unwind(AssertUnwindSafe(|| { - let stream = Xma2Stream::new(sample_rate, channels as usize) - .map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?; + let stream = + make(sample_rate, channels as usize).map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?; try_new_handle(LeonidaXma2Decoder { stream: Mutex::new(stream), channels: channels as usize, @@ -232,6 +254,24 @@ mod tests { unsafe { leonida_xma2_decoder_destroy(decoder) }; } + #[test] + fn create_hardware_accepts_stereo_and_rejects_three_channels() { + let mut decoder = ptr::null_mut(); + assert_eq!( + unsafe { leonida_xma2_decoder_create_hardware(48_000, 2, &mut decoder) }, + LEONIDA_XMA2_OK + ); + assert!(!decoder.is_null()); + unsafe { leonida_xma2_decoder_destroy(decoder) }; + + let mut decoder = ptr::dangling_mut(); + assert_eq!( + unsafe { leonida_xma2_decoder_create_hardware(48_000, 3, &mut decoder) }, + LEONIDA_XMA2_INVALID_FORMAT + ); + assert!(decoder.is_null()); + } + #[test] fn pcm_handle_allocation_failure_clears_output_and_allows_retry() { let mut decoder = ptr::null_mut(); -- cgit v1.2.3 From 0fe9c0bdfb844678209c0d0ffdd37d2533d1f57e Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 05:27:55 -0300 Subject: acphal: recover SHAPE allocation and preserve XMA stream state --- .github/workflows/runtime.yml | 1 + runtime/CMakeLists.txt | 4 + runtime/shims/acphal.cpp | 189 +++++++++++++++++----------- runtime/test/acphal_test.cpp | 199 ++++++++++++++++++++---------- runtime/xma_decoder/README.md | 1 + runtime/xma_decoder/src/lib.rs | 7 +- runtime/xma_decoder/tests/ffi_contract.rs | 22 ++++ 7 files changed, 283 insertions(+), 140 deletions(-) (limited to 'runtime/xma_decoder/src') diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index cafdf469f..de01c6397 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -243,6 +243,7 @@ jobs: -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLEONIDA_D3D12_SHIM_TESTS=ON -DLEONIDA_REQUIRE_VULKAN=ON + -DLEONIDA_REQUIRE_XMA2_DECODER=ON -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_POLICY_DEFAULT_CMP0141=NEW -DCMAKE_MSVC_DEBUG_INFORMATION_FORMAT=Embedded diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 6b1b4af16..98b10ed2a 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -108,6 +108,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) # Rust XMA2 decoder (runtime/xma_decoder), built at configure time when cargo is on PATH. # Without it (or if that build fails) the runtime still builds and XMA voices output silence. + option(LEONIDA_REQUIRE_XMA2_DECODER "Fail configure if the Rust XMA2 decoder is unavailable" OFF) find_program(LEONIDA_CARGO cargo) if(LEONIDA_CARGO) # Cargo's host (or configured default target) can differ from the runtime's MSVC ABI. @@ -139,6 +140,9 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) else() message(STATUS "cargo not found: runtime/xma_decoder not built, XMA voices will be silent") endif() + if(LEONIDA_REQUIRE_XMA2_DECODER AND NOT TARGET leonida_xma2_decoder) + message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable") + endif() add_executable(gta6rt src/main.cpp 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 @@ #include #include #include +#include #include #include #include @@ -286,8 +287,17 @@ ApuRegion g_cached_heap; ApuRegion g_noncached_heap; // Tracked SHAPE context arrays +struct ShapeArrayFree { + void operator()(void* array) const noexcept { std::free(array); } +}; + +struct ShapeAllocation { + SHAPE_CONTEXTS* caller; + std::array, 6> arrays; +}; + std::mutex g_shape_mutex; -std::vector g_active_shape_arrays; +std::vector g_shape_allocations; // Resolves a contiguous [apu, apu + len) byte range inside the APU heap. uint8_t* apu_span(uint32_t apu, std::size_t len) { @@ -391,8 +401,8 @@ struct XmaVoice { std::unique_ptr decoder; #endif std::deque pcm; - std::size_t skip = 0; // samples per channel to drop (start/loop subframe skip) - std::optional next_input_packet; + std::size_t loop_skip = 0; // samples per channel to drop after a rewind + std::optional exhausted_input; bool ended = false; }; @@ -406,14 +416,14 @@ public: ~XmaEngine() { unbind(); } void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) { + // Construct with a size so MSVC's Debug iterator allocations can also fail + // through this call instead of the noexcept default constructor. + std::vector> slots(count); + for (auto& slot : slots) slot = std::make_unique(); unbind(); std::unique_lock lock(table_mutex_); array_ = array; - voices_.clear(); - voices_.reserve(count); - for (uint32_t i = 0; i < count; ++i) { - voices_.push_back(std::make_unique()); - } + voices_.swap(slots); } void unbind() { @@ -476,16 +486,15 @@ public: { std::lock_guard slot_lock(voices_[index]->mutex); - const bool was_active = voices_[index]->voice.has_value(); + auto& voice = voices_[index]->voice; // Clear error_status (26..30) and error flag (31). ctx.set_field(2, 26, 6, 0); - XmaVoice voice; - voice.skip = static_cast(ctx.field(1, 24, 3)) * kXmaSubframeSamples; - voices_[index]->voice.emplace(std::move(voice)); - if (!was_active) { + if (!voice) { + voice.emplace(); active_count_.fetch_add(1, std::memory_order_relaxed); } + voice->ended = false; } ensure_worker_and_wake(); } @@ -566,19 +575,17 @@ private: uint32_t current = ctx.field(4, 31, 1); const uint32_t valid = ctx.field(0, 20, 2); - if (voice.next_input_packet || (valid & (1u << current)) == 0) { - const uint32_t other = 1u - current; - if ((valid & (1u << other)) == 0) { - voice.ended = true; - ctx.set_field(2, 26, 5, kXmaErrorInputInvalid); - ctx.set_field(2, 31, 1, 1); - return !voice.pcm.empty(); - } + if (valid == 0) { + voice.ended = true; + ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u); + return !voice.pcm.empty(); + } + const uint32_t other = 1u - current; + const bool current_valid = (valid & (1u << current)) != 0; + const bool other_valid = (valid & (1u << other)) != 0; + if (!current_valid || (voice.exhausted_input == current && other_valid)) { current = other; ctx.set_field(4, 31, 1, current); - const auto next_bit = voice.next_input_packet.value_or(0) * kXmaPacketBits; - ctx.set_field(2, 0, 26, static_cast(next_bit)); - voice.next_input_packet.reset(); } const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6); @@ -586,18 +593,25 @@ private: const std::size_t packet = ctx.field(2, 0, 26) / kXmaPacketBits; const uint8_t* data = apu_span(address & ~0x7FFu, packets * kXmaPacketBytes); if (!data || packet >= packets) { - ctx.set_field(0, 20 + current, 1, 0); - voice.next_input_packet = 0; - ctx.set_field(2, 0, 26, 0); + finish_input(ctx, voice, current, packet >= packets ? packet - packets : 0); return true; } + voice.exhausted_input.reset(); const uint8_t* packet_data = data + packet * kXmaPacketBytes; const uint8_t packet_skip = packet_data[3]; std::vector pcm; decode_packet(ctx, voice, packet_data, pcm); - const std::size_t skip_samples = std::min(voice.skip * channels, pcm.size()); - voice.skip -= skip_samples / channels; + const std::size_t subframe_samples = kXmaSubframeSamples * channels; + const std::size_t initial_skip = ctx.field(1, 24, 3); + const std::size_t skipped_subframes = std::min(initial_skip, pcm.size() / subframe_samples); + if (skipped_subframes != 0) { + ctx.set_field(1, 24, 3, static_cast(initial_skip - skipped_subframes)); + } + const std::size_t initial_samples = skipped_subframes * subframe_samples; + const std::size_t loop_samples = std::min(voice.loop_skip * channels, pcm.size() - initial_samples); + voice.loop_skip -= loop_samples / channels; + const std::size_t skip_samples = initial_samples + loop_samples; voice.pcm.insert(voice.pcm.end(), pcm.begin() + static_cast(skip_samples), pcm.end()); // XMA2 packet headers link packets from the same stream; 0xff ends the chain. @@ -606,7 +620,7 @@ private: const std::size_t loop_end = ctx.field(4, 0, 26); if (loops > 0 && loop_end != 0 && packet == loop_end / kXmaPacketBits) { next = ctx.field(3, 0, 26) / kXmaPacketBits; - voice.skip = static_cast(ctx.field(1, 17, 3)) * kXmaSubframeSamples; + voice.loop_skip = static_cast(ctx.field(1, 17, 3)) * kXmaSubframeSamples; #if defined(LEONIDA_HAVE_XMA2_DECODER) // A frame spilling out of the loop-end packet does not continue in the loop-start packet: // start a fresh decoder there rather than decode the spliced bits. @@ -615,16 +629,24 @@ private: if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u); } if (next >= packets) { - ctx.set_field(0, 20 + current, 1, 0); - voice.next_input_packet = next - packets; - next = 0; + finish_input(ctx, voice, current, next - packets); + } else { + ctx.set_field(2, 0, 26, static_cast(next * kXmaPacketBits)); } - ctx.set_field(2, 0, 26, static_cast(next * kXmaPacketBits)); return true; } + static void finish_input(XmaContextView ctx, XmaVoice& voice, uint32_t current, + std::size_t skip_packets) { + voice.exhausted_input = current; + // Publish the next offset before telling the title it can refill this input. + ctx.set_field(2, 0, 26, static_cast(skip_packets * kXmaPacketBits)); + ctx.set_field(0, 20 + current, 1, 0); + } + static void pump_voice(XmaContextView ctx, XmaVoice& voice) { const uint32_t size = ctx.field(0, 22, 5); + if (size == 0 || ctx.field(1, 31, 1) == 0) return; auto* ring = apu_span(ctx.get(7), size * kXmaBlockBytes); if (!ring) return; @@ -918,58 +940,80 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { std::lock_guard lock(g_shape_mutex); - auto alloc_array = [](uint32_t count, size_t elem_size) -> void* { + ShapeAllocation pending{ctx, {}}; + std::size_t array_index = 0; + auto alloc_array = [&](uint32_t count, size_t elem_size) -> void* { if (count == 0) return nullptr; void* ptr = std::calloc(count, elem_size); - if (ptr) g_active_shape_arrays.push_back(ptr); + if (!ptr) throw std::bad_alloc(); + pending.arrays[array_index++].reset(ptr); return ptr; }; - ctx->srcContextArray = static_cast( - alloc_array(ctx->numSrcContexts, sizeof(SHAPE_SRC_CONTEXT))); - ctx->eqCompContextArray = static_cast( - alloc_array(ctx->numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT))); - ctx->filtVolContextArray = static_cast( - alloc_array(ctx->numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT))); - ctx->dmaContextArray = static_cast( - alloc_array(ctx->numDmaContexts, sizeof(SHAPE_DMA_CONTEXT))); - ctx->xmaContextArray = static_cast( - alloc_array(ctx->numXmaContexts, sizeof(SHAPE_XMA_CONTEXT))); - ctx->pcmContextArray = static_cast( - alloc_array(ctx->numPcmContexts, sizeof(SHAPE_PCM_CONTEXT))); - - // On PC there is no physical APU address translation for host context arrays; - // assign unique synthetic addresses from the APU base. - ctx->apuSrcContextArray = {ctx->srcContextArray ? kApuBaseAddress : 0}; - ctx->apuEqCompContextArray = {ctx->eqCompContextArray ? kApuBaseAddress + 0x1000 : 0}; - ctx->apuFiltVolContextArray = {ctx->filtVolContextArray ? kApuBaseAddress + 0x2000 : 0}; - ctx->apuDmaContextArray = {ctx->dmaContextArray ? kApuBaseAddress + 0x3000 : 0}; - ctx->apuXmaContextArray = {ctx->xmaContextArray ? kApuBaseAddress + 0x4000 : 0}; - ctx->apuPcmContextArray = {ctx->pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; - - g_xma_engine.bind(ctx->xmaContextArray, ctx->numXmaContexts); - - trace_call("AcpHalAllocateShapeContexts", - ",\"src\":" + std::to_string(ctx->numSrcContexts) + - ",\"xma\":" + std::to_string(ctx->numXmaContexts) + - ",\"pcm\":" + std::to_string(ctx->numPcmContexts)); + SHAPE_CONTEXTS result{}; + result.numSrcContexts = ctx->numSrcContexts; + result.numEqCompContexts = ctx->numEqCompContexts; + result.numFiltVolContexts = ctx->numFiltVolContexts; + result.numDmaContexts = ctx->numDmaContexts; + result.numXmaContexts = ctx->numXmaContexts; + result.numPcmContexts = ctx->numPcmContexts; + try { + result.srcContextArray = static_cast( + alloc_array(result.numSrcContexts, sizeof(SHAPE_SRC_CONTEXT))); + result.eqCompContextArray = static_cast( + alloc_array(result.numEqCompContexts, sizeof(SHAPE_EQCOMP_CONTEXT))); + result.filtVolContextArray = static_cast( + alloc_array(result.numFiltVolContexts, sizeof(SHAPE_FILTVOL_CONTEXT))); + result.dmaContextArray = static_cast( + alloc_array(result.numDmaContexts, sizeof(SHAPE_DMA_CONTEXT))); + result.xmaContextArray = static_cast( + alloc_array(result.numXmaContexts, sizeof(SHAPE_XMA_CONTEXT))); + result.pcmContextArray = static_cast( + alloc_array(result.numPcmContexts, sizeof(SHAPE_PCM_CONTEXT))); + + // Assign synthetic APU addresses to the host-side context arrays. + result.apuSrcContextArray = {result.srcContextArray ? kApuBaseAddress : 0}; + result.apuEqCompContextArray = {result.eqCompContextArray ? kApuBaseAddress + 0x1000 : 0}; + result.apuFiltVolContextArray = {result.filtVolContextArray ? kApuBaseAddress + 0x2000 : 0}; + result.apuDmaContextArray = {result.dmaContextArray ? kApuBaseAddress + 0x3000 : 0}; + result.apuXmaContextArray = {result.xmaContextArray ? kApuBaseAddress + 0x4000 : 0}; + result.apuPcmContextArray = {result.pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; + + g_shape_allocations.reserve(g_shape_allocations.size() + 1); + g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + + // Both the backing arrays and the engine's slots are now fully allocated. + g_shape_allocations.push_back(std::move(pending)); + *ctx = result; + if (rt::startup_trace::enabled()) { + try { + trace_call("AcpHalAllocateShapeContexts", + ",\"src\":" + std::to_string(result.numSrcContexts) + + ",\"xma\":" + std::to_string(result.numXmaContexts) + + ",\"pcm\":" + std::to_string(result.numPcmContexts)); + } catch (const std::bad_alloc&) { + // The allocation succeeded. A missing diagnostic does not invalidate it. + } + } return S_OK; } // ---- AcpHalReleaseShapeContexts ---- -HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { +HRESULT __stdcall AcpHalReleaseShapeContexts(void* argument = nullptr) { std::lock_guard lock(g_shape_mutex); // Stop and detach the XMA worker before freeing backing arrays. g_xma_engine.unbind(); - // Free all recorded context allocations - for (void* p : g_active_shape_arrays) { - if (p) std::free(p); - } - g_active_shape_arrays.clear(); - - if (ctx) { + // Retail passes its IAcpHal handle. Only a pointer previously supplied to + // AllocateShapeContexts can safely be treated as a SHAPE_CONTEXTS output. + const auto allocation = std::find_if(g_shape_allocations.begin(), g_shape_allocations.end(), + [argument](const ShapeAllocation& entry) { return entry.caller == argument; }); + if (allocation != g_shape_allocations.end()) { + auto* ctx = allocation->caller; ctx->srcContextArray = nullptr; ctx->eqCompContextArray = nullptr; ctx->filtVolContextArray = nullptr; @@ -977,6 +1021,7 @@ HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { ctx->xmaContextArray = nullptr; ctx->pcmContextArray = nullptr; } + g_shape_allocations.clear(); trace_call("AcpHalReleaseShapeContexts", ""); return S_OK; diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp index 9ee2ee7ff..540906ec8 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp @@ -11,12 +11,28 @@ #include #include #include +#include #include +#include #include #include #include "shims.h" +// Fail only the calling test thread's designated allocation. +static thread_local int allocations_before_failure = -1; +void* operator new(std::size_t size) { + if (allocations_before_failure == 0) { + allocations_before_failure = -1; + throw std::bad_alloc(); + } + if (allocations_before_failure > 0) --allocations_before_failure; + if (void* memory = std::malloc(size ? size : 1)) return memory; + throw std::bad_alloc(); +} +void operator delete(void* memory) noexcept { std::free(memory); } +void operator delete(void* memory, std::size_t) noexcept { std::free(memory); } + namespace { using AcpHalCreateFn = HRESULT(__stdcall*)(void**); @@ -78,9 +94,42 @@ struct XmaWords { } }; +// Synthetic mono XMA2 with a single positive spectral coefficient in each frame. +void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip) { + constexpr uint32_t frame_bits = 82; + std::memset(packet, 0xFF, 2048); + std::size_t at = 0; + auto put = [&](uint32_t value, std::size_t width) { + for (std::size_t i = 0; i < width; ++i, ++at) { + const auto mask = static_cast(0x80u >> (at % 8)); + packet[at / 8] &= static_cast(~mask); + if ((value >> (width - 1 - i)) & 1u) packet[at / 8] |= mask; + } + }; + put((frames << 26) | (1u << 8) | packet_skip, 32); + for (uint32_t frame = 0; frame < frames; ++frame) { + put(frame_bits, 15); + put(0b10u, 2); // Fixed layout, one 512-sample subframe. + put(0, 11); // Gain, trim, fill and subframe error flag. + put(1, 1); // Coefficients are present. + put(1, 1); // Explicit vector coefficient count. + put(0, 8); // Use only run/level coding. + put(0, 6); // Quantizer adjustment. + put(0, 2); // Scale factor step. + put((1u << 23) - 1, 23); // One zero delta per 48 kHz scale band. + put(0, 1); // Run/level table 0. + put(0b00u, 2); // Run 0, level 1. + put(1, 1); // Positive sign. + put(0b0101011u, 7); // End of coefficients. + put(0, 1); // Frame padding bit. + put(frame + 1 < frames ? 1 : 0, 1); + } +} + } // namespace int main() { + std::setvbuf(stdout, nullptr, _IONBF, 0); std::printf("acphal_test: registered acphal.dll shim verification\n"); const auto create = reinterpret_cast( @@ -264,6 +313,21 @@ int main() { check(ctx_all.xmaContextArray != nullptr, "xmaContextArray is allocated"); check(ctx_all.pcmContextArray != nullptr, "pcmContextArray is allocated"); + TestShapeContexts retry_ctx{}; + retry_ctx.numXmaContexts = 2; + allocations_before_failure = 1; // The tracked allocation can grow, then voice slot allocation fails. + HRESULT allocation_result = E_UNEXPECTED; + try { + allocation_result = alloc_ctx(&retry_ctx); + } catch (const std::bad_alloc&) { + // An exception across the AcpHal boundary is a regression. + } + allocations_before_failure = -1; + check(allocation_result == E_OUTOFMEMORY && retry_ctx.xmaContextArray == nullptr, + "A failed XMA slot allocation returns E_OUTOFMEMORY without publishing a context"); + check(alloc_ctx(&retry_ctx) == S_OK && retry_ctx.xmaContextArray != nullptr, + "SHAPE allocation can be retried after memory pressure"); + // Release shape contexts check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds"); check(ctx_all.xmaContextArray == nullptr, "xmaContextArray is reset to null"); @@ -359,44 +423,6 @@ int main() { { // Two synthetic XMA2 packets with three mono frames each. Each frame // transmits one positive spectral coefficient so decoded PCM differs from fallback silence. - std::vector stream(2 * 2048, 0xFFu); - auto put_bits = [&](size_t at, uint32_t value, size_t width) { - for (size_t i = 0; i < width; ++i) { - const size_t p = at + i; - const uint32_t bit = (value >> (width - 1 - i)) & 1u; - stream[p / 8] = static_cast( - (stream[p / 8] & ~(0x80u >> (p % 8))) | - (bit << (7 - (p % 8)))); - } - }; - for (size_t packet = 0; packet < 2; ++packet) { - const size_t base = packet * 2048 * 8; - put_bits(base, (3u << 26) | (1u << 8), 32); - constexpr size_t frame_bits = 82; - for (size_t f = 0; f < 3; ++f) { - size_t at = base + 32 + f * frame_bits; - auto put = [&](uint32_t value, size_t width) { - put_bits(at, value, width); - at += width; - }; - put(frame_bits, 15); - put(0b10u, 2); // Fixed layout, one 512-sample subframe. - put(0, 11); // Gain, trim, fill and subframe error flag. - put(1, 1); // Coefficients are present. - put(1, 1); // Explicit vector coefficient count. - put(0, 8); // Use only run/level coding. - put(0, 6); // Quantizer adjustment. - put(0, 2); // Scale factor step. - put((1u << 23) - 1, 23); // One zero delta per 48 kHz scale band. - put(0, 1); // Run/level table 0. - put(0b00u, 2); // Run 0, level 1. - put(1, 1); // Positive sign. - put(0b0101011u, 7); // End of coefficients. - put(0, 1); // Frame padding bit. - put(f < 2 ? 1u : 0u, 1); // Another frame follows in this packet. - } - } - TestShapeContexts xma_ctx{}; xma_ctx.numXmaContexts = 4; check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr, @@ -406,7 +432,9 @@ int main() { uint32_t in_apu = 0; check(alloc(&in_va, &in_apu, 0x1000, 0x800, 1) == S_OK && in_va != nullptr, "ApuAlloc 2-packet XMA2 input buffer"); - std::memcpy(in_va, stream.data(), stream.size()); + auto* packets = static_cast(in_va); + write_xma_packet(packets, 3, 0); + write_xma_packet(packets + 2048, 3, 0); void* out_va = nullptr; uint32_t out_apu = 0; @@ -499,27 +527,6 @@ int main() { // 8b. Loops are rounded to whole packets: the loop end packet plays in full and the read // restarts at the packet holding the loop start. One 1-frame packet = 512 samples = 4 blocks. { - // Three packets with one silent mono frame each. Packet 0 skips packet 1, - // which belongs to another stream. - std::vector stream(3 * 2048, 0xFFu); - auto put_bits = [&](size_t at, uint32_t value, size_t width) { - for (size_t i = 0; i < width; ++i) { - const size_t p = at + i; - const uint32_t bit = (value >> (width - 1 - i)) & 1u; - stream[p / 8] = static_cast( - (stream[p / 8] & ~(0x80u >> (p % 8))) | - (bit << (7 - (p % 8)))); - } - }; - for (size_t packet = 0; packet < 3; ++packet) { - const size_t base = packet * 2048 * 8; - put_bits(base, (1u << 26) | (packet == 0 ? 1u : 0u), 32); - const size_t at = base + 32; - put_bits(at, 31, 15); // frame length - put_bits(at + 15, 0b10u, 2); // fixed layout, one 512-sample subframe - put_bits(at + 17, 0, 14); // gain(8) + trim(1) + subframe_skip/empty(5) - } - TestShapeContexts xma_ctx{}; xma_ctx.numXmaContexts = 4; check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr, @@ -527,9 +534,12 @@ int main() { void* in_va = nullptr; uint32_t in_apu = 0; - check(alloc(&in_va, &in_apu, 0x1800, 0x800, 1) == S_OK && in_va != nullptr, - "ApuAlloc 3-packet loop input buffer"); - std::memcpy(in_va, stream.data(), stream.size()); + check(alloc(&in_va, &in_apu, 0x2000, 0x800, 1) == S_OK && in_va != nullptr, + "ApuAlloc 4-packet loop and refill input buffer"); + auto* packets = static_cast(in_va); + write_xma_packet(packets, 1, 1); // Packet 1 belongs to another stream. + write_xma_packet(packets + 0x800, 2, 0); + write_xma_packet(packets + 0x1000, 1, 0); void* out_va = nullptr; uint32_t out_apu = 0; @@ -569,8 +579,10 @@ int main() { const uint32_t voice_index = 2u; // Returns the number of blocks written before input exhaustion, or -1 on timeout. - auto run_blocks = [&](uint32_t loops, uint32_t input_0_packets = 3) -> int { + auto run_blocks = [&](uint32_t loops, uint32_t input_0_packets = 3, + uint32_t initial_skip = 0, uint32_t loop_skip = 0) -> int { configure_voice(loops, input_0_packets, 16, 0, 0); + words[1].fetch_or((initial_skip << 24) | (loop_skip << 17)); check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK, "ENABLE_XMA voice 2 succeeds"); int wait = 0; @@ -588,10 +600,26 @@ int main() { check(run_blocks(0) == 8, "Packets 0 and 2 write 8 blocks, skipping packet 1"); check(run_blocks(1) == 12, "One loop of packet 0 writes 12 blocks (packets 0, 0, 2)"); check(((words[0] >> 12) & 0xFFu) == 0u, "Loop count is consumed by the single loop"); + const auto* ring_bytes = static_cast(out_va); +#if defined(LEONIDA_HAVE_XMA2_DECODER) + auto has_signal = [](const uint8_t* start) { + return std::any_of(start, start + 0x400, [](uint8_t b) { return b != 0 && b != 0x55; }); + }; + check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400) && has_signal(ring_bytes + 0x800), + "Rust produces signal before and after rewinding the loop"); + check(std::memcmp(ring_bytes, ring_bytes + 0x400, 0x400) == 0, + "Rewind decodes the first packet from fresh decoder state"); +#endif + check(run_blocks(1, 3, 2, 1) == 9 && ((words[1] >> 24) & 7u) == 0, + "Initial and loop subframe skips consume 3 blocks and clear the initial skip"); check(run_blocks(0, 2) == 8 && (words[4] >> 31) == 1u, "A skip to the end of input 0 continues at input 1"); check(run_blocks(0, 1) == 8 && (words[4] >> 31) == 1u, "An overshooting skip starts at packet 1 of input 1"); +#if defined(LEONIDA_HAVE_XMA2_DECODER) + check(has_signal(ring_bytes) && has_signal(ring_bytes + 0x400), + "Rust produces signal on both sides of the buffer switch"); +#endif configure_voice(255, 3, 4, 7, 9); check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &voice_index, 0) == S_OK, @@ -602,7 +630,6 @@ int main() { check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK, "Disable infinite loop after filling bounded ring"); check(((words[0] >> 12) & 0xFFu) == 255u, "Infinite loop does not consume its loop count"); - const auto* ring_bytes = static_cast(out_va); check(std::all_of(ring_bytes + 0x400, ring_bytes + 0x1000, [](uint8_t b) { return b == 0x55; }), "Output never writes beyond the configured four-block ring"); @@ -613,6 +640,48 @@ int main() { check(fn_submit(x_acp, 18, 0xf5, 0xffffffffu, advance_args, 0) == S_OK && words[9] == 2u, "ADVANCE_XMA_READ wraps at the ring size without overflowing"); + auto wait_for_ring = [&]() { + for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1); + return (words[1] >> 31) == 0u; + }; + const uint32_t refill_read_args[2] = {voice_index, 4}; + + configure_voice(0, 3, 4, 0, 0); + words[0] = 1u | (1u << 20) | (4u << 22); + write_xma_packet(packets, 3, 0); + check(fn_submit(x_acp, 5, 0xf6, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(), + "First packet fills the ring and leaves queued PCM"); + words[0].fetch_or(1u << 20); + check(fn_submit(x_acp, 5, 0xf7, 0xffffffffu, &voice_index, 0) == S_OK, + "Re-enable while refilling the current input"); + int refills = 0; + for (int i = 0; i < 5; ++i) { + if (fn_submit(x_acp, 18, 0xf8, 0xffffffffu, refill_read_args, 0) != S_OK || !wait_for_ring()) break; + ++refills; + } + check(refills == 5 && (words[2] >> 31) == 0u && ((words[0] >> 20) & 3u) == 0u, + "Refill and repeated enable preserve all six frames and consume the reused input"); + check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &voice_index, 0) == S_OK, + "Disable the single-buffer refill voice"); + + // The next same-stream packet is in the first input's refill, after a short second input. + write_xma_packet(packets, 1, 2); + write_xma_packet(packets + 0x1000, 2, 0); + write_xma_packet(packets + 0x1800, 1, 0); + configure_voice(0, 1, 4, 0, 0); + words[1] = (words[1] & ~0xFFFu) | 1u; + check(fn_submit(x_acp, 5, 0xfa, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(), + "Voice fills the ring before the skip crosses two buffers"); + words[5] = in_apu + 0x1000u; + words[0] = (words[0] & ~0xFFFu) | 2u | (1u << 20); + check(fn_submit(x_acp, 18, 0xfb, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(), + "The same-stream packet fills the ring after two buffer crossings"); + check(((words[0] >> 20) & 3u) == 0u && (words[4] >> 31) == 0u, + "A skip across both buffers lands on the last packet of the reloaded input"); + check(fn_submit(x_acp, 7, 0xfc, 0xffffffffu, &voice_index, 0) == S_OK, + "Disable the two-buffer refill voice"); + + check(release_ctx(x_acp) == S_OK, "Release SHAPE contexts through the opaque AcpHal handle"); check(fn_release(x_acp) == S_OK, "Release packet loop AcpHal succeeds"); free_mem(in_va); free_mem(out_va); diff --git a/runtime/xma_decoder/README.md b/runtime/xma_decoder/README.md index 44eb4288a..9db801810 100644 --- a/runtime/xma_decoder/README.md +++ b/runtime/xma_decoder/README.md @@ -23,3 +23,4 @@ The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_3 `runtime/shims/acphal.cpp` uses `leonida_xma2_decoder_create_hardware` and decodes whole 2048-byte packets, so loop points are rounded to packets. The shim creates a fresh decoder after a loop rewind or a decoder error. Without `cargo`, when that build fails, or with the cl.exe fallback of `scripts/build_runtime.ps1`, XMA voices output silence. +Use `-DLEONIDA_REQUIRE_XMA2_DECODER=ON` to require the decoder in a CMake build, as the Windows runtime CI does. diff --git a/runtime/xma_decoder/src/lib.rs b/runtime/xma_decoder/src/lib.rs index cda2721fb..69fedf49e 100644 --- a/runtime/xma_decoder/src/lib.rs +++ b/runtime/xma_decoder/src/lib.rs @@ -109,7 +109,8 @@ unsafe fn create_with( /// Decodes a buffer containing one or more complete 2048-byte XMA2 packets. /// /// # Safety -/// `decoder` must be a live handle returned by `leonida_xma2_decoder_create`. +/// `decoder` must be a live handle returned by `leonida_xma2_decoder_create` +/// or `leonida_xma2_decoder_create_hardware`. /// `input` must reference `input_len` readable bytes and `out_block` must be writable. /// Do not destroy a decoder concurrently with this call. The returned PCM block remains valid /// until `leonida_xma2_pcm_destroy` is called. @@ -182,8 +183,8 @@ pub unsafe extern "C" fn leonida_xma2_decode_buffer( /// Destroys a decoder. Passing null is a no-op. /// /// # Safety -/// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create`, -/// and no calls may be using it concurrently. +/// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create` +/// or `leonida_xma2_decoder_create_hardware`. No calls may be using it concurrently. #[no_mangle] pub unsafe extern "C" fn leonida_xma2_decoder_destroy(decoder: *mut LeonidaXma2Decoder) { if !decoder.is_null() { diff --git a/runtime/xma_decoder/tests/ffi_contract.rs b/runtime/xma_decoder/tests/ffi_contract.rs index 0eb8e5cf4..6e6185c39 100644 --- a/runtime/xma_decoder/tests/ffi_contract.rs +++ b/runtime/xma_decoder/tests/ffi_contract.rs @@ -51,6 +51,28 @@ fn make_decoder(rate: u32, channels: u32) -> *mut LeonidaXma2Decoder { decoder } +#[test] +fn hardware_mode_keeps_all_samples_of_the_first_stereo_frame() { + let mut packet = synthetic_silent_packet(2); + packet[..4].copy_from_slice(&[4, 0, 1, 0]); // One frame, no continuation from a previous packet. + let mut decoder = ptr::null_mut(); + let mut block = ptr::null_mut(); + unsafe { + assert_eq!( + leonida_xma2_decoder_create_hardware(48_000, 2, &mut decoder), + LEONIDA_XMA2_OK + ); + assert_eq!( + leonida_xma2_decode_buffer(decoder, packet.as_ptr(), packet.len(), &mut block), + LEONIDA_XMA2_OK + ); + let count = leonida_xma2_pcm_sample_count(block); + leonida_xma2_pcm_destroy(block); + leonida_xma2_decoder_destroy(decoder); + assert_eq!(count, 512 * 2); + } +} + #[test] fn creation_rejects_invalid_outputs_and_formats() { assert_eq!( -- cgit v1.2.3