diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index cafdf469fb..de01c63977 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 64e346f40a..e3d2b8eba2 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -106,6 +106,44 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" ) + # 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. + set(_xma_target x86_64-pc-windows-msvc) + set(_xma_target_dir ${CMAKE_BINARY_DIR}/xma_decoder) + set(_xma_lib ${_xma_target_dir}/${_xma_target}/release/leonida_xma2_decoder.lib) + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.toml + ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.lock + ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/src/lib.rs) + execute_process( + COMMAND ${LEONIDA_CARGO} build --release --locked --target ${_xma_target} + --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.toml + --target-dir ${_xma_target_dir} + TIMEOUT 120 + RESULT_VARIABLE _xma_result) + if(_xma_result STREQUAL "0" AND EXISTS ${_xma_lib}) + add_library(leonida_xma2_decoder STATIC IMPORTED) + # Link Rust's Windows SDK dependencies. CMake's C++ target selects its own CRT + # (/MD or /MDd); the C ABI keeps allocation and deallocation on the same side. + set_target_properties(leonida_xma2_decoder PROPERTIES + IMPORTED_LOCATION ${_xma_lib} + INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder + INTERFACE_COMPILE_DEFINITIONS LEONIDA_HAVE_XMA2_DECODER=1 + INTERFACE_LINK_LIBRARIES "kernel32;ntdll;userenv;ws2_32;dbghelp") + else() + message(WARNING "cargo build of runtime/xma_decoder failed: XMA voices will be silent") + endif() + 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 src/host_cpu.cpp @@ -250,6 +288,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8) target_link_options(acphal_test PRIVATE /OPT:NOREF) + if(TARGET leonida_xma2_decoder) + target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder) + target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder) + endif() + # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. add_executable(cpu_emulation_test test/cpu_emulation_test.cpp) @@ -1162,6 +1205,7 @@ if(BUILD_TESTING) endif() if(WIN32 AND TARGET acphal_test) add_test(NAME acphal COMMAND acphal_test) + add_test(NAME acphal_noncached_only COMMAND acphal_test --noncached-only) endif() if(WIN32 AND TARGET cpu_emulation_test) add_test(NAME cpu_emulation COMMAND cpu_emulation_test) diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp index 5ead016d63..f1c33ddd9e 100644 --- a/runtime/shims/acphal.cpp +++ b/runtime/shims/acphal.cpp @@ -1,10 +1,12 @@ // acphal.dll: Audio Control Processor HAL. Scalable Hardware Audio Processing Engine // (SHAPE) and APU (Audio Processing Unit) physical memory management for Xbox Series. // -// On a PC there is no SHAPE/ACP hardware and APU physical memory does not exist. -// This shim creates the APU heap from process memory and manages allocations within it. -// The SHAPE context arrays are allocated on the process heap; the ACP interface -// accepts and acknowledges commands to allow audio bring-up to proceed cleanly. +// Provides: +// - A VirtualAlloc-backed APU heap (cached + non-cached) with 32-bit device addresses; +// - SHAPE context arrays sized to the documented GDK strides; +// - The IAcpHal command and message queue (registration, completion, disconnect, +// flowgraph acknowledgement, and APU notification word writes); +// - A background XMA2 decoder pumping enabled SHAPE_XMA_CONTEXT output rings. // // Signatures from the public GDK reference (devdocs.xbox.com): // AcpHal, APU reference, SHAPE_CONTEXTS, APU_ADDRESS. @@ -14,21 +16,37 @@ #include -#include +#include #include +#include +#include +#include +#include #include #include #include #include #include +#include #include +#include #include +#include +#include #include +#include +#include #include +#include +#include +#include #include #include "shims.h" #include "startup_trace.h" +#if defined(LEONIDA_HAVE_XMA2_DECODER) +#include "leonida_xma2_decoder.h" +#endif namespace { @@ -124,24 +142,7 @@ struct SHAPE_DMA_CONTEXT { static_assert(sizeof(SHAPE_DMA_CONTEXT) == 16, "SHAPE_DMA_CONTEXT is 16 bytes per GDK"); struct SHAPE_XMA_CONTEXT { - uint32_t sizeRead0 : 12; - uint32_t numLoops : 8; - uint32_t validBuffer : 2; - uint32_t sizeWrite : 5; - uint32_t offsetWrite : 5; - uint32_t sizeRead1 : 12; - uint32_t sequenceNumber : 12; - uint32_t stopSampleAddress : 8; - uint32_t subframeOffset : 4; - uint32_t reserved0 : 1; - uint32_t isLooping : 1; - uint32_t subframeSkip : 2; - uint32_t packetMetadata : 16; - uint32_t currentByteOffset : 26; - uint32_t reserved1 : 6; - uint32_t loopStartOffset : 26; - uint32_t loopEndOffset : 6; - uint32_t reserved[11]; // the GDK's 64-byte context: the published field list leaves one trailing word + uint32_t words[16]; // See the shared word layout above the XMA engine. }; static_assert(sizeof(SHAPE_XMA_CONTEXT) == 64, "SHAPE_XMA_CONTEXT is 64 bytes per GDK"); @@ -194,21 +195,28 @@ static_assert(offsetof(SHAPE_CONTEXTS, xmaContextArray) == 0x38, // ---- Startup trace helper ---- -void trace_call(const char* api, const std::string& detail) { +void trace_call(const char* api, std::string_view detail = {}) noexcept try { if (!rt::startup_trace::enabled()) return; static std::mutex mutex; static std::set seen; { const std::lock_guard lock(mutex); - if (!seen.insert(std::string(api) + detail).second) return; + if (!seen.insert(std::string(api).append(detail)).second) return; } rt::startup_trace::event("acphal", - std::string("\"api\":\"") + api + "\"" + detail); + (std::string("\"api\":\"") + api + "\"").append(detail)); +} catch (...) { + // Tracing cannot change the result of a guest-facing call. } // ---- Genuine APU Heap Implementation ---- constexpr uint32_t kApuBaseAddress = 0x40000000u; +constexpr uint64_t kApuRegionAlignment = 0x10000u; + +uint64_t align_apu_region(uint64_t size) { + return (size + kApuRegionAlignment - 1) & ~(kApuRegionAlignment - 1); +} struct ApuRegion { void* base = nullptr; @@ -241,6 +249,13 @@ struct ApuRegion { return static_cast(base) + offset; } + uint8_t* span_from_offset(uint32_t offset, std::size_t len) const { + if (!base || len == 0 || offset >= size) return nullptr; + const uint64_t remaining = size - offset; + if (len > remaining) return nullptr; + return static_cast(base) + offset; + } + void* allocate(uint32_t alloc_size, uint32_t alignment, uint32_t* out_offset) { if (alloc_size == 0 || alignment == 0) return nullptr; uint64_t at = 0; @@ -281,48 +296,667 @@ ApuRegion g_cached_heap; ApuRegion g_noncached_heap; // Tracked SHAPE context arrays -std::vector g_active_shape_arrays; +struct ShapeArrayFree { + void operator()(void* array) const noexcept { std::free(array); } +}; + +using ShapeAllocation = std::array, 6>; + +std::mutex g_shape_mutex; +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) { + if (apu < kApuBaseAddress || len == 0) return nullptr; + std::lock_guard lock(g_apu_mutex); + const uint32_t offset = apu - kApuBaseAddress; + if (g_cached_heap.base && offset < g_cached_heap.size) { + return g_cached_heap.span_from_offset(offset, len); + } + if (g_noncached_heap.base) { + const uint64_t cached_span = align_apu_region(g_cached_heap.size); + if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { + return g_noncached_heap.span_from_offset( + static_cast(offset - cached_span), len); + } + } + return nullptr; +} + +// ---- ACP Command / Message Protocol Constants ---- + +constexpr uint32_t kCmdLoadFlowgraph = 1; +constexpr uint32_t kCmdRegisterMessages = 2; +constexpr uint32_t kCmdUnregisterMessages = 3; +constexpr uint32_t kCmdEnableXma = 5; +constexpr uint32_t kCmdEnableXmas = 6; +constexpr uint32_t kCmdDisableXma = 7; +constexpr uint32_t kCmdDisableXmas = 8; +constexpr uint32_t kCmdAdvanceXmaRead = 18; + +constexpr uint32_t kMsgFlowgraphCompleted = 0x02u; +constexpr uint32_t kMsgCommandCompleted = 0x10u; +constexpr uint32_t kMsgDisconnected = 0x80u; + +// 128 samples per audio frame at 48 kHz = 375 audio frames/second. +constexpr uint64_t kAudioFramesPerSecond = 375; + +// ---- XMA2 Hardware Context Decoder Engine ---- +// +// Each 64-byte SHAPE_XMA_CONTEXT holds 16 32-bit words shared with the title: +// Word 0: input 0 packets (0..11), loop count (12..19, 255 = forever), +// valid input bits (20..21), output ring blocks (22..26), write block (27..31). +// Word 1: input 1 packets (0..11), loop end subframe (12..13), loop start skip subframes +// (17..19), initial skip subframes (24..26), rate index (27..28: 24/32/44.1/48 kHz), +// stereo (29), output writable (31). +// Word 2: read bit offset (0..25), error status (26..30), error flag (31). +// Word 3: loop start bit offset (0..25). +// Word 4: loop end bit offset (0..25), current input buffer index (31). +// Word 5: input 0 APU address. +// Word 6: input 1 APU address. +// Word 7: output ring APU address. +// Word 8: overlap buffer APU address. +// Word 9: output read block index (0..4). +// +// Packets are decoded by the Rust decoder in runtime/xma_decoder when CMake found cargo (LEONIDA_HAVE_XMA2_DECODER); +// otherwise each packet becomes silence for its frame count. The read offset (word 2) and the loop points (words 3 +// and 4) are used per 2048-byte packet, so the loop-end subframe (word 1 bits 12..13) is not applied. + +constexpr std::size_t kXmaBlockBytes = 256; +constexpr std::size_t kXmaSamplesPerBlock = kXmaBlockBytes / 2; +constexpr std::size_t kXmaPacketBytes = 2048; +constexpr std::size_t kXmaPacketBits = kXmaPacketBytes * 8; +constexpr std::size_t kXmaSubframeSamples = 128; +constexpr std::size_t kXmaFrameSamples = 512; +constexpr uint32_t kXmaErrorInputInvalid = 4; + +#if defined(LEONIDA_HAVE_XMA2_DECODER) +constexpr uint32_t kXmaRates[4] = {24000, 32000, 44100, 48000}; +struct Xma2DecoderFree { + void operator()(LeonidaXma2Decoder* d) const noexcept { leonida_xma2_decoder_destroy(d); } +}; +struct Xma2PcmFree { + void operator()(LeonidaXma2PcmBlock* b) const noexcept { leonida_xma2_pcm_destroy(b); } +}; +#endif + +struct XmaContextView { + uint32_t* words = nullptr; + + uint32_t get(std::size_t index) const { return std::atomic_ref(words[index]).load(); } + + uint32_t field(std::size_t index, uint32_t shift, uint32_t bits) const { + const uint32_t mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u); + return (get(index) >> shift) & mask; + } + + uint32_t set_field(std::size_t index, uint32_t shift, uint32_t bits, uint32_t value) const { + const uint32_t raw_mask = (bits >= 32) ? 0xFFFFFFFFu : ((1u << bits) - 1u); + const uint32_t mask = raw_mask << shift; + const uint32_t field_value = (value << shift) & mask; + std::atomic_ref word(words[index]); + uint32_t previous = word.load(); + while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {} + return previous; + } + +}; + +struct XmaVoice { + explicit XmaVoice(uint32_t format_bits) : pcm(0), format(format_bits) {} + std::size_t channels() const { return 1u + (format >> 2); } + std::size_t queued_samples() const { return pcm.size() - pcm_read; } + +#if defined(LEONIDA_HAVE_XMA2_DECODER) + std::unique_ptr decoder; +#endif + std::vector pcm; + std::size_t pcm_read = 0; + std::size_t loop_skip = 0; // samples per channel to drop after a rewind + uint32_t format; // SHAPE word 1 bits 27..29, rate and channel layout + bool ended = false; +}; + +struct XmaVoiceSlot { + std::mutex mutex; + std::optional voice; +}; + +class XmaEngine { +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_.swap(slots); + } + + void unbind() { + { + std::unique_lock lock(table_mutex_); + array_ = nullptr; + voices_.clear(); + active_count_.store(0, std::memory_order_relaxed); + } + // Once detached, commands cannot start a worker for this table. + stop_worker(); + } + + bool handle_command(uint32_t command, const void* config) { + auto read_word = [config](std::size_t index) -> uint32_t { + if (!config) return 0u; + uint32_t value = 0; + std::memcpy(&value, static_cast(config) + index * sizeof(uint32_t), + sizeof(uint32_t)); + return value; + }; + + switch (command) { + case kCmdEnableXma: + if (config) enable(read_word(0)); + return true; + case kCmdDisableXma: + if (config) disable(read_word(0)); + return true; + case kCmdEnableXmas: + case kCmdDisableXmas: { + std::shared_lock lock(table_mutex_); + const std::size_t count = voices_.size(); + lock.unlock(); + if (!config) return true; + for (std::size_t i = 0; i < count; ++i) { + const uint32_t bits = read_word(i / 32); + if ((bits & (1u << (i % 32))) != 0) { + if (command == kCmdEnableXmas) { + enable(static_cast(i)); + } else { + disable(static_cast(i)); + } + } + } + return true; + } + case kCmdAdvanceXmaRead: + if (config) advance_read(read_word(0), read_word(1)); + return true; + default: + return false; + } + } + + void enable(uint32_t index) { + std::shared_lock table_lock(table_mutex_); + XmaContextView ctx = context_locked(index); + if (!ctx.words) return; + + { + std::lock_guard slot_lock(voices_[index]->mutex); + auto& voice = voices_[index]->voice; + const uint32_t format = ctx.field(1, 27, 3); + // The worker cannot access the voice until the slot is unlocked. + ensure_worker_and_wake(); + if (!voice) { + voice.emplace(format); + active_count_.fetch_add(1, std::memory_order_relaxed); + } else if (voice->format != format) { + voice->pcm.clear(); + voice->pcm_read = 0; + voice->loop_skip = 0; + voice->format = format; +#if defined(LEONIDA_HAVE_XMA2_DECODER) + voice->decoder.reset(); +#endif + } + voice->ended = false; + ctx.set_field(2, 26, 6, 0); + } + } + + void disable(uint32_t index) { + std::shared_lock table_lock(table_mutex_); + if (index >= voices_.size()) return; + std::lock_guard slot_lock(voices_[index]->mutex); + if (voices_[index]->voice.has_value()) { + voices_[index]->voice.reset(); + active_count_.fetch_sub(1, std::memory_order_relaxed); + } + } + + void advance_read(uint32_t index, uint32_t blocks) { + std::shared_lock table_lock(table_mutex_); + XmaContextView ctx = context_locked(index); + if (!ctx.words) return; + + bool wake = false; + { + std::lock_guard slot_lock(voices_[index]->mutex); + const uint32_t size = ctx.field(0, 22, 5); + if (size == 0) return; + const uint32_t read = (ctx.field(9, 0, 5) + blocks % size) % size; + ctx.set_field(9, 0, 5, read); + if (blocks > 0) { + ctx.set_field(1, 31, 1, 1); + } + wake = voices_[index]->voice.has_value(); + } + if (wake) ensure_worker_and_wake(); + } + +private: + XmaContextView context_locked(uint32_t index) const { + if (!array_ || index >= voices_.size()) return {}; + return XmaContextView{array_[index].words}; + } + + // Appends interleaved s16 for one 2048-byte packet. Without the Rust decoder, or when it + // fails, the packet becomes silence for its frame count (header bits 26..31) so timing holds. + static void decode_packet(XmaVoice& voice, const uint8_t* bytes) { + const std::size_t channels = voice.channels(); +#if defined(LEONIDA_HAVE_XMA2_DECODER) + if (!voice.decoder) { + LeonidaXma2Decoder* raw = nullptr; + if (leonida_xma2_decoder_create_hardware(kXmaRates[voice.format & 3u], + static_cast(channels), &raw) == LEONIDA_XMA2_OK) { + voice.decoder.reset(raw); + } + } + if (voice.decoder) { + LeonidaXma2PcmBlock* raw = nullptr; + if (leonida_xma2_decode_buffer(voice.decoder.get(), bytes, kXmaPacketBytes, &raw) == LEONIDA_XMA2_OK) { + const std::unique_ptr block(raw); + const int16_t* samples = leonida_xma2_pcm_data(block.get()); + const std::size_t count = leonida_xma2_pcm_sample_count(block.get()); + if (count != 0) voice.pcm.insert(voice.pcm.end(), samples, samples + count); + return; + } + voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence. + } +#endif + voice.pcm.resize(voice.pcm.size() + static_cast(bytes[0] >> 2) * kXmaFrameSamples * channels); + } + + // Decodes the packet at the read offset of the current input buffer and queues its PCM. + // Offsets and loop points are used per packet: a loop plays its end packet in full and + // restarts at the start of the packet holding the loop start. + static bool decode_one_packet(XmaContextView ctx, XmaVoice& voice) { + if (voice.ended) return false; + + const std::size_t channels = voice.channels(); + uint32_t current = ctx.field(4, 31, 1); + const uint32_t valid = ctx.field(0, 20, 2); + + if (valid == 0) { + voice.ended = true; + ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u); + return voice.queued_samples() != 0; + } + if ((valid & (1u << current)) == 0) { + current ^= 1u; + ctx.set_field(4, 31, 1, current); + } + + const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6); + const std::size_t packets = (current == 0) ? ctx.field(0, 0, 12) : ctx.field(1, 0, 12); + 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) { + finish_input(ctx, current, packet >= packets ? packet - packets : 0); + return true; + } + + const uint8_t* packet_data = data + packet * kXmaPacketBytes; + const uint8_t packet_skip = packet_data[3]; + // Decoding is only requested when less than a ring block remains. Keep that + // tail and reuse the packet storage as the voice consumes subsequent packets. + voice.pcm.erase(voice.pcm.begin(), voice.pcm.begin() + static_cast(voice.pcm_read)); + voice.pcm_read = 0; + const std::size_t packet_start = voice.pcm.size(); + decode_packet(voice, packet_data); + const std::size_t packet_samples = voice.pcm.size() - packet_start; + 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, packet_samples / subframe_samples); + const std::size_t initial_samples = skipped_subframes * subframe_samples; + const std::size_t loop_samples = std::min(voice.loop_skip * channels, packet_samples - initial_samples); + const std::size_t skip_samples = initial_samples + loop_samples; + if (skip_samples != 0) { + const auto first = voice.pcm.begin() + static_cast(packet_start); + voice.pcm.erase(first, first + static_cast(skip_samples)); + } + // Update the context only after the PCM append succeeds. + if (skipped_subframes != 0) { + ctx.set_field(1, 24, 3, static_cast(initial_skip - skipped_subframes)); + } + voice.loop_skip -= loop_samples / channels; + + // XMA2 packet headers link packets from the same stream; 0xff ends the chain. + std::size_t next = packet_skip == 0xFFu ? packets : packet + 1 + packet_skip; + const uint32_t loops = ctx.field(0, 12, 8); + 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.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. + voice.decoder.reset(); +#endif + if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u); + } + if (next >= packets) { + finish_input(ctx, current, next - packets); + } else { + ctx.set_field(2, 0, 26, static_cast(next * kXmaPacketBits)); + } + return true; + } + + static void finish_input(XmaContextView ctx, uint32_t current, + std::size_t skip_packets) { + // Publish the next offset before telling the title it can refill this input. + ctx.set_field(2, 0, 26, static_cast(skip_packets * kXmaPacketBits)); + const uint32_t other = 1u - current; + const uint32_t retired = ctx.set_field(0, 20 + current, 1, 0); + // Take the other input if it was queued at retirement. Otherwise a double + // refill of the empty pair starts at input 0. A lone input can still run. + ctx.set_field(4, 31, 1, (retired & (1u << (20 + other))) != 0 ? other : 0u); + } + + 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; + + for (uint32_t blocks = 0; blocks < size && ctx.field(1, 31, 1) == 1; ++blocks) { + int decode_guard = 0; + while (voice.queued_samples() < kXmaSamplesPerBlock && decode_guard++ < 16) { + if (!decode_one_packet(ctx, voice)) break; + } + if (voice.queued_samples() == 0) return; + + const uint32_t write = ctx.field(0, 27, 5) % size; + uint8_t* out = ring + write * kXmaBlockBytes; + + for (std::size_t i = 0; i < kXmaSamplesPerBlock; ++i) { + int16_t sample = 0; + if (voice.pcm_read != voice.pcm.size()) { + sample = voice.pcm[voice.pcm_read++]; + } + const uint16_t raw = static_cast(sample); + out[2 * i] = static_cast(raw & 0xFFu); + out[2 * i + 1] = static_cast((raw >> 8) & 0xFFu); + } + + const uint32_t next_write = (write + 1u) % size; + ctx.set_field(0, 27, 5, next_write); + if (next_write == ctx.field(9, 0, 5) % size) { + ctx.set_field(1, 31, 1, 0); + } + } + } + + void pump_all() { + std::shared_lock table_lock(table_mutex_); + if (!array_) return; + for (std::size_t i = 0; i < voices_.size(); ++i) { + std::lock_guard slot_lock(voices_[i]->mutex); + auto& voice = voices_[i]->voice; + if (!voice) continue; + auto ctx = context_locked(static_cast(i)); + try { + pump_voice(ctx, *voice); + } catch (const std::bad_alloc&) { + // Only this voice failed. Retire it and allow the title to enable it again. + voice.reset(); + active_count_.fetch_sub(1, std::memory_order_relaxed); + ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u); + } + } + } + + void ensure_worker_and_wake() { + std::lock_guard lock(worker_mutex_); + if (!worker_.joinable()) { + worker_ = std::jthread([this](std::stop_token stop) { worker_loop(stop); }); + } + wake_requested_ = true; + worker_cv_.notify_one(); + } + + // Each worker owns its stop_token, so a stop only ever reaches the thread it was + // sent to; a worker started after this call is unaffected by it. + void stop_worker() { + std::jthread to_join; + { + std::lock_guard lock(worker_mutex_); + if (!worker_.joinable()) return; + worker_.request_stop(); + worker_cv_.notify_all(); + to_join = std::move(worker_); + } + if (to_join.joinable()) to_join.join(); + } + + void worker_loop(std::stop_token stop) { + for (;;) { + { + std::unique_lock lock(worker_mutex_); + if (stop.stop_requested()) return; + if (active_count_.load(std::memory_order_relaxed) == 0 && !wake_requested_) { + worker_cv_.wait(lock, stop, [this]() { return wake_requested_; }); + if (stop.stop_requested()) return; + } + wake_requested_ = false; + } + + pump_all(); + + std::unique_lock lock(worker_mutex_); + if (stop.stop_requested()) return; + if (!wake_requested_ && active_count_.load(std::memory_order_relaxed) > 0) { + // One 256-byte output block lasts ~2.67 ms at 48 kHz mono. + worker_cv_.wait_for(lock, stop, std::chrono::milliseconds(2), + [this]() { return wake_requested_; }); + } + } + } + + mutable std::shared_mutex table_mutex_; + SHAPE_XMA_CONTEXT* array_ = nullptr; + std::vector> voices_; + std::atomic active_count_{0}; + + std::mutex worker_mutex_; + std::condition_variable_any worker_cv_; + std::jthread worker_; + bool wake_requested_ = false; +}; + +XmaEngine g_xma_engine; // ---- IAcpHal Interface Implementation ---- -struct AcpHalImpl { +#pragma pack(push, 1) +struct AcpMessage { + uint32_t kind = 0; + uint32_t dropped = 0; + uint32_t usec = 0; + uint8_t data[16]{}; +}; +#pragma pack(pop) +static_assert(sizeof(AcpMessage) == 28, "AcpMessage is 28 bytes"); + +void write_u32_le(uint8_t* dst, uint32_t value) { + dst[0] = static_cast(value & 0xFFu); + dst[1] = static_cast((value >> 8) & 0xFFu); + dst[2] = static_cast((value >> 16) & 0xFFu); + dst[3] = static_cast((value >> 24) & 0xFFu); +} + +void write_u64_le(uint8_t* dst, uint64_t value) { + write_u32_le(dst, static_cast(value & 0xFFFFFFFFu)); + write_u32_le(dst + 4, static_cast(value >> 32)); +} + +struct IAcpHal { + virtual HRESULT __stdcall connect(uint32_t commands, uint32_t messages) = 0; + virtual HRESULT __stdcall disconnect() = 0; + virtual HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame, + const void* config, uint32_t notification) = 0; + virtual uint32_t __stdcall pop_message(void* out) = 0; + virtual uint32_t __stdcall get_num_messages() = 0; + virtual HRESULT __stdcall release() = 0; +}; + +struct AcpHalImpl final : IAcpHal { + std::mutex mutex_; + bool connected_ = false; + uint32_t mask_ = 0; + std::deque messages_; + std::size_t capacity_ = 0; + uint32_t dropped_ = 0; + std::chrono::steady_clock::time_point since_ = std::chrono::steady_clock::now(); + + uint64_t elapsed_usec_locked() const { + const auto dt = std::chrono::steady_clock::now() - since_; + return static_cast( + std::chrono::duration_cast(dt).count()); + } + + uint32_t audio_frame_locked() const { + return static_cast((elapsed_usec_locked() * kAudioFramesPerSecond) / 1000000ull); + } + + void post_locked(uint32_t kind, const uint8_t* payload, std::size_t len) { + if ((mask_ & kind) == 0) return; + if (messages_.size() >= capacity_) { + if (dropped_ < UINT32_MAX) ++dropped_; + return; + } + AcpMessage msg{}; + msg.kind = kind; + msg.dropped = dropped_; + msg.usec = static_cast(elapsed_usec_locked()); + if (payload && len > 0) { + std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data))); + } + try { + messages_.push_back(msg); + dropped_ = 0; + } catch (const std::bad_alloc&) { + if (dropped_ < UINT32_MAX) ++dropped_; + } + } + // Slot 0: Connect (called at boot with (0x1000, 0x1000), result checked) - virtual HRESULT __stdcall connect(uint32_t, uint32_t) { + HRESULT __stdcall connect(uint32_t commands, uint32_t messages) override { trace_call("AcpHal::Connect", ""); + if (commands == 0) return E_INVALIDARG; + std::lock_guard lock(mutex_); + connected_ = true; + capacity_ = messages; return S_OK; } // Slot 1: Disconnect (called at shutdown) - virtual HRESULT __stdcall disconnect() { + HRESULT __stdcall disconnect() override { trace_call("AcpHal::Disconnect", ""); + std::lock_guard lock(mutex_); + if (!connected_) return E_FAIL; + post_locked(kMsgDisconnected, nullptr, 0); + connected_ = false; return S_OK; } // Slot 2: SubmitCommand - // Critical: The title calls slot 2 as (2, 0xf0f0f0f0, -1, config, 0) and - // a negative result triggers a fatal int3 kernel panic (+0x43ad94e). - virtual HRESULT __stdcall submit_command(uint32_t cmd, uint32_t d1, uint32_t d2, - const void* config, uint32_t d3) { - (void)cmd; - (void)d1; - (void)d2; - (void)config; - (void)d3; - static std::atomic warned{false}; - if (!warned.exchange(true, std::memory_order_relaxed)) { - std::fprintf(stderr, - "[rt] acphal: command accepted and dropped: no audio DSP hardware on PC\n"); + // Acknowledges command completion, updates registered message masks, dispatches + // XMA voice commands, and writes any requested APU notification word. + HRESULT __stdcall submit_command(uint32_t cmd, uint64_t id, uint32_t frame, + const void* config, uint32_t notification) override try { + (void)frame; + auto read_word = [config](std::size_t index) -> uint32_t { + if (!config) return 0u; + uint32_t value = 0; + std::memcpy(&value, static_cast(config) + index * sizeof(uint32_t), + sizeof(uint32_t)); + return value; + }; + + const bool handled_xma = g_xma_engine.handle_command(cmd, config); + { + std::lock_guard lock(mutex_); + if (!handled_xma) { + switch (cmd) { + case kCmdRegisterMessages: + mask_ |= read_word(0); + break; + case kCmdUnregisterMessages: + mask_ &= ~read_word(0); + break; + case kCmdLoadFlowgraph: { + uint8_t payload[4]; + write_u32_le(payload, read_word(1)); + post_locked(kMsgFlowgraphCompleted, payload, sizeof(payload)); + break; + } + default: + break; + } + } + if (id != 0) { + uint8_t done[16]; + write_u32_le(done, cmd); + write_u64_le(done + 4, id); + write_u32_le(done + 12, audio_frame_locked()); + post_locked(kMsgCommandCompleted, done, sizeof(done)); + } + } + + if (notification != 0) { + if (uint8_t* word_bytes = apu_span(notification, sizeof(uint32_t))) { + if ((reinterpret_cast(word_bytes) & 3u) == 0) { + *reinterpret_cast(word_bytes) = 1u; + } else { + static constexpr uint8_t kOneLe[4] = {1, 0, 0, 0}; + volatile uint8_t* dst = word_bytes; + for (std::size_t i = 0; i < 4; ++i) dst[i] = kOneLe[i]; + } + } } + trace_call("AcpHal::SubmitCommand", ""); return S_OK; + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } catch (const std::system_error&) { + return E_FAIL; } - // Slots 3 and 4: PopMessage and GetNumMessages (message polling, not called by title) - virtual uint32_t __stdcall pop_message() { return 0; } - virtual uint32_t __stdcall get_num_messages() { return 0; } + // Slot 3: PopMessage — returns 0 without touching `out` when the queue is empty. + uint32_t __stdcall pop_message(void* out) override { + std::lock_guard lock(mutex_); + if (messages_.empty()) return 0u; + const AcpMessage msg = messages_.front(); + messages_.pop_front(); + if (out) std::memcpy(out, &msg, sizeof(msg)); + return 1u; + } + + // Slot 4: GetNumMessages + uint32_t __stdcall get_num_messages() override { + std::lock_guard lock(mutex_); + return static_cast(messages_.size()); + } // Slot 5: Release - virtual HRESULT __stdcall release() { + HRESULT __stdcall release() override { trace_call("AcpHal::Release", ""); delete this; return S_OK; @@ -333,7 +967,12 @@ struct AcpHalImpl { HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { if (!ppAcpHal) return E_POINTER; - *ppAcpHal = new AcpHalImpl(); + *ppAcpHal = nullptr; + try { + *ppAcpHal = new AcpHalImpl(); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } trace_call("AcpHalCreate", ""); return S_OK; } @@ -343,63 +982,79 @@ HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { if (!ctx) return E_POINTER; - std::lock_guard lock(g_apu_mutex); + std::lock_guard lock(g_shape_mutex); - auto alloc_array = [](uint32_t count, size_t elem_size) -> void* { + ShapeAllocation pending{}; + 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[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}; - - 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); + if (result.xmaContextArray) 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) { - std::lock_guard lock(g_apu_mutex); - - // Free all recorded context allocations - for (void* p : g_active_shape_arrays) { - if (p) std::free(p); - } - g_active_shape_arrays.clear(); +HRESULT __stdcall AcpHalReleaseShapeContexts(void* /*hal*/) { + std::lock_guard lock(g_shape_mutex); + // Stop and detach the XMA worker before freeing backing arrays. + g_xma_engine.unbind(); - if (ctx) { - ctx->srcContextArray = nullptr; - ctx->eqCompContextArray = nullptr; - ctx->filtVolContextArray = nullptr; - ctx->dmaContextArray = nullptr; - ctx->xmaContextArray = nullptr; - ctx->pcmContextArray = nullptr; - } + // The export releases the process-wide SHAPE arrays. The argument is an + // opaque HAL handle, and allocation descriptors are owned by the caller. + g_shape_allocations.clear(); trace_call("AcpHalReleaseShapeContexts", ""); return S_OK; @@ -411,6 +1066,9 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes, uint32_t nonCachedSizeInBytes) { std::lock_guard lock(g_apu_mutex); if (g_apu_heap_created) return E_FAIL; + const uint64_t address_bytes = (nonCachedSizeInBytes ? align_apu_region(cachedSizeInBytes) + : cachedSizeInBytes) + nonCachedSizeInBytes; + if (address_bytes > static_cast(UINT32_MAX) + 1 - kApuBaseAddress) return E_INVALIDARG; if (cachedSizeInBytes > 0) { g_cached_heap.base = VirtualAlloc( @@ -430,17 +1088,23 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes, } g_apu_heap_created = true; - trace_call("ApuCreateHeap", - ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) + - ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes)); + if (rt::startup_trace::enabled()) { + try { + trace_call("ApuCreateHeap", + ",\"cachedSize\":" + std::to_string(cachedSizeInBytes) + + ",\"nonCachedSize\":" + std::to_string(nonCachedSizeInBytes)); + } catch (const std::bad_alloc&) { + // The heap is ready even if its diagnostic cannot be built. + } + } return S_OK; } // ---- ApuAlloc ---- HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, - uint32_t sizeInBytes, uint32_t alignmentInBytes, - uint32_t flags) { + uint32_t sizeInBytes, uint32_t alignmentInBytes, + uint32_t flags) try { if (!virtualAddress) return E_POINTER; *virtualAddress = nullptr; if (physicalAddress) *physicalAddress = 0; @@ -459,6 +1123,7 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, if (!target->base) { if (!prefer_noncached) { + if (g_apu_heap_created) return E_OUTOFMEMORY; // Lazy default cached heap if ApuCreateHeap wasn't called yet constexpr uint32_t kDefaultHeapSize = 64 * 1024 * 1024; target->base = VirtualAlloc(nullptr, kDefaultHeapSize, @@ -485,17 +1150,17 @@ HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, *virtualAddress = ptr; if (physicalAddress) { - // Disjoint APU address ranges: - // cached: 0x40000000 .. 0x40000000 + cached_size - 1 - // non-cached: 0x40000000 + cached_size .. 0x40000000 + cached_size + noncached_size - 1 + // Leave alignment padding between the two synthetic address ranges. uint32_t apu = kApuBaseAddress + offset; if (target == &g_noncached_heap) { - apu += static_cast(g_cached_heap.size); + apu += static_cast(align_apu_region(g_cached_heap.size)); } *physicalAddress = apu; } return S_OK; +} catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; } // ---- ApuFree ---- @@ -530,7 +1195,7 @@ void* __stdcall ApuMapApuAddress(uint32_t apu) { return g_cached_heap.from_offset(offset); } if (g_noncached_heap.base) { - const uint32_t cached_span = static_cast(g_cached_heap.size); + const uint32_t cached_span = static_cast(align_apu_region(g_cached_heap.size)); if (offset >= cached_span && offset - cached_span < g_noncached_heap.size) { return g_noncached_heap.from_offset(offset - cached_span); } @@ -547,7 +1212,7 @@ uint32_t __stdcall ApuMapVirtualAddress(void* virtualAddress) { return kApuBaseAddress + g_cached_heap.to_offset(virtualAddress); } if (g_noncached_heap.contains(virtualAddress)) { - return kApuBaseAddress + static_cast(g_cached_heap.size) + + return kApuBaseAddress + static_cast(align_apu_region(g_cached_heap.size)) + g_noncached_heap.to_offset(virtualAddress); } return 0; diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp index bd93f70405..be2c6f1e1a 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp @@ -6,13 +6,44 @@ #include +#include +#include #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; +static std::atomic fail_worker_allocation{false}; +static std::atomic count_worker_allocations{false}; +static std::atomic worker_allocations{0}; +static DWORD test_thread_id; +void* operator new(std::size_t size) { + if (allocations_before_failure == 0) { + allocations_before_failure = -1; + throw std::bad_alloc(); + } + if (fail_worker_allocation.load() && GetCurrentThreadId() != test_thread_id && + fail_worker_allocation.exchange(false)) { + throw std::bad_alloc(); + } + if (count_worker_allocations.load() && GetCurrentThreadId() != test_thread_id) { + worker_allocations.fetch_add(1, std::memory_order_relaxed); + } + 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**); @@ -66,9 +97,62 @@ static_assert(sizeof(TestShapeContexts) == 120, "TestShapeContexts is 120 bytes" static_assert(offsetof(TestShapeContexts, xmaContextArray) == 0x38, "xmaContextArray is at offset +0x38"); +struct XmaWords { + uint32_t* data; + + std::atomic_ref operator[](std::size_t index) const { + return std::atomic_ref(data[index]); + } +}; + +// Synthetic XMA2 with one nonzero spectral coefficient per channel and frame. +void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip, + uint32_t rate_index = 3, bool stereo = false) { + constexpr uint32_t scale_bands[] = {23, 24, 23, 23}; + const uint32_t bands = scale_bands[rate_index]; + const uint32_t channels = stereo ? 2u : 1u; + const uint32_t frame_bits = stereo ? 90 + 2 * bands : 59 + bands; + 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. + if (stereo) put(0, 1); // No optional decorrelation matrix. + put(0, 11); // Gain, trim, fill and subframe error flag. + if (stereo) put(0b010u, 3); // Two channels without decorrelation. + put((1u << channels) - 1, channels); // Coefficients are present in each channel. + put(1, 1); // Explicit vector coefficient count. + put(0, 8 * channels); // Use only run/level coding. + put(0, 6); // Quantizer adjustment. + if (stereo) put(0, 5); // No per-channel quantizer modifiers. + for (uint32_t channel = 0; channel < channels; ++channel) { + put(0, 2); // Scale factor step. + put((1u << bands) - 1, bands); // One zero delta per scale band. + } + for (uint32_t channel = 0; channel < channels; ++channel) { + put(0, 1); // Run/level table 0. + put(0b00u, 2); // Run 0, level 1. + put(channel == 0 ? 1u : 0u, 1); + put(0b0101011u, 7); // End of coefficients. + } + put(0, 1); // Frame padding bit. + put(frame + 1 < frames ? 1 : 0, 1); + } +} + } // namespace -int main() { +int main(int argc, char** argv) { + std::setvbuf(stdout, nullptr, _IONBF, 0); + test_thread_id = GetCurrentThreadId(); std::printf("acphal_test: registered acphal.dll shim verification\n"); const auto create = reinterpret_cast( @@ -107,18 +191,44 @@ int main() { return 1; } + // Heap configuration is process-wide, so CTest exercises this mode separately. + if (argc == 2 && std::strcmp(argv[1], "--noncached-only") == 0) { + check(create_heap(0, 0x6000u) == S_OK, "Create only the non-cached APU heap"); + void* noncached = nullptr; + uint32_t noncached_address = 0; + check(alloc(&noncached, &noncached_address, 0x1000, 0x800, 2) == S_OK && noncached != nullptr, + "Allocate from the non-cached heap"); + void* cached = noncached; + uint32_t cached_address = noncached_address; + check(alloc(&cached, &cached_address, 0x1000, 0x800, 1) == E_OUTOFMEMORY && + cached == nullptr && cached_address == 0, + "A missing cached heap stays unavailable after explicit configuration"); + check(map_apu(noncached_address) == noncached && map_virtual(noncached) == noncached_address, + "A failed cached allocation leaves the non-cached mapping unchanged"); + free_mem(noncached); + std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); + return g_failures != 0; + } + // 1. AcpHalCreate void* acp = nullptr; check(create(&acp) == S_OK && acp != nullptr, "AcpHalCreate returns S_OK with a non-null object"); check(create(nullptr) == E_POINTER, "AcpHalCreate(nullptr) returns E_POINTER"); + void* failed_hal = acp; + allocations_before_failure = 0; + const HRESULT create_failure = create(&failed_hal); + allocations_before_failure = -1; + check(create_failure == E_OUTOFMEMORY && failed_hal == nullptr, + "AcpHalCreate returns E_OUTOFMEMORY and clears the output"); if (acp) { using Slot0Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); using Slot1Fn = HRESULT(__stdcall*)(void*); - using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, const void*, uint32_t); - using Slot3Fn = uint32_t(__stdcall*)(void*); + using Slot2Fn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); + using Slot3Fn = uint32_t(__stdcall*)(void*, void*); + using Slot4Fn = uint32_t(__stdcall*)(void*); using Slot5Fn = HRESULT(__stdcall*)(void*); auto vtable = *static_cast(acp); @@ -139,8 +249,8 @@ int main() { "IAcpHal slot 2 (submit_command) returns S_OK (vital boot unblocker)"); // Slots 3 and 4: Message polling returns 0 - check(reinterpret_cast(vtable[3])(acp) == 0, "IAcpHal slot 3 returns 0"); - check(reinterpret_cast(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0"); + check(reinterpret_cast(vtable[3])(acp, nullptr) == 0, "IAcpHal slot 3 returns 0"); + check(reinterpret_cast(vtable[4])(acp) == 0, "IAcpHal slot 4 returns 0"); // Slot 1: Disconnect returns S_OK check(reinterpret_cast(vtable[1])(acp) == S_OK, "IAcpHal slot 1 returns S_OK"); @@ -150,8 +260,8 @@ int main() { } // 2. ApuCreateHeap: title passes (cachedSize, nonCachedSize=0x226e00) - check(create_heap(4 * 1024 * 1024, 0x226e00) == S_OK, - "ApuCreateHeap(4 MiB, 0x226e00) succeeds"); + check(create_heap(4 * 1024 * 1024 + 0x400, 0x226e00) == S_OK, + "ApuCreateHeap succeeds with an unaligned cached heap size"); check(create_heap(4 * 1024 * 1024, 0x226e00) != S_OK, "ApuCreateHeap second call fails (heap already created)"); @@ -252,11 +362,513 @@ 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 + std::memset(&ctx_all, 0x55, sizeof(ctx_all)); check(release_ctx(&ctx_all) == S_OK, "AcpHalReleaseShapeContexts succeeds"); - check(ctx_all.xmaContextArray == nullptr, "xmaContextArray is reset to null"); + const auto* released_argument = reinterpret_cast(&ctx_all); + check(std::all_of(released_argument, released_argument + sizeof(ctx_all), + [](uint8_t b) { return b == 0x55; }), + "SHAPE release does not write through an opaque or recycled argument"); check(release_ctx(nullptr) == S_OK, "AcpHalReleaseShapeContexts(nullptr) succeeds"); + // 7. ACP command/message queue protocol (register, complete, overflow drops, disconnect, notify word) + { + #pragma pack(push, 1) + struct TestAcpMessage { + uint32_t kind; + uint32_t dropped; + uint32_t usec; + uint8_t data[16]; + }; + #pragma pack(pop) + static_assert(sizeof(TestAcpMessage) == 28, "ACP message is 28 bytes"); + + using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); + using DisconnectFn = HRESULT(__stdcall*)(void*); + using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); + using PopFn = uint32_t(__stdcall*)(void*, TestAcpMessage*); + using CountFn = uint32_t(__stdcall*)(void*); + using ReleaseFn = HRESULT(__stdcall*)(void*); + + void* q_acp = nullptr; + check(create(&q_acp) == S_OK && q_acp != nullptr, "AcpHalCreate for queue test"); + auto vt = *static_cast(q_acp); + const auto fn_connect = reinterpret_cast(vt[0]); + const auto fn_disconnect = reinterpret_cast(vt[1]); + const auto fn_submit = reinterpret_cast(vt[2]); + const auto fn_pop = reinterpret_cast(vt[3]); + const auto fn_count = reinterpret_cast(vt[4]); + const auto fn_release = reinterpret_cast(vt[5]); + + check(fn_connect(q_acp, 0, 16) == E_INVALIDARG, "Connect(commands=0) returns E_INVALIDARG"); + check(fn_disconnect(q_acp) == E_FAIL, "Disconnect before Connect returns E_FAIL"); + check(fn_connect(q_acp, 16, 2) == S_OK, "Connect(16, 2) succeeds"); + + // Allocate a 4-byte notification word in APU memory. + void* notify_va = nullptr; + uint32_t notify_apu = 0; + check(alloc(¬ify_va, ¬ify_apu, 16, 16, 1) == S_OK && notify_va != nullptr, + "ApuAlloc notification word succeeds"); + *static_cast(notify_va) = 0; + + const uint32_t reg_mask = 0x92u; // FLOWGRAPH_COMPLETED(0x02) | COMMAND_COMPLETED(0x10) | DISCONNECTED(0x80) + check(fn_submit(q_acp, 2, 0x1122334455667788ull, 0xffffffffu, ®_mask, notify_apu) == S_OK, + "REGISTER_MESSAGES with id and notify word succeeds"); + check(*static_cast(notify_va) == 1u, + "SubmitCommand writes 1 to APU notification word"); + check(fn_count(q_acp) == 1u, "COMMAND_COMPLETED queued after REGISTER_MESSAGES"); + + TestAcpMessage msg{}; + check(fn_pop(q_acp, &msg) == 1u, "PopMessage retrieves COMMAND_COMPLETED"); + uint32_t ack_cmd = 0; + uint64_t ack_id = 0; + std::memcpy(&ack_cmd, msg.data, 4); + std::memcpy(&ack_id, msg.data + 4, 8); + check(msg.kind == 0x10u && msg.dropped == 0u && ack_cmd == 2u && ack_id == 0x1122334455667788ull, + "COMMAND_COMPLETED payload carries command id and 64-bit token"); + + // Overflow queue of capacity 2 with 4 commands -> 2 dropped, reported on the 5th. + for (uint64_t tok = 1; tok <= 4; ++tok) { + check(fn_submit(q_acp, 12, tok, 0xffffffffu, nullptr, 0) == S_OK, + "SubmitCommand during overflow succeeds"); + } + check(fn_count(q_acp) == 2u, "Message queue caps at capacity 2"); + check(fn_pop(q_acp, &msg) == 1u && fn_pop(q_acp, &msg) == 1u, + "Drained the 2 queued messages"); + check(fn_submit(q_acp, 12, 5, 0xffffffffu, nullptr, 0) == S_OK, + "SubmitCommand 5 after drain succeeds"); + check(fn_pop(q_acp, &msg) == 1u && msg.dropped == 2u, + "Next queued message reports dropped == 2"); + + // LOAD_FLOWGRAPH posts FLOWGRAPH_COMPLETED carrying word(1). + const uint32_t fg_cfg[2] = {0, 0x42u}; + check(fn_submit(q_acp, 1, 0, 0xffffffffu, fg_cfg, 0) == S_OK, "LOAD_FLOWGRAPH succeeds"); + check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x02u, "FLOWGRAPH_COMPLETED queued"); + uint32_t fg_id = 0; + std::memcpy(&fg_id, msg.data, 4); + check(fg_id == 0x42u, "FLOWGRAPH_COMPLETED carries flowgraph word"); + + const uint32_t command_completed_mask = 0x10u; + check(fn_submit(q_acp, 3, 0x100u, 0xffffffffu, &command_completed_mask, 0) == S_OK && + fn_count(q_acp) == 0u, + "UNREGISTER_MESSAGES suppresses command-completed messages"); + + // Disconnect posts DISCONNECTED. + check(fn_disconnect(q_acp) == S_OK, "Disconnect succeeds when connected"); + check(fn_count(q_acp) == 1u, "Disconnect queued DISCONNECTED message"); + check(fn_pop(q_acp, &msg) == 1u && msg.kind == 0x80u, "Popped DISCONNECTED message"); + + free_mem(notify_va); + check(fn_release(q_acp) == S_OK, "Release queue AcpHal succeeds"); + } + + // 8. End-to-end XMA2 context ring decoding via background decoder thread + { + // Two synthetic XMA2 packets with three mono frames each. Each frame + // transmits one positive spectral coefficient so decoded PCM differs from fallback silence. + TestShapeContexts xma_ctx{}; + xma_ctx.numXmaContexts = 4; + check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr, + "Allocate 4 XMA SHAPE contexts"); + + void* in_va = nullptr; + 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"); + 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; + check(alloc(&out_va, &out_apu, 0x400, 0x100, 2) == S_OK && out_va != nullptr, + "ApuAlloc 4-block XMA2 output ring"); + std::memset(out_va, 0x55, 0x400); + + // Configure voice index 1: 2 packets in input 0, input 0 valid, 4 output blocks, + // writable = 1, 48 kHz mono, read_bit = 32. + const XmaWords words{static_cast(xma_ctx.xmaContextArray) + 16}; + words[0] = 2u | (1u << 20) | (4u << 22); + words[1] = (1u << 31) | (3u << 27); + words[2] = 32u; + words[5] = in_apu; + words[7] = out_apu; + + using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); + using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); + using ReleaseFn = HRESULT(__stdcall*)(void*); + + void* x_acp = nullptr; + check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for XMA decode test"); + auto vt = *static_cast(x_acp); + const auto fn_connect = reinterpret_cast(vt[0]); + const auto fn_submit = reinterpret_cast(vt[2]); + const auto fn_release = reinterpret_cast(vt[5]); + + check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA decode test"); + + // ENABLE_XMA (cmd 5) on voice 1. + const uint32_t enable_arg = 1u; + worker_allocations.store(0); + count_worker_allocations.store(true); + check(fn_submit(x_acp, 5, 0xf1, 0xffffffffu, &enable_arg, 0) == S_OK, + "ENABLE_XMA voice 1 succeeds"); + + // Wait up to 500 ms for the background decoder thread to fill the 4-block ring. + for (int wait = 0; wait < 500 && ((words[1] >> 31) & 1u) == 1u; ++wait) { + Sleep(1); + } + const bool ring_full = (words[1] >> 31) == 0u; + check(ring_full, "Background XMA2 decoder fills ring and clears writable flag"); + check(((words[0] >> 27) & 0x1Fu) == 0u, + "Write block wrapped back to 0 after filling 4 blocks"); + + const auto* ring_bytes = static_cast(out_va); +#if defined(LEONIDA_HAVE_XMA2_DECODER) + check(ring_full && std::any_of(ring_bytes, ring_bytes + 0x400, + [](uint8_t b) { return b != 0 && b != 0x55; }), + "The Rust decoder writes non-silent PCM"); +#else + check(ring_full && std::all_of(ring_bytes, ring_bytes + 0x400, [](uint8_t b) { return b == 0; }), + "The fallback writes silence"); +#endif + + // Advance read pointer 4 blocks at a time until input exhausts and INPUT_INVALID fires. + const uint32_t advance_args[2] = {1u, 4u}; + int written_blocks = ring_full ? 4 : 0; + bool advanced = true; + for (int step = 0; step < 6; ++step) { + advanced &= fn_submit(x_acp, 18, 0xf2 + static_cast(step), + 0xffffffffu, advance_args, 0) == S_OK; + // Wait until either ring fills again (writable == 0) or stream hits error bit. + for (int wait = 0; wait < 200; ++wait) { + const uint32_t w1 = words[1]; + const uint32_t w2 = words[2]; + if (((w1 >> 31) & 1u) == 0u || ((w2 >> 31) & 1u) == 1u) break; + Sleep(1); + } + if (((words[2] >> 31) & 1u) == 1u && ((words[1] >> 31) & 1u) == 1u) { + break; + } + if ((words[1] >> 31) != 0u) break; + written_blocks += 4; + } + check(advanced, "ADVANCE_XMA_READ succeeds"); + check(written_blocks == 24, "Six frames write exactly 24 blocks before input exhaustion"); + count_worker_allocations.store(false); + const unsigned allocation_count = worker_allocations.load(); + std::printf("C++ worker allocations for six PCM frames: %u\n", allocation_count); + check(allocation_count > 0 && allocation_count < 16, + "PCM storage is reused across packets instead of allocating per sample block"); + check(((words[0] >> 20) & 3u) == 0u, "XMA input buffer valid bits cleared on exhaustion"); + check(((words[2] >> 31) & 1u) == 1u, "XMA error flag set on exhaustion"); + check(((words[2] >> 26) & 0x1Fu) == 4u, "XMA error status is INPUT_INVALID (4)"); + + // DISABLE_XMA (cmd 7) on voice 1. + const uint32_t disable_arg = 1u; + check(fn_submit(x_acp, 7, 0xf9, 0xffffffffu, &disable_arg, 0) == S_OK, + "DISABLE_XMA voice 1 succeeds"); + check(fn_release(x_acp) == S_OK, "Release XMA AcpHal succeeds"); + free_mem(in_va); + free_mem(out_va); + check(release_ctx(&xma_ctx) == S_OK, "Release XMA SHAPE contexts joins decoder cleanly"); + } + + // 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. + { + TestShapeContexts xma_ctx{}; + xma_ctx.numXmaContexts = 4; + check(alloc_ctx(&xma_ctx) == S_OK && xma_ctx.xmaContextArray != nullptr, + "Allocate 4 XMA SHAPE contexts for the packet loop test"); + + void* in_va = nullptr; + uint32_t in_apu = 0; + check(alloc(&in_va, &in_apu, 0x2000, 0x800, 2) == S_OK && in_va != nullptr && + (in_apu & 0x7FFu) == 0 && map_apu(in_apu) == in_va, + "Non-cached XMA input keeps its requested alignment and round trips"); + 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; + check(alloc(&out_va, &out_apu, 0x1000, 0x100, 2) == S_OK && out_va != nullptr, + "ApuAlloc 16-block loop output ring"); + + // Voice index 2. + const XmaWords words{static_cast(xma_ctx.xmaContextArray) + 32}; + + using ConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); + using SubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); + using ReleaseFn = HRESULT(__stdcall*)(void*); + + void* x_acp = nullptr; + check(create(&x_acp) == S_OK && x_acp != nullptr, "AcpHalCreate for packet loop test"); + auto vt = *static_cast(x_acp); + const auto fn_connect = reinterpret_cast(vt[0]); + const auto fn_submit = reinterpret_cast(vt[2]); + const auto fn_release = reinterpret_cast(vt[5]); + check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for packet loop test"); + + auto configure_voice = [&](uint32_t loops, uint32_t input_0_packets, uint32_t ring_size, + uint32_t write, uint32_t read) { + std::memset(out_va, 0x55, 0x1000); + const uint32_t input_1_packets = 3u - input_0_packets; + words[0] = input_0_packets | (loops << 12) | + ((input_1_packets != 0 ? 3u : 1u) << 20) | (ring_size << 22) | (write << 27); + words[1] = (1u << 31) | (3u << 27) | input_1_packets; + words[2] = 32u; // read at packet 0 + words[3] = 32u; // loop start: packet 0 + words[4] = 100u; // loop end: packet 0 + words[5] = in_apu; + words[6] = in_apu + input_0_packets * 2048u; + words[7] = out_apu; + words[9] = read; + }; + + 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, + 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; + for (; wait < 1000 && ((words[2] >> 31) & 1u) == 0u; ++wait) { + Sleep(1); + } + const int blocks = ((words[2] >> 31) & 1u) != 0u + ? static_cast((words[0] >> 27) & 0x1Fu) + : -1; + check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK, + "DISABLE_XMA voice 2 succeeds"); + return blocks; + }; + + 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, + "A skip to the end of input 0 continues at input 1"); + check(run_blocks(0, 1) == 8, + "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, + "Enable infinite loop with out-of-range ring indices"); + for (int wait = 0; wait < 1000 && (words[1] >> 31) != 0u; ++wait) Sleep(1); + check((words[1] >> 31) == 0u && ((words[0] >> 27) & 0x1Fu) == 1u, + "Ring stops at the normalized read index"); + 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"); + 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"); + + words[0] = 3u << 22; // three ring blocks + words[9] = 2u; + const uint32_t advance_args[2] = {2u, UINT32_MAX}; + 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"); + TestShapeContexts source_only{}; + source_only.numSrcContexts = 1; + check(alloc_ctx(&source_only) == S_OK && source_only.srcContextArray != nullptr, + "A non-XMA allocation can coexist with the active XMA table"); + 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"); + + // Both sides were empty. When both are refilled, the title's first input wins. + write_xma_packet(packets, 1, 0); + configure_voice(0, 3, 4, 0, 0); + words[0] = 1u | (1u << 20) | (4u << 22); + const uint32_t voice_bit = 1u << voice_index; + check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring(), + "ENABLE_XMAS starts the selected voice and exhausts the first input"); + write_xma_packet(packets, 2, 0); + write_xma_packet(packets + 0x800, 1, 0); + words[6] = in_apu + 0x800u; + words[1].fetch_or(1u); + words[0].fetch_or(3u << 20); + check(fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK && wait_for_ring(), + "A double refill supplies the next PCM blocks"); + check(((words[0] >> 20) & 3u) == 2u && (words[4] >> 31) == 1u, + "A double refill plays input 0 before input 1"); +#if defined(LEONIDA_HAVE_XMA2_DECODER) + check(has_signal(ring_bytes), "Rust decodes non-silent PCM after a double refill"); +#endif + + check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK, + "Reset the voice before exhausting both inputs"); + write_xma_packet(packets, 1, 0); + write_xma_packet(packets + 0x800, 1, 0); + configure_voice(0, 1, 8, 0, 0); + words[1] = (words[1] & ~0xFFFu) | 1u; + check(fn_submit(x_acp, 6, 0, 0xffffffffu, &voice_bit, 0) == S_OK && wait_for_ring() && + ((words[0] >> 20) & 3u) == 0u, + "The voice exhausts input 0 and then input 1"); + write_xma_packet(packets, 2, 0); + words[0].fetch_or(3u << 20); + const uint32_t full_ring[2] = {voice_index, 8}; + check(fn_submit(x_acp, 18, 0, 0xffffffffu, full_ring, 0) == S_OK && wait_for_ring() && + ((words[0] >> 20) & 3u) == 2u, + "A double refill plays input 0 first even after exhausting input 1"); + + // Reconfigure the still-enabled slot and verify that no queued PCM or old format survives. + bool reconfigured = true; + for (uint32_t rate = 0; rate < 4; ++rate) { + const bool stereo = (rate & 1u) == 0; + write_xma_packet(packets, 1, 0, rate, stereo); + words[0] = 1u | (1u << 20) | (16u << 22); + words[2] = 32u; + words[4] = 0u; + words[9] = 12u; + std::memset(out_va, 0, 0x1000); + // Enable applies the new format before making the output writable. + words[1] = ((rate | (stereo ? 4u : 0u)) << 27); + reconfigured &= fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK; + reconfigured &= fn_submit(x_acp, 18, 0, 0xffffffffu, refill_read_args, 0) == S_OK; + for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1); + reconfigured &= (words[2] >> 31) == 1u && ((words[0] >> 27) & 0x1Fu) == (stereo ? 8u : 4u); +#if defined(LEONIDA_HAVE_XMA2_DECODER) + reconfigured &= has_signal(ring_bytes); +#endif + } + check(reconfigured, "Re-enabled voices select mono or stereo PCM at all four sample rates"); + check(fn_submit(x_acp, 8, 0, 0xffffffffu, &voice_bit, 0) == S_OK, + "DISABLE_XMAS stops the selected voice"); + + configure_voice(0, 3, 4, 0, 0); + write_xma_packet(packets, 1, 1); + fail_worker_allocation.store(true); + check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK, + "Enable a voice before an injected worker allocation failure"); + for (int wait = 0; wait < 1000 && (words[2] >> 31) == 0u; ++wait) Sleep(1); + check(!fail_worker_allocation.exchange(false) && (words[2] >> 31) != 0u, + "Worker allocation failure surfaces an XMA error without terminating the process"); + check(fn_submit(x_acp, 5, 0, 0xffffffffu, &voice_index, 0) == S_OK && wait_for_ring(), + "A voice can run again after a worker allocation failure"); + + 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); + check(release_ctx(&xma_ctx) == S_OK, "Release packet loop SHAPE contexts"); + } + + // 9. ENABLE_XMA racing SHAPE allocation and release, including concurrent releases. + { + using RaceConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t); + using RaceSubmitFn = HRESULT(__stdcall*)(void*, uint32_t, uint64_t, uint32_t, const void*, uint32_t); + using RaceReleaseFn = HRESULT(__stdcall*)(void*); + + void* race_acp = nullptr; + check(create(&race_acp) == S_OK && race_acp != nullptr, "AcpHalCreate for XMA race test"); + auto race_vt = *static_cast(race_acp); + const auto race_connect = reinterpret_cast(race_vt[0]); + const auto race_submit = reinterpret_cast(race_vt[2]); + const auto race_release = reinterpret_cast(race_vt[5]); + check(race_connect(race_acp, 0x1000, 0x1000) == S_OK, "Connect for XMA race test"); + + constexpr int kRaceIterations = 20000; + std::atomic bind_failures{0}; + std::thread enabler([&]() { + const uint32_t enable_arg = 1u; + for (int i = 0; i < kRaceIterations; ++i) { + race_submit(race_acp, 5, 0xe000u + static_cast(i), 0xffffffffu, + &enable_arg, 0); + } + }); + std::thread releaser([&]() { + for (int i = 0; i < kRaceIterations; ++i) { + if (release_ctx(nullptr) != S_OK) ++bind_failures; + } + }); + for (int i = 0; i < kRaceIterations; ++i) { + TestShapeContexts race_ctx{}; + race_ctx.numXmaContexts = 4; + if (alloc_ctx(&race_ctx) != S_OK) ++bind_failures; + if (release_ctx(&race_ctx) != S_OK) ++bind_failures; + } + enabler.join(); + releaser.join(); + check(bind_failures == 0, "20000 bind/release cycles race ENABLE_XMA and independent releases"); + check(race_release(race_acp) == S_OK, "Release race AcpHal succeeds"); + } + std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/xma_decoder/README.md b/runtime/xma_decoder/README.md index 4a6d5fb103..9db8018104 100644 --- a/runtime/xma_decoder/README.md +++ b/runtime/xma_decoder/README.md @@ -6,8 +6,6 @@ Each decoder handle serializes decode calls. The returned PCM block owns its sam The tests build packets in memory; they do not open or contain audio fixtures. The synthetic C++ smoke test verifies the exported ABI and ownership boundary. -This PR adds the decoder boundary only; the Windows XAudio2 engine/source-voice adapter is a follow-up stage. - Run: ```powershell @@ -17,3 +15,12 @@ cargo build --manifest-path runtime/xma_decoder/Cargo.toml --locked ``` The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_32, userenv, and ntdll for Rust's Windows standard library. + +## Use in the runtime + +`runtime/CMakeLists.txt` builds this crate for `x86_64-pc-windows-msvc` at configure time when `cargo` is on `PATH` and links it into `gta6rt` and `acphal_test` with `LEONIDA_HAVE_XMA2_DECODER` defined. The first build fetches the pinned `xma` git dependency. Set `CARGO_NET_OFFLINE=true` for a configure that uses only the local Cargo cache. + +`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/leonida_xma2_decoder.h b/runtime/xma_decoder/leonida_xma2_decoder.h index 98dd5c49c5..a4c5b45344 100644 --- a/runtime/xma_decoder/leonida_xma2_decoder.h +++ b/runtime/xma_decoder/leonida_xma2_decoder.h @@ -25,6 +25,10 @@ enum LeonidaXma2Status { int32_t leonida_xma2_decoder_create(uint32_t sample_rate, uint32_t channels, LeonidaXma2Decoder **out_decoder); +/* 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. */ +int32_t leonida_xma2_decoder_create_hardware(uint32_t sample_rate, uint32_t channels, + LeonidaXma2Decoder **out_decoder); int32_t leonida_xma2_decode_buffer(LeonidaXma2Decoder *decoder, const uint8_t *input, size_t input_len, LeonidaXma2PcmBlock **out_block); diff --git a/runtime/xma_decoder/src/lib.rs b/runtime/xma_decoder/src/lib.rs index 1b435a0ce6..69fedf49e0 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, @@ -87,7 +109,8 @@ pub unsafe extern "C" fn leonida_xma2_decoder_create( /// 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. @@ -160,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() { @@ -232,6 +255,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(); diff --git a/runtime/xma_decoder/tests/ffi_contract.rs b/runtime/xma_decoder/tests/ffi_contract.rs index 0eb8e5cf4c..6e6185c394 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!( diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 8bd74d1cf1..d575b42004 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -78,7 +78,7 @@ $build || exit /b 1 } else { # Keep this list in step with runtime\CMakeLists.txt. Optional parts that need a dependency are left out here: # the GameInput shim (SDL3), so controllers go through the host's GameInput.dll, if any, as without the shim. - Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3). Install CMake + Ninja or VS's CMake tools component to get it." + Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3) and without the Rust XMA2 decoder (XMA voices are silent). Install CMake + Ninja or VS's CMake tools component to get it." $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } diff --git a/third_party/xma/NOTICE.md b/third_party/xma/NOTICE.md index 1e21768294..760e6c77d6 100644 --- a/third_party/xma/NOTICE.md +++ b/third_party/xma/NOTICE.md @@ -10,3 +10,5 @@ The upstream NOTICE identifies this package as a Rust port of FFmpeg's WMA Pro/X > This file is part of FFmpeg and is licensed under the GNU Lesser General Public License, version 2.1 or later. Leonida's C ABI wrapper is independently written and licensed under GPL-3.0-or-later. No upstream implementation source is copied or vendored. + +When the Cargo build succeeds, `runtime/CMakeLists.txt` links the decoder and its `xma` dependency statically into `gta6rt` and `acphal_test`. The wrapper source is in `runtime/xma_decoder`. The pinned dependency source is available from the commit linked above.