From 4750df6a06e68c05343c5895f1d6dcddf61e38c3 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 01:44:00 -0300 Subject: [PATCH 1/9] acphal: add portable XMA2 decoder, ACP message queue, and SHAPE XMA worker - Add portable C++20 XMA2 packet parser and WMA Pro frame decoder (runtime/src/xma2_decoder.{h,cpp}, following FFmpeg wmaprodec.c / wmaprodata.h LGPL-2.1-or-later under Leonida's GPL-3.0-or-later) with cross-platform xma2_decoder_test. - Implement IAcpHal command/message queue protocol (REGISTER_MESSAGES, UNREGISTER_MESSAGES, LOAD_FLOWGRAPH, COMMAND_COMPLETED, DISCONNECTED, queue-full dropped counters, and APU notification word writes) in runtime/shims/acphal.cpp. - Wire a lazily-started, cleanly-joined background XMA2 decoder thread pumping enabled SHAPE_XMA_CONTEXT output rings in APU memory. --- runtime/CMakeLists.txt | 11 +- runtime/shims/acphal.cpp | 693 ++++++++++++++++-- runtime/src/xma2_decoder.cpp | 1094 ++++++++++++++++++++++++++++ runtime/src/xma2_decoder.h | 116 +++ runtime/test/acphal_test.cpp | 205 ++++++ runtime/test/xma2_decoder_test.cpp | 178 +++++ scripts/build_runtime.ps1 | 2 +- 7 files changed, 2241 insertions(+), 58 deletions(-) create mode 100644 runtime/src/xma2_decoder.cpp create mode 100644 runtime/src/xma2_decoder.h create mode 100644 runtime/test/xma2_decoder_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..e64748c1f5 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -110,6 +110,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) src/main.cpp src/host_cpu.cpp src/pe_loader.cpp + src/xma2_decoder.cpp shims/registry.cpp shims/file_system.cpp shims/winhttp_offline.cpp @@ -243,9 +244,10 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) add_executable(acphal_test test/acphal_test.cpp shims/acphal.cpp + src/xma2_decoder.cpp shims/registry.cpp ) - target_include_directories(acphal_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_include_directories(acphal_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims ${CMAKE_CURRENT_SOURCE_DIR}/src) target_compile_definitions(acphal_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) target_compile_options(acphal_test PRIVATE /W4 /permissive- /utf-8) target_link_options(acphal_test PRIVATE /OPT:NOREF) @@ -553,6 +555,13 @@ if(BUILD_TESTING) add_test(NAME vulkan_device_filter COMMAND vulkan_device_filter_test) add_executable(vk_presenter_capture_colour_test test/vk_presenter_capture_colour_test.cpp) add_test(NAME vk_presenter_capture_colour COMMAND vk_presenter_capture_colour_test) + # Portable XMA2 packet parser and WMA Pro frame decoder (src/xma2_decoder.cpp): pure stdlib, no GPU. + add_executable(xma2_decoder_test test/xma2_decoder_test.cpp src/xma2_decoder.cpp) + target_include_directories(xma2_decoder_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + if(MSVC) + target_compile_options(xma2_decoder_test PRIVATE /W4 /permissive- /utf-8) + endif() + add_test(NAME xma2_decoder COMMAND xma2_decoder_test) if(TARGET gta6rt) if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") add_executable(cpp_unwind_test test/cpp_unwind_test.cpp) diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp index 5ead016d63..c1d375c1c1 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,31 @@ #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" +#include "../src/xma2_decoder.h" namespace { @@ -241,6 +253,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; @@ -283,46 +302,596 @@ ApuRegion g_noncached_heap; // Tracked SHAPE context arrays std::vector g_active_shape_arrays; +// 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 = 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). + +constexpr std::size_t kXmaBlockBytes = 256; +constexpr std::size_t kXmaSamplesPerBlock = kXmaBlockBytes / 2; +constexpr uint32_t kXmaErrorInputInvalid = 4; + +struct XmaContextView { + volatile uint32_t* words = nullptr; + + uint32_t get(std::size_t index) const { return words[index]; } + void set(std::size_t index, uint32_t value) const { words[index] = value; } + + 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; + } + + void 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; + set(index, (get(index) & ~mask) | ((value << shift) & mask)); + } + + std::size_t channels() const { return 1u + static_cast(field(1, 29, 1)); } +}; + +struct XmaVoice { + std::optional decoder; + std::deque pcm; + std::size_t skip = 0; // samples per channel to drop (start/loop subframe skip) + bool ended = false; + std::size_t produced = 0; + uint32_t frames = 0; + uint32_t bad_frames = 0; + int16_t peak = 0; +}; + +struct XmaVoiceSlot { + std::mutex mutex; + std::optional voice; +}; + +class XmaEngine { +public: + ~XmaEngine() { unbind(); } + + void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) { + stop_worker(); + std::unique_lock lock(table_mutex_); + array_ = reinterpret_cast(array); + voices_.clear(); + voices_.reserve(count); + for (uint32_t i = 0; i < count; ++i) { + voices_.push_back(std::make_unique()); + } + active_count_.store(0, std::memory_order_relaxed); + } + + void unbind() { + stop_worker(); + std::unique_lock lock(table_mutex_); + array_ = nullptr; + voices_.clear(); + active_count_.store(0, std::memory_order_relaxed); + } + + 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); + const bool was_active = voices_[index]->voice.has_value(); + // 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)) * + leonida::xma2::kSubframeSamples; + voices_[index]->voice.emplace(std::move(voice)); + if (!was_active) { + active_count_.fetch_add(1, std::memory_order_relaxed); + } + } + ensure_worker_and_wake(); + } + + 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) { + bool wake = false; + { + std::shared_lock table_lock(table_mutex_); + XmaContextView ctx = context_locked(index); + if (!ctx.words) return; + + std::lock_guard slot_lock(voices_[index]->mutex); + const uint32_t raw_size = ctx.field(0, 22, 5); + const uint32_t size = raw_size ? raw_size : 1u; + const uint32_t read = (ctx.field(9, 0, 5) + blocks) % 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_ + static_cast(index) * 16}; + } + + static bool decode_one_frame(XmaContextView ctx, XmaVoice& voice) { + if (voice.ended) return false; + + const std::size_t channels = ctx.channels(); + uint32_t current = ctx.field(4, 31, 1); + const uint32_t valid = ctx.field(0, 20, 2); + + if ((valid & (1u << current)) == 0) { + const uint32_t other = 1u - current; + if ((valid & (1u << other)) == 0) { + // Both inputs exhausted: flush remaining overlap tail, then signal INPUT_INVALID. + if (voice.decoder.has_value()) { + std::vector tail; + voice.decoder->flush(tail); + voice.pcm.insert(voice.pcm.end(), tail.begin(), tail.end()); + } + voice.ended = true; + ctx.set_field(2, 26, 5, kXmaErrorInputInvalid); + ctx.set_field(2, 31, 1, 1); + return !voice.pcm.empty(); + } + current = other; + ctx.set_field(4, 31, 1, current); + ctx.set_field(2, 0, 26, 0); + } + + const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6); + const uint32_t packets = (current == 0) ? ctx.field(0, 0, 12) : ctx.field(1, 0, 12); + const std::size_t input_bytes = + static_cast(packets) * leonida::xma2::kPacketBytes; + const uint8_t* data = apu_span(address & ~0x7FFu, input_bytes); + if (!data) { + ctx.set_field(0, 20 + current, 1, 0); + return true; + } + + std::size_t at = static_cast(ctx.field(2, 0, 26)); + if (at < leonida::xma2::kHeaderBits) { + const auto pkt = leonida::xma2::parse_packet(data, input_bytes, 0); + at = leonida::xma2::kHeaderBits + (pkt.has_value() ? pkt->first_frame_bit : 0u); + } + + const auto frame = leonida::xma2::read_frame(data, input_bytes, at); + if (!frame.has_value()) { + ctx.set_field(0, 20 + current, 1, 0); + return true; + } + + if (!voice.decoder.has_value()) { + static constexpr uint32_t kRates[4] = {24000, 32000, 44100, 48000}; + const uint32_t rate_idx = ctx.field(1, 27, 2) & 3u; + voice.decoder.emplace(channels, kRates[rate_idx]); + } + + std::vector pcm; + pcm.reserve(leonida::xma2::kFrameSamples * channels); + ++voice.frames; + if (!voice.decoder->decode(frame->data.data(), frame->bits, pcm)) { + ++voice.bad_frames; + } + + std::size_t next = frame->next.value_or(0); + const uint32_t loops = ctx.field(0, 12, 8); + const std::size_t loop_end = static_cast(ctx.field(4, 0, 26)); + const bool ends_loop = + loop_end != 0 && + (frame->start == loop_end || + (frame->start < loop_end && (!frame->next.has_value() || loop_end < *frame->next))); + if (loops > 0 && ends_loop) { + const std::size_t keep = + (static_cast(ctx.field(1, 12, 2)) + 1u) * + leonida::xma2::kSubframeSamples * channels; + if (keep < pcm.size()) pcm.resize(keep); + next = static_cast(ctx.field(3, 0, 26)); + voice.skip = static_cast(ctx.field(1, 17, 3)) * + leonida::xma2::kSubframeSamples; + if (loops != 255u) { + ctx.set_field(0, 12, 8, loops - 1u); + } + } + + const std::size_t skip_samples = std::min(voice.skip * channels, pcm.size()); + voice.skip -= skip_samples / channels; + voice.pcm.insert(voice.pcm.end(), pcm.begin() + static_cast(skip_samples), + pcm.end()); + + if (next == 0) { + ctx.set_field(0, 20 + current, 1, 0); + } + ctx.set_field(2, 0, 26, static_cast(next)); + return true; + } + + static void pump_voice(XmaContextView ctx, XmaVoice& voice) { + const uint32_t size = ctx.field(0, 22, 5); + if (size == 0) return; + + while (ctx.field(1, 31, 1) == 1) { + int decode_guard = 0; + while (voice.pcm.size() < kXmaSamplesPerBlock && decode_guard++ < 16) { + if (!decode_one_frame(ctx, voice)) break; + } + if (voice.pcm.empty()) return; + + const uint32_t write = ctx.field(0, 27, 5); + const uint32_t out_addr = + ctx.get(7) + write * static_cast(kXmaBlockBytes); + uint8_t* out = apu_span(out_addr, kXmaBlockBytes); + if (!out) return; + + for (std::size_t i = 0; i < kXmaSamplesPerBlock; ++i) { + int16_t sample = 0; + if (!voice.pcm.empty()) { + sample = voice.pcm.front(); + voice.pcm.pop_front(); + } + const int32_t mag = + (sample == INT16_MIN) ? INT16_MAX : std::abs(static_cast(sample)); + if (mag > voice.peak) voice.peak = static_cast(mag); + const uint16_t raw = static_cast(sample); + out[2 * i] = static_cast(raw & 0xFFu); + out[2 * i + 1] = static_cast((raw >> 8) & 0xFFu); + } + + voice.produced += kXmaSamplesPerBlock / ctx.channels(); + const uint32_t next_write = (write + 1u) % size; + ctx.set_field(0, 27, 5, next_write); + if (next_write == ctx.field(9, 0, 5)) { + 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); + if (voices_[i]->voice.has_value()) { + pump_voice(context_locked(static_cast(i)), *voices_[i]->voice); + } + } + } + + void ensure_worker_and_wake() { + std::lock_guard lock(worker_mutex_); + if (!worker_.joinable()) { + stopping_ = false; + worker_ = std::thread([this]() { worker_loop(); }); + } + wake_requested_ = true; + worker_cv_.notify_one(); + } + + void stop_worker() { + std::thread to_join; + { + std::lock_guard lock(worker_mutex_); + if (!worker_.joinable()) return; + stopping_ = true; + wake_requested_ = true; + worker_cv_.notify_one(); + to_join = std::move(worker_); + } + if (to_join.joinable()) to_join.join(); + } + + void worker_loop() { + for (;;) { + { + std::unique_lock lock(worker_mutex_); + if (stopping_) return; + if (active_count_.load(std::memory_order_relaxed) == 0 && !wake_requested_) { + worker_cv_.wait(lock, [this]() { return stopping_ || wake_requested_; }); + if (stopping_) return; + } + wake_requested_ = false; + } + + pump_all(); + + std::unique_lock lock(worker_mutex_); + if (stopping_) 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, std::chrono::milliseconds(2), + [this]() { return stopping_ || wake_requested_; }); + } + } + } + + mutable std::shared_mutex table_mutex_; + volatile uint32_t* array_ = nullptr; + std::vector> voices_; + std::atomic active_count_{0}; + + std::mutex worker_mutex_; + std::condition_variable worker_cv_; + std::thread worker_; + bool stopping_ = false; + 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_; + dropped_ = 0; + msg.usec = static_cast(elapsed_usec_locked()); + if (payload && len > 0) { + std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data))); + } + messages_.push_back(msg); + } + // 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 { + (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; } - // 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; @@ -343,36 +912,45 @@ HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { if (!ctx) return E_POINTER; - std::lock_guard lock(g_apu_mutex); + SHAPE_XMA_CONTEXT* xma_array = nullptr; + uint32_t xma_count = 0; + { + std::lock_guard lock(g_apu_mutex); + + 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); + 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}; + + xma_array = ctx->xmaContextArray; + xma_count = ctx->numXmaContexts; + } - 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); - 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(xma_array, xma_count); trace_call("AcpHalAllocateShapeContexts", ",\"src\":" + std::to_string(ctx->numSrcContexts) + @@ -384,6 +962,9 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { // ---- AcpHalReleaseShapeContexts ---- HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { + // Stop and detach the XMA worker before freeing backing arrays. + g_xma_engine.unbind(); + std::lock_guard lock(g_apu_mutex); // Free all recorded context allocations @@ -439,8 +1020,8 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes, // ---- 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) { if (!virtualAddress) return E_POINTER; *virtualAddress = nullptr; if (physicalAddress) *physicalAddress = 0; diff --git a/runtime/src/xma2_decoder.cpp b/runtime/src/xma2_decoder.cpp new file mode 100644 index 0000000000..a257c873a1 --- /dev/null +++ b/runtime/src/xma2_decoder.cpp @@ -0,0 +1,1094 @@ +// Portable XMA2 packet parser and WMA Pro frame decoder. +// +// Canonical Huffman / run-level tables and decoding structure follow FFmpeg's libavcodec/wmaprodec.c and +// libavcodec/wmaprodata.h (LGPL-2.1-or-later, used under GPL-3.0-or-later), specialized for Xbox XMA2 streams +// (1–2 channels, 512-sample frames, 128/256/512 subframes, 2048-byte packets). +#include "xma2_decoder.h" + +#include +#include +#include +#include +#include + +namespace leonida::xma2 { +namespace { + +constexpr std::uint32_t kLengthBits = 15; +constexpr double kPi = 3.14159265358979323846264338327950288; + +struct SymLen { + std::uint16_t sym; + std::uint8_t len; +}; + +// Critical band cutoff frequencies (Hz) and canonical VLC tables from FFmpeg libavcodec/wmaprodata.h. +constexpr std::uint16_t kCriticalFreq[28] = { + 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, + 2700, 3150, 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500, 20675, 28575, 41375, 63875, +}; + +constexpr SymLen kScaleTable[121] = { + {58, 5}, {64, 6}, {66, 7}, {65, 7}, {62, 5}, {63, 6}, {68, 9}, {69, 10}, {54, 15}, {19, 19}, {20, 19}, + {21, 19}, {22, 19}, {23, 19}, {24, 19}, {25, 19}, {26, 19}, {27, 19}, {28, 19}, {29, 19}, {30, 19}, {31, 19}, + {32, 19}, {33, 19}, {34, 19}, {17, 19}, {36, 19}, {37, 19}, {38, 19}, {39, 19}, {40, 19}, {41, 19}, {42, 19}, + {43, 19}, {44, 19}, {45, 19}, {46, 19}, {47, 19}, {48, 19}, {49, 19}, {50, 19}, {51, 19}, {52, 19}, {15, 19}, + {16, 19}, {14, 19}, {13, 19}, {12, 19}, {11, 19}, {10, 19}, {0, 19}, {9, 19}, {8, 19}, {7, 19}, {6, 19}, + {5, 19}, {4, 19}, {55, 13}, {70, 13}, {3, 19}, {2, 19}, {1, 19}, {35, 19}, {71, 19}, {72, 19}, {73, 19}, + {74, 19}, {75, 19}, {76, 19}, {77, 19}, {78, 19}, {79, 19}, {80, 19}, {81, 19}, {82, 19}, {83, 19}, {84, 19}, + {85, 19}, {86, 19}, {87, 19}, {88, 19}, {89, 19}, {90, 19}, {91, 19}, {92, 19}, {93, 19}, {94, 19}, {95, 19}, + {96, 19}, {97, 19}, {98, 19}, {99, 19}, {100, 19},{101, 19},{102, 19},{103, 19},{104, 19},{105, 19},{106, 19}, + {107, 19},{108, 19},{109, 19},{110, 19},{111, 19},{112, 19},{113, 19},{114, 19},{115, 19},{116, 19},{117, 19}, + {118, 19},{119, 19},{120, 19},{18, 18}, {53, 16}, {56, 11}, {57, 8}, {67, 7}, {61, 3}, {59, 2}, {60, 1}, +}; + +constexpr SymLen kScaleRlTable[120] = { + {103, 7}, {80, 11}, {60, 11}, {18, 10}, {56, 10}, {21, 12}, {90, 12}, {58, 11}, {27, 11}, {69, 12}, {84, 15}, + {48, 15}, {86, 14}, {47, 13}, {19, 10}, {32, 9}, {78, 6}, {5, 5}, {28, 4}, {53, 5}, {9, 7}, {31, 8}, + {38, 8}, {10, 7}, {88, 11}, {25, 12}, {105, 12},{118, 11},{23, 12}, {82, 14}, {98, 16}, {110, 16},{108, 15}, + {93, 13}, {68, 10}, {72, 12}, {97, 12}, {81, 12}, {42, 12}, {64, 8}, {4, 4}, {1, 2}, {7, 6}, {14, 7}, + {0, 9}, {55, 9}, {61, 9}, {117, 10},{24, 12}, {44, 12}, {67, 12}, {70, 16}, {99, 18}, {96, 21}, {95, 21}, + {2, 21}, {77, 21}, {52, 21}, {111, 21},{102, 20},{101, 17},{46, 15}, {73, 15}, {109, 15},{51, 14}, {92, 14}, + {30, 7}, {11, 7}, {66, 7}, {15, 8}, {16, 8}, {116, 9}, {65, 9}, {57, 10}, {59, 10}, {115, 9}, {12, 7}, + {35, 9}, {17, 9}, {41, 9}, {20, 11}, {91, 11}, {26, 12}, {75, 15}, {45, 15}, {107, 14},{83, 14}, {100, 15}, + {89, 15}, {43, 11}, {62, 9}, {37, 9}, {104, 8}, {6, 5}, {39, 8}, {40, 9}, {34, 9}, {79, 7}, {8, 6}, + {63, 6}, {87, 12}, {94, 14}, {49, 14}, {50, 13}, {22, 11}, {119, 10},{33, 9}, {36, 9}, {113, 11},{106, 12}, + {112, 13},{71, 15}, {85, 15}, {74, 14}, {76, 10}, {114, 7}, {29, 5}, {54, 6}, {13, 6}, {3, 2}, +}; + +constexpr std::uint8_t kScaleRlRun[120] = { + 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, + 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, + 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 0, 1, 0, 1, +}; + +constexpr std::uint8_t kScaleRlLevel[120] = { + 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, +}; + +constexpr std::uint8_t kCoef0Lens[272] = { + 2, 9, 14, 14, 13, 12, 13, 14, 15, 15, 12, 10, 10, 10, 13, 14, 15, 15, 12, 11, 13, 14, 14, 13, + 15, 15, 14, 12, 12, 8, 10, 10, 15, 15, 14, 13, 14, 14, 13, 15, 20, 20, 19, 21, 21, 20, 19, 17, + 17, 18, 18, 15, 15, 13, 12, 14, 15, 15, 14, 15, 15, 12, 11, 6, 7, 8, 9, 13, 13, 13, 14, 14, + 11, 10, 7, 8, 14, 14, 14, 14, 12, 13, 13, 12, 12, 12, 11, 9, 13, 14, 14, 12, 11, 11, 11, 9, + 8, 7, 14, 15, 15, 14, 14, 12, 13, 15, 16, 17, 17, 14, 12, 12, 12, 15, 15, 14, 14, 14, 13, 13, + 9, 9, 11, 11, 10, 7, 6, 13, 15, 15, 14, 14, 14, 13, 14, 15, 15, 13, 14, 14, 14, 14, 10, 9, + 10, 10, 11, 11, 10, 8, 9, 13, 14, 14, 12, 11, 14, 15, 15, 13, 12, 14, 14, 14, 14, 13, 14, 14, + 3, 5, 8, 10, 10, 15, 15, 14, 14, 16, 16, 15, 12, 11, 11, 11, 7, 8, 8, 9, 12, 13, 13, 12, + 14, 15, 15, 13, 10, 11, 11, 13, 14, 14, 13, 14, 14, 11, 10, 13, 15, 15, 14, 12, 11, 4, 6, 6, + 8, 12, 12, 12, 13, 13, 12, 13, 13, 14, 14, 13, 13, 13, 9, 7, 9, 11, 14, 14, 13, 14, 14, 13, + 10, 8, 7, 5, 9, 12, 13, 14, 15, 15, 12, 12, 10, 14, 14, 13, 12, 13, 14, 14, 12, 13, 13, 12, + 12, 12, 9, 7, 6, 3, 4, 4, +}; + +constexpr std::uint16_t kCoef0Syms[272] = { + 2, 25, 111, 94, 69, 58, 87, 93, 136, 135, 59, 37, 34, 36, 82, 182, 120, 138, 195, 45, 168, 216, 178, + 86, 140, 219, 186, 162, 239, 18, 156, 35, 127, 236, 109, 85, 180, 253, 88, 147, 268, 264, 256, 266, 270, 262, + 260, 248, 246, 252, 258, 137, 189, 230, 64, 179, 146, 208, 101, 118, 238, 163, 46, 9, 153, 0, 26, 247, 169, + 76, 202, 131, 194, 38, 13, 19, 132, 106, 191, 97, 65, 198, 77, 62, 66, 164, 48, 27, 81, 183, 102, 60, + 47, 49, 159, 227, 20, 14, 112, 263, 144, 217, 104, 63, 79, 209, 269, 250, 254, 203, 241, 196, 61, 220, 148, + 124, 185, 100, 80, 78, 193, 28, 50, 235, 41, 1, 10, 171, 226, 150, 103, 114, 115, 170, 105, 211, 149, 249, + 108, 188, 107, 255, 231, 155, 42, 40, 55, 160, 39, 21, 29, 215, 234, 184, 228, 51, 116, 142, 145, 172, 165, + 181, 130, 113, 117, 89, 128, 204, 3, 7, 154, 157, 43, 141, 265, 133, 225, 271, 244, 221, 74, 54, 56, 52, + 15, 222, 22, 30, 83, 199, 173, 73, 123, 210, 143, 175, 44, 53, 237, 174, 139, 134, 110, 218, 129, 161, 213, + 177, 267, 151, 125, 67, 223, 5, 11, 192, 23, 214, 243, 166, 200, 176, 68, 224, 187, 257, 261, 232, 96, 251, + 31, 16, 32, 57, 207, 121, 91, 126, 119, 99, 158, 24, 212, 8, 33, 70, 92, 205, 240, 242, 75, 197, 233, + 259, 190, 98, 71, 201, 122, 206, 72, 90, 95, 84, 167, 245, 229, 17, 12, 4, 152, 6, +}; + +constexpr SymLen kCoef1Table[244] = { + {2, 2}, {3, 3}, {102, 3}, {4, 4}, {148, 6}, {134, 9}, {171, 10},{18, 10}, {11, 8}, {159, 8}, {14, 9}, + {156, 14},{235, 15},{61, 15}, {38, 13}, {153, 13},{48, 14}, {49, 14}, {23, 11}, {203, 13},{208, 19},{204, 19}, + {129, 18},{94, 17}, {87, 16}, {62, 15}, {174, 15},{147, 15},{29, 12}, {191, 12},{64, 15}, {65, 15}, {146, 14}, + {164, 13},{142, 5}, {132, 4}, {103, 5}, {154, 7}, {165, 9}, {181, 11},{109, 12},{30, 12}, {86, 16}, {92, 16}, + {239, 15},{138, 14},{39, 13}, {50, 14}, {115, 15},{238, 21},{228, 21},{236, 21},{222, 21},{216, 20},{226, 20}, + {196, 18},{192, 17},{120, 16},{221, 14},{51, 14}, {24, 11}, {143, 8}, {7, 6}, {9, 7}, {152, 10},{136, 12}, + {160, 12},{241, 15},{66, 15}, {168, 14},{219, 14},{113, 14},{193, 12},{19, 10}, {173, 10},{105, 8}, {149, 9}, + {15, 9}, {205, 13},{207, 13},{125, 17},{190, 17},{182, 16},{68, 15}, {70, 15}, {67, 15}, {137, 13},{31, 12}, + {223, 14},{116, 15},{210, 19},{220, 19},{198, 18},{126, 17},{88, 16}, {41, 13}, {25, 11}, {40, 13}, {73, 15}, + {243, 15},{53, 14}, {195, 12},{183, 11},{225, 14},{52, 14}, {71, 15}, {121, 16},{89, 16}, {170, 14},{55, 14}, + {69, 15}, {83, 15}, {209, 13},{108, 11},{32, 12}, {54, 14}, {122, 16},{184, 16},{176, 15},{42, 13}, {12, 8}, + {161, 8}, {6, 5}, {167, 9}, {106, 9}, {20, 10}, {145, 12},{111, 13},{43, 13}, {26, 11}, {175, 10},{107, 10}, + {34, 12}, {33, 12}, {197, 12},{74, 15}, {128, 17},{232, 20},{212, 20},{224, 19},{202, 18},{90, 16}, {57, 14}, + {227, 14},{97, 16}, {93, 16}, {140, 15},{185, 11},{27, 11}, {16, 9}, {158, 11},{211, 13},{56, 14}, {117, 15}, + {72, 15}, {166, 13},{91, 16}, {95, 16}, {80, 15}, {101, 16},{194, 17},{127, 17},{82, 15}, {21, 10}, {144, 10}, + {177, 10},{151, 6}, {10, 7}, {157, 7}, {8, 6}, {5, 4}, {13, 8}, {0, 9}, {213, 13},{46, 13}, {199, 12}, + {35, 12}, {162, 12},{135, 10},{169, 9}, {45, 13}, {59, 14}, {114, 14},{44, 13}, {188, 16},{186, 16},{75, 15}, + {79, 15}, {118, 15},{187, 11},{112, 13},{139, 14},{178, 15},{81, 15}, {110, 12},{28, 11}, {163, 8}, {133, 6}, + {104, 6}, {17, 9}, {22, 10}, {229, 14},{172, 14},{217, 13},{201, 12},{36, 12}, {218, 20},{242, 22},{240, 22}, + {234, 21},{230, 19},{206, 18},{200, 18},{214, 18},{130, 17},{131, 17},{141, 15},{84, 15}, {76, 15}, {215, 13}, + {58, 14}, {231, 14},{233, 14},{180, 15},{77, 15}, {37, 12}, {189, 11},{179, 10},{155, 10},{47, 13}, {96, 16}, + {99, 16}, {119, 15},{63, 14}, {237, 14},{78, 15}, {85, 15}, {60, 14}, {98, 16}, {100, 16},{124, 16},{123, 16}, + {150, 11},{1, 7}, +}; + +constexpr std::uint16_t kCoef0Run[272] = { + 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, + 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, + 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, + 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, + 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 0, 1, 2, 3, 4, 5, 6, 7, 8, + 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, + 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, +}; + +constexpr float kCoef0Level[272] = { + 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, + 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, + 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, + 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, + 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 5.0f, 5.0f, + 5.0f, 5.0f, 5.0f, 6.0f, 6.0f, 7.0f, 7.0f, 8.0f, 8.0f, 9.0f, 9.0f, 10.0f, 10.0f, 11.0f, 11.0f, 12.0f, + 12.0f, 13.0f, 13.0f, 14.0f, 14.0f, 15.0f, 15.0f, 16.0f, 16.0f, 17.0f, 17.0f, 18.0f, 18.0f, 19.0f, 19.0f, 20.0f, + 20.0f, 21.0f, 21.0f, 22.0f, 22.0f, 23.0f, 23.0f, 24.0f, 24.0f, 25.0f, 25.0f, 26.0f, 26.0f, 27.0f, 27.0f, 28.0f, +}; + +constexpr std::uint16_t kCoef1Run[244] = { + 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, + 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, + 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 0, 1, 2, 3, 4, 5, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, +}; + +constexpr float kCoef1Level[244] = { + 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, + 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, + 2.0f, 2.0f, 2.0f, 2.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 4.0f, + 4.0f, 4.0f, 4.0f, 4.0f, 5.0f, 5.0f, 5.0f, 6.0f, 6.0f, 6.0f, 7.0f, 7.0f, 7.0f, 8.0f, 8.0f, 9.0f, + 9.0f, 10.0f, 10.0f, 11.0f, 11.0f, 12.0f, 12.0f, 13.0f, 13.0f, 14.0f, 14.0f, 15.0f, 15.0f, 16.0f, 16.0f, 17.0f, + 17.0f, 18.0f, 18.0f, 19.0f, 19.0f, 20.0f, 20.0f, 21.0f, 21.0f, 22.0f, 22.0f, 23.0f, 23.0f, 24.0f, 24.0f, 25.0f, + 25.0f, 26.0f, 26.0f, 27.0f, 27.0f, 28.0f, 28.0f, 29.0f, 29.0f, 30.0f, 30.0f, 31.0f, 31.0f, 32.0f, 32.0f, 33.0f, + 33.0f, 34.0f, 34.0f, 35.0f, 35.0f, 36.0f, 36.0f, 37.0f, 37.0f, 38.0f, 38.0f, 39.0f, 39.0f, 40.0f, 40.0f, 41.0f, + 41.0f, 42.0f, 42.0f, 43.0f, 43.0f, 44.0f, 44.0f, 45.0f, 45.0f, 46.0f, 46.0f, 47.0f, 47.0f, 48.0f, 48.0f, 49.0f, + 49.0f, 50.0f, 51.0f, 52.0f, +}; + +constexpr std::uint8_t kVec4Lens[127] = { + 1, 6, 8, 10, 10, 10, 10, 8, 8, 10, 10, 9, 8, 8, 9, 12, 12, 11, 12, 12, 11, 9, 9, 8, 8, 9, + 9, 8, 8, 9, 9, 12, 12, 12, 14, 14, 13, 11, 11, 9, 8, 9, 9, 11, 11, 10, 9, 8, 6, 6, 6, 6, + 6, 6, 11, 11, 10, 11, 11, 10, 10, 11, 11, 9, 7, 6, 7, 7, 6, 6, 6, 5, 7, 11, 11, 10, 9, 8, + 6, 9, 9, 10, 10, 9, 8, 8, 6, 6, 6, 8, 8, 9, 12, 12, 11, 10, 8, 8, 8, 10, 10, 10, 10, 9, + 9, 8, 10, 11, 11, 9, 8, 8, 8, 9, 9, 10, 11, 12, 12, 9, 9, 9, 8, 8, 7, 7, 7, +}; + +constexpr std::uint16_t kVec4Syms[127] = { + 0, 4370, 275, 8195, 4146, 12545, 8225, 290, 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, + 5121, 8961, 321, 1041, 51, 4641, 546, 4610, 530, 513, 8451, 4385, 4130, 33, 8211, 5, + 66, 4161, 1281, 81, 6, 801, 8196, 8481, 8449, 4611, 531, 561, 769, 12290, 8226, 19, + 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, 12305, 49, 12321, 260, 4100, 516, 21, 12546, + 8466, 4353, 4371, 4626, 257, 18, 17, 1, 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, + 276, 50, 785, 4116, 8209, 4099, 273, 4113, 258, 259, 4609, 35, 1026, 1025, 16401, 305, + 34, 529, 289, 770, 12289, 4, 4145, 4356, 12306, 8193, 12801, 261, 16386, 4881, 3, 514, + 4129, 545, 306, 36, 4101, 65, 20481, 786, 4401, 4866, 8721, 291, 8450, 8465, 4115, +}; + +constexpr SymLen kVec2Table[137] = { + {19, 5}, {165, 10},{211, 11},{46, 11}, {75, 10}, {177, 11},{12, 11}, {86, 8}, {83, 7}, {38, 7}, {133, 9}, + {178, 10},{28, 10}, {104, 9}, {73, 9}, {35, 5}, {52, 6}, {113, 9}, {8, 9}, {101, 8}, {69, 7}, {0, 3}, + {71, 8}, {119, 9}, {91, 10}, {179, 10},{114, 8}, {166, 10},{10, 10}, {44, 10}, {145, 10},{66, 6}, {21, 6}, + {24, 8}, {146, 9}, {26, 9}, {65, 7}, {5, 7}, {226, 11},{225, 12},{15, 12}, {180, 10},{147, 9}, {115, 8}, + {40, 8}, {89, 9}, {134, 9}, {84, 7}, {54, 7}, {42, 9}, {60, 10}, {31, 11}, {193, 11},{181, 10},{76, 10}, + {148, 9}, {37, 6}, {67, 6}, {33, 6}, {3, 6}, {17, 6}, {2, 6}, {102, 8}, {87, 8}, {116, 8}, {56, 8}, + {50, 5}, {20, 5}, {120, 9}, {58, 9}, {29, 10}, {194, 10},{135, 9}, {97, 8}, {7, 8}, {105, 9}, {13, 11}, + {241, 12},{16, 12}, {45, 10}, {149, 9}, {74, 9}, {98, 7}, {23, 7}, {85, 7}, {70, 7}, {195, 10},{161, 10}, + {129, 9}, {72, 8}, {51, 5}, {36, 5}, {117, 8}, {61, 10}, {11, 10}, {162, 9}, {1, 7}, {4, 6}, {49, 6}, + {68, 6}, {9, 9}, {27, 9}, {130, 8}, {39, 7}, {53, 6}, {99, 7}, {25, 8}, {150, 9}, {90, 9}, {103, 8}, + {163, 9}, {196, 10},{210, 10},{136, 9}, {121, 9}, {41, 8}, {131, 8}, {43, 9}, {164, 9}, {118, 8}, {88, 8}, + {81, 7}, {6, 7}, {55, 7}, {59, 9}, {30, 10}, {209, 11},{14, 11}, {151, 9}, {106, 9}, {82, 6}, {22, 6}, + {100, 7}, {132, 8}, {57, 8}, {18, 4}, {34, 4}, +}; + +constexpr SymLen kVec1Table[101] = { + {7, 5}, {32, 8}, {59, 10}, {60, 10}, {83, 11}, {82, 11}, {62, 10}, {33, 8}, {45, 9}, {61, 10}, {84, 11}, + {85, 11}, {1, 6}, {13, 5}, {19, 6}, {25, 7}, {34, 8}, {46, 9}, {47, 9}, {14, 5}, {6, 5}, {64, 10}, + {87, 11}, {86, 11}, {63, 10}, {88, 11}, {90, 11}, {35, 8}, {26, 7}, {0, 7}, {48, 9}, {65, 10}, {66, 10}, + {36, 8}, {15, 5}, {20, 6}, {91, 11}, {89, 11}, {67, 10}, {49, 9}, {50, 9}, {69, 10}, {92, 11}, {93, 11}, + {27, 7}, {5, 5}, {37, 8}, {68, 10}, {71, 10}, {51, 9}, {52, 9}, {70, 10}, {94, 11}, {96, 11}, {38, 8}, + {21, 6}, {16, 5}, {4, 5}, {28, 7}, {53, 9}, {95, 11}, {97, 11}, {73, 10}, {39, 8}, {29, 7}, {72, 10}, + {98, 11}, {99, 11}, {54, 9}, {40, 8}, {22, 6}, {30, 7}, {55, 9}, {74, 10}, {76, 10}, {56, 9}, {75, 10}, + {77, 10}, {17, 5}, {3, 5}, {23, 6}, {41, 8}, {57, 9}, {78, 10}, {79, 10}, {31, 7}, {10, 4}, {9, 4}, + {100, 5}, {2, 5}, {11, 4}, {8, 4}, {18, 5}, {42, 8}, {58, 9}, {80, 10}, {81, 10}, {43, 8}, {44, 8}, + {24, 6}, {12, 4}, +}; + +std::uint32_t floor_log2(std::size_t v) { + const std::size_t clamped = std::max(v, 1u); + return static_cast(std::bit_width(clamped) - 1u); +} + +struct PacketCursor { + const std::uint8_t* data; + std::size_t size; + std::size_t pos; + + bool read_bit(std::uint32_t& out) { + if ((pos % kPacketBits) == 0) { + const std::size_t prev = pos / kPacketBits; + if (prev > 0) { + const auto hdr = parse_packet(data, size, prev - 1); + if (!hdr) return false; + pos = (prev + static_cast(hdr->skip)) * kPacketBits; + } + pos += kHeaderBits; + } + const std::size_t byte_idx = pos / 8; + if (byte_idx >= size) return false; + out = static_cast((data[byte_idx] >> (7u - (pos % 8u))) & 1u); + ++pos; + return true; + } + + bool read_bits(std::uint32_t n, std::uint32_t& out) { + std::uint32_t v = 0; + for (std::uint32_t i = 0; i < n; ++i) { + std::uint32_t b = 0; + if (!read_bit(b)) return false; + v = (v << 1) | b; + } + out = v; + return true; + } +}; + +std::optional find_next_frame(const std::uint8_t* data, std::size_t size, std::size_t start, + std::size_t end) { + const std::size_t index = start / kPacketBits; + const auto header = parse_packet(data, size, index); + if (!header) return std::nullopt; + + std::size_t at = index * kPacketBits + kHeaderBits + static_cast(header->first_frame_bit); + std::uint32_t number = 0; + while (at < start) { + PacketCursor cur{data, size, at}; + std::uint32_t bits = 0; + if (!cur.read_bits(kLengthBits, bits) || bits <= kLengthBits) return std::nullopt; + at += static_cast(bits); + ++number; + } + const bool last = (number + 1u) >= header->frames; + if ((end % kPacketBits) == 0 || (last && (end / kPacketBits) == index)) { + const std::size_t end_pkt = (end - 1u) / kPacketBits; + const auto end_hdr = parse_packet(data, size, end_pkt); + if (!end_hdr) return std::nullopt; + const std::size_t next_pkt = end_pkt + 1u + static_cast(end_hdr->skip); + const auto next_hdr = parse_packet(data, size, next_pkt); + if (!next_hdr) return std::nullopt; + end = next_pkt * kPacketBits + kHeaderBits + static_cast(next_hdr->first_frame_bit); + } + if ((end / 8u) >= size) return std::nullopt; + return end; +} + +struct VlcEntry { + std::uint32_t code; + std::uint8_t len; + std::int32_t symbol; +}; + +struct Vlc { + std::vector codes; + + template + static Vlc build(std::size_t count, Fn&& get_sym_len) { + Vlc vlc; + vlc.codes.reserve(count); + std::uint64_t code = 0; + for (std::size_t i = 0; i < count; ++i) { + const auto [sym, len] = get_sym_len(i); + vlc.codes.push_back({static_cast(code), len, sym}); + code += (1ull << (32u - len)); + } + return vlc; + } + + std::int32_t read(std::uint32_t peek32, std::size_t& pos) const { + const auto it = std::upper_bound(codes.begin(), codes.end(), peek32, + [](std::uint32_t val, const VlcEntry& e) { return val < e.code; }); + const std::size_t idx = (it == codes.begin()) ? 0u : static_cast((it - codes.begin()) - 1); + pos += codes[idx].len; + return codes[idx].symbol; + } +}; + +struct CodeTables { + Vlc scale; + Vlc scale_rl; + Vlc coef[2]; + Vlc vec4; + Vlc vec2; + Vlc vec1; +}; + +const CodeTables& code_tables() { + static const CodeTables tables = [] { + CodeTables t; + t.scale = Vlc::build(std::size(kScaleTable), [](std::size_t i) { + return std::pair{static_cast(kScaleTable[i].sym) - 60, + kScaleTable[i].len}; + }); + t.scale_rl = Vlc::build(std::size(kScaleRlTable), [](std::size_t i) { + return std::pair{static_cast(kScaleRlTable[i].sym), + kScaleRlTable[i].len}; + }); + t.coef[0] = Vlc::build(std::size(kCoef0Syms), [](std::size_t i) { + return std::pair{static_cast(kCoef0Syms[i]), kCoef0Lens[i]}; + }); + t.coef[1] = Vlc::build(std::size(kCoef1Table), [](std::size_t i) { + return std::pair{static_cast(kCoef1Table[i].sym), + kCoef1Table[i].len}; + }); + t.vec4 = Vlc::build(std::size(kVec4Syms), [](std::size_t i) { + return std::pair{static_cast(kVec4Syms[i]) - 1, kVec4Lens[i]}; + }); + t.vec2 = Vlc::build(std::size(kVec2Table), [](std::size_t i) { + return std::pair{static_cast(kVec2Table[i].sym) - 1, + kVec2Table[i].len}; + }); + t.vec1 = Vlc::build(std::size(kVec1Table), [](std::size_t i) { + return std::pair{static_cast(kVec1Table[i].sym), + kVec1Table[i].len}; + }); + return t; + }(); + return tables; +} + +void fft_radix2(std::vector& re, std::vector& im) { + const std::size_t n = re.size(); + std::size_t j = 0; + for (std::size_t i = 1; i < n; ++i) { + std::size_t bit = n >> 1; + while ((j & bit) != 0) { + j ^= bit; + bit >>= 1; + } + j |= bit; + if (i < j) { + std::swap(re[i], re[j]); + std::swap(im[i], im[j]); + } + } + for (std::size_t len = 2; len <= n; len <<= 1) { + const double ang = -2.0 * kPi / static_cast(len); + const double wc = std::cos(ang); + const double ws = std::sin(ang); + for (std::size_t start = 0; start < n; start += len) { + double cr = 1.0; + double ci = 0.0; + for (std::size_t k = 0; k < len / 2; ++k) { + const std::size_t a = start + k; + const std::size_t b = a + len / 2; + const double tr = re[b] * cr - im[b] * ci; + const double ti = re[b] * ci + im[b] * cr; + re[b] = re[a] - tr; + im[b] = im[a] - ti; + re[a] += tr; + im[a] += ti; + const double next_cr = cr * wc - ci * ws; + const double next_ci = cr * ws + ci * wc; + cr = next_cr; + ci = next_ci; + } + } + } +} + +std::vector make_sine_window(std::size_t n) { + std::vector w(n); + for (std::size_t i = 0; i < n; ++i) { + w[i] = static_cast(std::sin((static_cast(i) + 0.5) * kPi / (2.0 * static_cast(n)))); + } + return w; +} + +std::int16_t float_to_i16(float v) { + const float scaled = std::round(v * 32768.0f); + const float clamped = std::clamp(scaled, -32768.0f, 32767.0f); + return static_cast(clamped); +} + +} // namespace + +struct Decoder::Bits { + const std::uint8_t* data; + std::size_t byte_len; + std::size_t pos; + std::size_t end; + + std::uint32_t peek32() const { + std::uint64_t v = 0; + const std::size_t byte = pos / 8u; + for (std::size_t i = 0; i < 5u; ++i) { + const std::uint8_t b = (byte + i < byte_len) ? data[byte + i] : 0u; + v = (v << 8) | static_cast(b); + } + return static_cast((v << (24u + (pos % 8u))) >> 32u); + } + + std::uint32_t read(std::uint32_t n) { + if (n == 0) return 0; + const std::uint32_t v = peek32() >> (32u - n); + pos += static_cast(n); + return v; + } + + bool bit() { return read(1) != 0; } + + std::int32_t read_signed(std::uint32_t n) { + const std::uint32_t u = read(n); + return static_cast(u << (32u - n)) >> static_cast(32u - n); + } + + std::int32_t read_vlc(const Vlc& vlc) { return vlc.read(peek32(), pos); } + + std::uint32_t large_value() { + std::uint32_t n = 8; + if (bit()) { + n += 8; + if (bit()) { + n += 8; + if (bit()) n += 7; + } + } + return read(n); + } + + bool overread() const { return pos > end; } +}; + +std::optional parse_packet(const std::uint8_t* data, std::size_t size, std::size_t packet_index) { + if (!data || packet_index > std::numeric_limits::max() / kPacketBytes) return std::nullopt; + const std::size_t start = packet_index * kPacketBytes; + if (start > size || (size - start) < 4u) return std::nullopt; + const std::uint32_t h = (static_cast(data[start]) << 24) | + (static_cast(data[start + 1]) << 16) | + (static_cast(data[start + 2]) << 8) | + static_cast(data[start + 3]); + return PacketHeader{h >> 26, (h >> 11) & 0x7fffu, h & 0xffu}; +} + +std::optional read_frame(const std::uint8_t* data, std::size_t size, std::size_t start_bit) { + if (!data || size == 0) return std::nullopt; + PacketCursor probe{data, size, start_bit}; + std::uint32_t bits_u32 = 0; + if (!probe.read_bits(kLengthBits, bits_u32)) return std::nullopt; + const std::size_t bits = static_cast(bits_u32); + if (bits <= kLengthBits || bits == 0x7fffu) return std::nullopt; + + std::vector out((bits + 7u) / 8u, 0u); + PacketCursor cur{data, size, start_bit}; + for (std::size_t i = 0; i < bits; ++i) { + std::uint32_t b = 0; + if (!cur.read_bit(b)) return std::nullopt; + out[i / 8u] |= static_cast(b << (7u - (i % 8u))); + } + const std::size_t end = cur.pos; + return FrameBits{std::move(out), bits, start_bit, find_next_frame(data, size, start_bit, end)}; +} + +void imdct_half(const float* input, float* output, std::size_t n, float scale) { + const std::size_t m = n / 2u; + std::vector re(m, 0.0); + std::vector im(m, 0.0); + for (std::size_t k = 0; k < m; ++k) { + const double a = static_cast(input[2u * k]); + const double b = static_cast(input[n - 1u - 2u * k]); + const double ang = -kPi * static_cast(k) / static_cast(n); + const double c = std::cos(ang); + const double s = std::sin(ang); + re[k] = a * c - b * s; + im[k] = a * s + b * c; + } + fft_radix2(re, im); + for (std::size_t k = 0; k < m; ++k) { + const double ang = -kPi * static_cast(4u * k + 1u) / static_cast(4u * n); + const double c = std::cos(ang); + const double s = std::sin(ang); + const double wr = re[k] * c - im[k] * s; + const double wi = re[k] * s + im[k] * c; + output[n - 1u - 2u * k] = static_cast(wr) * scale; + output[2u * k] = -static_cast(wi) * scale; + } +} + +void window_overlap(float* block, const float* window, std::size_t block_len) { + const std::size_t half = block_len / 2u; + for (std::size_t k = 0; k < half; ++k) { + const std::size_t i = k; + const std::size_t j = 2u * half - 1u - k; + const float s0 = block[i]; + const float s1 = block[j]; + const float wi = window[i]; + const float wj = window[j]; + block[i] = s0 * wj - s1 * wi; + block[j] = s0 * wi + s1 * wj; + } +} + +const std::vector& sine_window(std::size_t n) { + static const std::vector w128 = make_sine_window(128); + static const std::vector w256 = make_sine_window(256); + static const std::vector w512 = make_sine_window(512); + if (n == 128u) return w128; + if (n == 256u) return w256; + return w512; +} + +Decoder::Decoder(std::size_t channels, std::uint32_t sample_rate) : channels_(std::clamp(channels, 1u, 2u)) { + std::size_t rate = 24000u; + if (sample_rate > 44100u) rate = 48000u; + else if (sample_rate > 32000u) rate = 44100u; + else if (sample_rate > 24000u) rate = 32000u; + + for (std::size_t i = 0; i < kBlockSizes; ++i) { + const std::size_t sflen = kFrameSamples >> i; + auto& offsets = sfb_offsets_[i]; + offsets.fill(0); + std::size_t band = 1; + for (std::size_t f = 0; f < std::size(kCriticalFreq); ++f) { + if (offsets[band - 1u] >= sflen) break; + const std::size_t offset = (((sflen * 2u * static_cast(kCriticalFreq[f])) / rate) + 2u) & ~std::size_t(3u); + if (offset > offsets[band - 1u]) { + offsets[band] = offset; + ++band; + } + if (offset >= sflen) break; + } + offsets[band - 1u] = sflen; + num_sfb_[i] = band - 1u; + } + + for (std::size_t i = 0; i < kBlockSizes; ++i) { + for (std::size_t b = 0; b < num_sfb_[i]; ++b) { + const std::size_t offset = ((sfb_offsets_[i][b] + sfb_offsets_[i][b + 1u] - 1u) << i) >> 1u; + for (std::size_t x = 0; x < kBlockSizes; ++x) { + std::size_t v = 0; + while (v + 1u < kMaxBands && (sfb_offsets_[x][v + 1u] << x) < offset) ++v; + sf_offsets_[i][x][b] = v; + } + } + } + reset(); +} + +void Decoder::reset() { ch_ = {Channel{}, Channel{}}; } + +bool Decoder::decode(const std::uint8_t* data, std::size_t bits, std::vector& out, const char** error) { + const std::size_t byte_len = (bits + 7u) / 8u; + Bits b{data, byte_len, 0u, bits}; + const std::size_t len = static_cast(b.read(kLengthBits)); + const char* err = nullptr; + const bool ok = decode_frame(b, len, err); + if (!ok) { + if (error) *error = err ? err : "decode error"; + for (std::size_t c = 0; c < channels_; ++c) ch_[c].out.fill(0.0f); + } else if (error) { + *error = nullptr; + } + out.reserve(out.size() + kFrameSamples * channels_); + for (std::size_t i = 0; i < kFrameSamples; ++i) { + for (std::size_t c = 0; c < channels_; ++c) { + out.push_back(float_to_i16(ch_[c].out[i])); + } + } + for (std::size_t c = 0; c < channels_; ++c) { + std::copy(ch_[c].out.begin() + static_cast(kFrameSamples), ch_[c].out.end(), ch_[c].out.begin()); + } + return ok; +} + +void Decoder::flush(std::vector& out) { + out.reserve(out.size() + (kFrameSamples / 2u) * channels_); + for (std::size_t i = 0; i < kFrameSamples / 2u; ++i) { + for (std::size_t c = 0; c < channels_; ++c) { + out.push_back(float_to_i16(ch_[c].out[i])); + } + } + reset(); +} + +bool Decoder::decode_frame(Bits& b, std::size_t len, const char*& err) { + if (!decode_tile_header(b, err)) return false; + if (channels_ > 1u && b.bit() && b.bit()) { + b.read(static_cast(channels_ * channels_ * 4u)); + } + b.read(8); // dynamic range compression gain + if (b.bit()) { + if (b.bit()) b.read(floor_log2(kFrameSamples * 2u)); + if (b.bit()) b.read(floor_log2(kFrameSamples * 2u)); + } + parsed_all_subframes_ = false; + for (std::size_t c = 0; c < channels_; ++c) { + ch_[c].decoded_samples = 0; + ch_[c].cur_subframe = 0; + ch_[c].reuse_sf = false; + } + while (!parsed_all_subframes_) { + if (!decode_subframe(b, err)) return false; + } + if (b.overread() || b.pos > len) { + err = "frame overread"; + return false; + } + return true; +} + +bool Decoder::decode_subframe_length(Bits& b, std::size_t offset, std::size_t& out_len, const char*& err) const { + if (offset == kFrameSamples - kSubframeSamples) { + out_len = kSubframeSamples; + return true; + } + const std::uint32_t shift = b.bit() ? (1u + b.read(1)) : 0u; + const std::size_t len = kFrameSamples >> shift; + if (len < kSubframeSamples) { + err = "subframe length"; + return false; + } + out_len = len; + return true; +} + +bool Decoder::decode_tile_header(Bits& b, const char*& err) { + std::array num_samples{0, 0}; + std::array contains{false, false}; + std::size_t cur_channels = channels_; + std::size_t min_channel_len = 0; + for (std::size_t c = 0; c < channels_; ++c) ch_[c].num_subframes = 0; + const bool fixed = b.bit(); + for (;;) { + for (std::size_t c = 0; c < channels_; ++c) { + contains[c] = (num_samples[c] == min_channel_len) && + (fixed || cur_channels == 1u || min_channel_len == kFrameSamples - kSubframeSamples || b.bit()); + } + std::size_t sflen = 0; + if (!decode_subframe_length(b, min_channel_len, sflen, err)) return false; + min_channel_len += sflen; + for (std::size_t c = 0; c < channels_; ++c) { + auto& ch = ch_[c]; + if (contains[c]) { + if (ch.num_subframes >= kMaxSubframes) { + err = "too many subframes"; + return false; + } + ch.subframe_len[ch.num_subframes] = sflen; + num_samples[c] += sflen; + ++ch.num_subframes; + if (num_samples[c] > kFrameSamples) { + err = "channel longer than frame"; + return false; + } + } else if (num_samples[c] <= min_channel_len) { + if (num_samples[c] < min_channel_len) { + cur_channels = 0; + min_channel_len = num_samples[c]; + } + ++cur_channels; + } + } + if (min_channel_len >= kFrameSamples || b.overread()) break; + } + if (b.overread()) { + err = "tile header overread"; + return false; + } + return true; +} + +bool Decoder::decode_channel_transform(Bits& b, const char*& err) { + transform_ = false; + if (channels_ == 1u) return true; + if (b.bit()) { + err = "channel transform bit"; + return false; + } + if (channels_for_cur_subframe_ == 2u) { + if (b.bit()) { + if (b.bit()) { + err = "channel transform type"; + return false; + } + } else { + transform_ = true; + } + } + if (transform_) { + if (!b.bit()) { + for (std::size_t i = 0; i < num_bands_; ++i) transform_band_[i] = b.bit(); + } else { + transform_band_.fill(true); + } + } + return true; +} + +bool Decoder::decode_scale_factors(Bits& b, const char*& err) { + const auto& tables = code_tables(); + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + const std::size_t c = channel_indexes_[i]; + const auto& sf_off = sf_offsets_[table_idx_][ch_[c].table_idx]; + auto& ch = ch_[c]; + const std::size_t target = 1u - ch.scale_factor_idx; + ch.scale_factors = target; + if (ch.reuse_sf) { + const auto from = ch.saved_scale_factors[ch.scale_factor_idx]; + for (std::size_t band = 0; band < num_bands_; ++band) { + ch.saved_scale_factors[target][band] = from[sf_off[band]]; + } + } + if (ch.cur_subframe == 0u || b.bit()) { + if (!ch.reuse_sf) { + ch.scale_factor_step = static_cast(b.read(2)) + 1; + std::int32_t val = 45 / ch.scale_factor_step; + for (std::size_t band = 0; band < num_bands_; ++band) { + val += b.read_vlc(tables.scale); + ch.saved_scale_factors[target][band] = val; + } + } else { + std::size_t band = 0; + while (band < num_bands_) { + const std::int32_t idx = b.read_vlc(tables.scale_rl); + std::uint32_t skip = 0; + std::int32_t val = 0; + bool neg = false; + if (idx == 0) { + const std::uint32_t code = b.read(14); + skip = (code & 0x3fu) >> 1u; + val = static_cast(code >> 6u); + neg = (code & 1u) == 0u; + } else if (idx == 1) { + break; + } else { + skip = kScaleRlRun[static_cast(idx)]; + val = static_cast(kScaleRlLevel[static_cast(idx)]); + neg = !b.bit(); + } + band += static_cast(skip); + if (band >= num_bands_) { + err = "scale factor run"; + return false; + } + ch.saved_scale_factors[target][band] += neg ? -val : val; + ++band; + } + } + ch.scale_factor_idx = target; + ch.table_idx = table_idx_; + ch.reuse_sf = true; + } + std::int32_t max_sf = 0; + if (num_bands_ > 0u) { + max_sf = ch.saved_scale_factors[ch.scale_factors][0]; + for (std::size_t band = 1; band < num_bands_; ++band) { + max_sf = std::max(max_sf, ch.saved_scale_factors[ch.scale_factors][band]); + } + } + ch.max_scale_factor = max_sf; + } + return true; +} + +bool Decoder::decode_coefficients(Bits& b, std::size_t c, const char*& err) { + const auto& tables = code_tables(); + const std::size_t table = b.bit() ? 1u : 0u; + const std::uint16_t* run = (table == 1u) ? kCoef1Run : kCoef0Run; + const float* level = (table == 1u) ? kCoef1Level : kCoef0Level; + auto& ch = ch_[c]; + + bool rl_mode = false; + std::size_t cur = 0; + std::size_t num_zeros = 0; + while ((transmit_num_vec_coeffs_ || !rl_mode) && cur + 3u < ch.num_vec_coeffs) { + std::array vals{}; + const std::int32_t idx4 = b.read_vlc(tables.vec4); + if (idx4 < 0) { + for (std::size_t i = 0; i < 4u; i += 2u) { + const std::int32_t idx2 = b.read_vlc(tables.vec2); + if (idx2 < 0) { + for (std::size_t k = 0; k < 2u; ++k) { + std::uint32_t x = static_cast(b.read_vlc(tables.vec1)); + if (x == static_cast(std::size(kVec1Table) - 1u)) { + x += b.large_value(); + } + vals[i + k] = x; + } + } else { + vals[i] = static_cast(idx2 >> 4); + vals[i + 1u] = static_cast(idx2 & 0xf); + } + } + } else { + vals[0] = static_cast((idx4 >> 12) & 0xf); + vals[1] = static_cast((idx4 >> 8) & 0xf); + vals[2] = static_cast((idx4 >> 4) & 0xf); + vals[3] = static_cast(idx4 & 0xf); + } + for (std::uint32_t v : vals) { + if (v != 0u) { + const bool neg = !b.bit(); + ch.coeffs[cur] = neg ? -static_cast(v) : static_cast(v); + num_zeros = 0; + } else { + ch.coeffs[cur] = 0.0f; + ++num_zeros; + if (num_zeros > (subframe_len_ >> 8u)) rl_mode = true; + } + ++cur; + } + if (b.overread()) { + err = "vector coefficients overread"; + return false; + } + } + + if (cur < subframe_len_) { + std::fill(ch.coeffs.begin() + static_cast(cur), + ch.coeffs.begin() + static_cast(subframe_len_), 0.0f); + const std::size_t mask = subframe_len_ - 1u; + std::size_t offset = cur; + while (offset < subframe_len_) { + const std::int32_t code = b.read_vlc(tables.coef[table]); + if (code > 1) { + offset += static_cast(run[static_cast(code)]); + const bool neg = !b.bit(); + const float v = level[static_cast(code)]; + ch.coeffs[offset & mask] = neg ? -v : v; + } else if (code == 1) { + break; + } else { + const std::int32_t value = static_cast(b.large_value()); + if (b.bit()) { + if (b.bit()) { + if (b.bit()) break; // escape terminator + offset += static_cast(b.read(esc_len_)) + 4u; + } else { + offset += static_cast(b.read(2)) + 1u; + } + } + const bool neg = !b.bit(); + ch.coeffs[offset & mask] = static_cast(neg ? -value : value); + } + if (b.overread()) { + err = "run-level coefficients overread"; + return false; + } + ++offset; + } + } + return true; +} + +void Decoder::inverse_channel_transform() { + if (!transform_ || channels_for_cur_subframe_ != 2u) return; + const auto& sfb = sfb_offsets_[table_idx_]; + auto& a = ch_[0]; + auto& b = ch_[1]; + for (std::size_t band = 0; band < num_bands_; ++band) { + const std::size_t end = std::min(sfb[band + 1u], subframe_len_); + if (transform_band_[band]) { + for (std::size_t y = sfb[band]; y < end; ++y) { + const float l = a.coeffs[y]; + const float r = b.coeffs[y]; + a.coeffs[y] = l - r; + b.coeffs[y] = l + r; + } + } else { + for (std::size_t y = sfb[band]; y < end; ++y) { + a.coeffs[y] *= 181.0f / 128.0f; + b.coeffs[y] *= 181.0f / 128.0f; + } + } + } +} + +bool Decoder::decode_subframe(Bits& b, const char*& err) { + std::size_t offset = kFrameSamples; + std::size_t sflen = kFrameSamples; + std::size_t total_samples = kFrameSamples * channels_; + for (std::size_t c = 0; c < channels_; ++c) { + const auto& ch = ch_[c]; + if (offset > ch.decoded_samples) { + offset = ch.decoded_samples; + sflen = ch.subframe_len[std::min(ch.cur_subframe, kMaxSubframes - 1u)]; + } + } + channels_for_cur_subframe_ = 0; + for (std::size_t c = 0; c < channels_; ++c) { + auto& ch = ch_[c]; + total_samples -= ch.decoded_samples; + if (offset == ch.decoded_samples && ch.cur_subframe < ch.num_subframes && + sflen == ch.subframe_len[ch.cur_subframe]) { + total_samples -= sflen; + ch.decoded_samples += sflen; + channel_indexes_[channels_for_cur_subframe_] = c; + ++channels_for_cur_subframe_; + } + } + if (channels_for_cur_subframe_ == 0u) { + err = "no channel in subframe"; + return false; + } + if (total_samples == 0u) parsed_all_subframes_ = true; + + table_idx_ = static_cast(floor_log2(kFrameSamples / sflen)); + num_bands_ = num_sfb_[table_idx_]; + subframe_len_ = sflen; + esc_len_ = floor_log2(sflen - 1u) + 1u; + + if (b.bit()) { + std::size_t fill = static_cast(b.read(2)); + if (fill == 0u) { + const std::uint32_t len = b.read(4); + fill = static_cast(b.read(len)) + 1u; + } + b.pos += fill; + } + if (b.bit()) { + err = "reserved bit set"; + return false; + } + if (!decode_channel_transform(b, err)) return false; + + bool transmit_coeffs = false; + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + const std::size_t c = channel_indexes_[i]; + ch_[c].transmit_coefs = b.bit(); + transmit_coeffs = transmit_coeffs || ch_[c].transmit_coefs; + } + if (transmit_coeffs) { + transmit_num_vec_coeffs_ = b.bit(); + if (transmit_num_vec_coeffs_) { + const std::uint32_t num_bits = floor_log2((sflen + 3u) / 4u) + 1u; + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + const std::size_t c = channel_indexes_[i]; + const std::size_t n = static_cast(b.read(num_bits)) << 2u; + if (n > sflen) { + err = "vector coefficient count"; + return false; + } + ch_[c].num_vec_coeffs = n; + } + } else { + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + ch_[channel_indexes_[i]].num_vec_coeffs = sflen; + } + } + std::int32_t quant_step = 90; + std::int32_t step = b.read_signed(6); + quant_step += step; + if (step == -32 || step == 31) { + const bool negative = (step == -32); + std::int32_t quant = 0; + while (b.pos + 5u < b.end) { + step = static_cast(b.read(5)); + if (step != 31) break; + quant += 31; + } + quant_step += negative ? -(quant + step) : (quant + step); + } + if (channels_for_cur_subframe_ == 1u) { + ch_[channel_indexes_[0]].quant_step = quant_step; + } else { + const std::uint32_t mod_len = b.read(3); + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + const std::size_t c = channel_indexes_[i]; + ch_[c].quant_step = quant_step; + if (b.bit()) { + ch_[c].quant_step += (mod_len > 0u) ? (static_cast(b.read(mod_len)) + 1) : 1; + } + } + } + if (!decode_scale_factors(b, err)) return false; + } + + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + const std::size_t c = channel_indexes_[i]; + if (ch_[c].transmit_coefs && b.pos < b.end) { + if (!decode_coefficients(b, c, err)) return false; + } else { + std::fill(ch_[c].coeffs.begin(), ch_[c].coeffs.begin() + static_cast(sflen), 0.0f); + } + } + + const std::size_t at = offset + kFrameSamples / 2u; + if (transmit_coeffs) { + inverse_channel_transform(); + const float scale = 2.0f / static_cast(sflen) / 32768.0f; + const auto& sfb = sfb_offsets_[table_idx_]; + std::array tmp{}; + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + auto& ch = ch_[channel_indexes_[i]]; + const auto& sf = ch.saved_scale_factors[ch.scale_factors]; + for (std::size_t band = 0; band < num_bands_; ++band) { + const std::size_t end = std::min(sfb[band + 1u], sflen); + const std::int32_t exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; + const float quant = std::pow(10.0f, static_cast(exp) / 20.0f); + for (std::size_t y = sfb[band]; y < end; ++y) tmp[y] = ch.coeffs[y] * quant; + } + imdct_half(tmp.data(), ch.out.data() + at, sflen, scale); + } + } else { + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + auto& out_buf = ch_[channel_indexes_[i]].out; + std::fill(out_buf.begin() + static_cast(at), + out_buf.begin() + static_cast(at + sflen), 0.0f); + } + } + + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + auto& ch = ch_[channel_indexes_[i]]; + std::size_t winlen = ch.prev_block_len; + std::size_t start = at - winlen / 2u; + if (sflen < winlen) { + start += (winlen - sflen) / 2u; + winlen = sflen; + } + window_overlap(ch.out.data() + start, sine_window(winlen).data(), winlen); + ch.prev_block_len = sflen; + } + + for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { + auto& ch = ch_[channel_indexes_[i]]; + if (ch.cur_subframe >= ch.num_subframes) { + err = "subframe overrun"; + return false; + } + ++ch.cur_subframe; + } + if (b.overread()) { + err = "subframe overread"; + return false; + } + return true; +} + +} // namespace leonida::xma2 diff --git a/runtime/src/xma2_decoder.h b/runtime/src/xma2_decoder.h new file mode 100644 index 0000000000..3ee9fed17b --- /dev/null +++ b/runtime/src/xma2_decoder.h @@ -0,0 +1,116 @@ +// Portable XMA2 packet parser and WMA Pro frame decoder (1–2 channels, 512-sample frames, 128–512 subframes). +// +// Algorithm and canonical Huffman / quantization tables follow FFmpeg's libavcodec/wmaprodec.c and wmaprodata.h +// (LGPL-2.1-or-later, used here under GPL-3.0-or-later), specialized for Xbox XMA2 streams (up to 2 channels, no LFE, +// 2048-byte packets with 32-bit MSB-first packet headers). +#pragma once + +#include +#include +#include +#include +#include + +namespace leonida::xma2 { + +inline constexpr std::size_t kPacketBytes = 2048; +inline constexpr std::size_t kPacketBits = kPacketBytes * 8; +inline constexpr std::size_t kHeaderBits = 32; +inline constexpr std::size_t kFrameSamples = 512; +inline constexpr std::size_t kSubframeSamples = 128; + +struct PacketHeader { + std::uint32_t frames = 0; + std::uint32_t first_frame_bit = 0; + std::uint32_t skip = 0; +}; + +struct FrameBits { + std::vector data; + std::size_t bits = 0; + std::size_t start = 0; + std::optional next; +}; + +// Parses the 32-bit MSB-first header of packet `packet_index` inside `data[0..size)`. +std::optional parse_packet(const std::uint8_t* data, std::size_t size, std::size_t packet_index); + +// Gathers one XMA2 frame starting at bit offset `start_bit` inside a buffer of 2048-byte packets, crossing packet +// headers and skipped interleaved stream packets, and computes the bit offset of the next frame if present. +std::optional read_frame(const std::uint8_t* data, std::size_t size, std::size_t start_bit); + +// Half-length inverse MDCT (negated DCT-IV scaled by `scale`) and sine window overlap-add helpers. +void imdct_half(const float* input, float* output, std::size_t n, float scale); +void window_overlap(float* block, const float* window, std::size_t block_len); +const std::vector& sine_window(std::size_t n); + +class Decoder { +public: + static constexpr std::size_t kBlockSizes = 3; + static constexpr std::size_t kMaxBands = 29; + static constexpr std::size_t kMaxSubframes = 32; + + Decoder(std::size_t channels, std::uint32_t sample_rate); + + std::size_t channels() const { return channels_; } + void reset(); + + // Decodes one frame (`data`, `bits`) and appends kFrameSamples interleaved 16-bit PCM samples per channel to `out`. + // Returns false and optionally sets `*error` on a bitstream error (still emitting timing-preserving silence). + bool decode(const std::uint8_t* data, std::size_t bits, std::vector& out, + const char** error = nullptr); + + // Emits the remaining half-frame overlap tail (kFrameSamples / 2 samples per channel) and resets state. + void flush(std::vector& out); + +private: + struct Channel { + std::size_t prev_block_len = kFrameSamples; + bool transmit_coefs = false; + std::size_t num_subframes = 0; + std::array subframe_len{}; + std::size_t cur_subframe = 0; + std::size_t decoded_samples = 0; + std::int32_t quant_step = 0; + bool reuse_sf = false; + std::int32_t scale_factor_step = 1; + std::int32_t max_scale_factor = 0; + std::array, 2> saved_scale_factors{}; + std::size_t scale_factor_idx = 0; + std::size_t scale_factors = 0; + std::size_t table_idx = 0; + std::size_t num_vec_coeffs = 0; + std::array coeffs{}; + std::array out{}; + }; + + struct Bits; + + bool decode_frame(Bits& b, std::size_t len, const char*& err); + bool decode_tile_header(Bits& b, const char*& err); + bool decode_subframe_length(Bits& b, std::size_t offset, std::size_t& out_len, const char*& err) const; + bool decode_subframe(Bits& b, const char*& err); + bool decode_channel_transform(Bits& b, const char*& err); + bool decode_scale_factors(Bits& b, const char*& err); + bool decode_coefficients(Bits& b, std::size_t c, const char*& err); + void inverse_channel_transform(); + + std::size_t channels_ = 1; + std::array num_sfb_{}; + std::array, kBlockSizes> sfb_offsets_{}; + std::array, kBlockSizes>, kBlockSizes> sf_offsets_{}; + std::array ch_{}; + + std::size_t subframe_len_ = kFrameSamples; + std::size_t channels_for_cur_subframe_ = 0; + std::array channel_indexes_{0, 1}; + std::size_t num_bands_ = 0; + std::size_t table_idx_ = 0; + std::uint32_t esc_len_ = 0; + bool transmit_num_vec_coeffs_ = false; + bool transform_ = false; + std::array transform_band_{}; + bool parsed_all_subframes_ = false; +}; + +} // namespace leonida::xma2 diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp index bd93f70405..ca3167e64e 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include "shims.h" @@ -257,6 +258,210 @@ int main() { check(ctx_all.xmaContextArray == nullptr, "xmaContextArray is reset to null"); 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"); + + // 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 + { + // Build a 2-packet XMA2 buffer with 3 silent mono frames per packet (6 frames total). + 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, 32); // 3 frames, first_frame_bit = 0, skip = 0 + for (size_t f = 0; f < 3; ++f) { + const size_t at = base + 32 + f * 31; + 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, + "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"); + std::memcpy(in_va, stream.data(), stream.size()); + + 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. + auto* 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; + 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); + } + check(((words[1] >> 31) & 1u) == 0u, + "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"); + + bool ring_zeroed = true; + const auto* ring_bytes = static_cast(out_va); + for (size_t i = 0; i < 0x400; ++i) { + if (ring_bytes[i] != 0) { + ring_zeroed = false; + break; + } + } + check(ring_zeroed, "Decoded silent PCM overwrote sentinel bytes across all 4 ring blocks"); + + // Advance read pointer 4 blocks at a time until input exhausts and INPUT_INVALID fires. + const uint32_t advance_args[2] = {1u, 4u}; + for (int step = 0; step < 20; ++step) { + check(fn_submit(x_acp, 18, 0xf2 + static_cast(step), + 0xffffffffu, advance_args, 0) == S_OK, + "ADVANCE_XMA_READ succeeds"); + // 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; + } + } + 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"); + } + std::printf("acphal_test complete: %d checks, %d failures\n", g_checks, g_failures); return g_failures ? 1 : 0; } diff --git a/runtime/test/xma2_decoder_test.cpp b/runtime/test/xma2_decoder_test.cpp new file mode 100644 index 0000000000..b8d64e9bb6 --- /dev/null +++ b/runtime/test/xma2_decoder_test.cpp @@ -0,0 +1,178 @@ +// Portable unit tests for leonida::xma2 (runtime/src/xma2_decoder.h/.cpp): packet parsing, multi-packet frame walk, +// zero-length damaged packet guard, half-IMDCT accuracy, MDCT+IMDCT overlap-add signal reconstruction, and silent +// stream decoding. Needs no game data or Windows headers. +#include "../src/xma2_decoder.h" + +#include +#include +#include +#include +#include + +namespace { + +constexpr double kPi = 3.14159265358979323846264338327950288; + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +void put_bits(std::vector& data, std::size_t pos, std::uint32_t n, std::uint32_t value) { + for (std::size_t i = 0; i < n; ++i) { + const std::uint8_t bit = static_cast((value >> (n - 1u - i)) & 1u); + const std::size_t p = pos + i; + data[p / 8u] = static_cast((data[p / 8u] & ~(1u << (7u - (p % 8u)))) | (bit << (7u - (p % 8u)))); + } +} + +std::vector imdct_reference(const std::vector& input) { + const std::size_t n = input.size(); + std::vector out(n, 0.0f); + for (std::size_t j = 0; j < n; ++j) { + const double t = static_cast(j + n / 2u) + 0.5 + static_cast(n) / 2.0; + double sum = 0.0; + for (std::size_t k = 0; k < n; ++k) { + sum += static_cast(input[k]) * + std::cos(kPi / static_cast(n) * t * (static_cast(k) + 0.5)); + } + out[j] = -static_cast(sum); + } + return out; +} + +} // namespace + +int main() { + using namespace leonida::xma2; + + // 1. Out-of-range index and truncated packet header rejection. + { + const std::uint8_t tiny[4]{}; + check(!parse_packet(tiny, 4, std::numeric_limits::max() / kPacketBytes + 1u).has_value(), + "parse_packet rejects overflow packet index"); + check(!parse_packet(tiny, 3, 0).has_value(), "parse_packet rejects truncated header"); + } + + // 2. Zero-length damaged frame before start terminates search cleanly. + { + std::vector data(kPacketBytes, 0u); + put_bits(data, 0, 32, 2u << 26); + const std::size_t start = kHeaderBits + 100u; + put_bits(data, start, 15, 200u); + const auto frame = read_frame(data.data(), data.size(), start); + check(frame.has_value() && frame->bits == 200u && !frame->next.has_value(), + "zero-length damaged frame before start ends search safely"); + } + + // 3. Multi-packet frame walk (frame crossing boundary into next packet). + { + std::vector data(2u * kPacketBytes, 0xffu); + auto hdr = [](std::uint32_t frames, std::uint32_t first) { return (frames << 26) | (first << 11); }; + put_bits(data, 0, 32, hdr(2, 0)); + put_bits(data, kPacketBits, 32, hdr(1, 48)); + put_bits(data, 32, 15, 100u); + put_bits(data, 132, 15, 16300u); + const std::size_t c_start = kPacketBits + 32u + 48u; + put_bits(data, c_start, 15, 60u); + + const auto a = read_frame(data.data(), data.size(), 32u); + const auto b = read_frame(data.data(), data.size(), 132u); + const auto c = read_frame(data.data(), data.size(), c_start); + check(a && a->bits == 100u && a->next == 132u, "frame A walks to frame B"); + check(b && b->bits == 16300u && b->next == c_start && b->data.size() == (16300u + 7u) / 8u, + "frame B crosses packet header into packet 1"); + check(c && c->bits == 60u && !c->next.has_value(), "frame C terminates at end of buffer"); + } + + // 4. Fast half-IMDCT matches direct cosine sum for n = 128, 256, 512. + { + bool all_close = true; + for (const std::size_t n : {std::size_t(128), std::size_t(256), std::size_t(512)}) { + std::vector input(n); + for (std::size_t i = 0; i < n; ++i) input[i] = static_cast((i * 7919u) % 97u) - 48.0f; + std::vector fast(n, 0.0f); + imdct_half(input.data(), fast.data(), n, 1.0f); + const auto ref = imdct_reference(input); + for (std::size_t i = 0; i < n; ++i) { + if (std::fabs(fast[i] - ref[i]) >= 1e-2f * (1.0f + std::fabs(ref[i]))) all_close = false; + } + } + check(all_close, "fast imdct_half matches direct cosine sum for 128/256/512"); + } + + // 5. MDCT + imdct_half + window_overlap reconstructs a continuous sine wave. + { + constexpr std::size_t n = 256; + std::vector signal(n * 6u); + for (std::size_t i = 0; i < signal.size(); ++i) { + signal[i] = std::sin(static_cast(i) * 0.05f) * 0.3f; + } + auto win = [&](std::size_t i) { + return std::sin((static_cast(i) + 0.5) * kPi / (2.0 * static_cast(n))); + }; + std::vector out(n * 7u, 0.0f); + for (std::size_t block = 0; block < 5u; ++block) { + const std::size_t base = block * n; + std::vector coeffs(n, 0.0f); + for (std::size_t k = 0; k < n; ++k) { + double sum = 0.0; + for (std::size_t i = 0; i < 2u * n; ++i) { + const double t = static_cast(i) + 0.5 + static_cast(n) / 2.0; + sum += -static_cast(signal[base + i]) * win(i) * + std::cos(kPi / static_cast(n) * t * (static_cast(k) + 0.5)); + } + coeffs[k] = static_cast(sum); + } + const std::size_t at = base + n / 2u; + imdct_half(coeffs.data(), out.data() + at, n, 2.0f / static_cast(n)); + if (block > 0u) window_overlap(out.data() + (at - n / 2u), sine_window(n).data(), n); + } + bool exact = true; + for (std::size_t i = n; i < 5u * n; ++i) { + if (std::fabs(out[i] - signal[i]) >= 1e-3f) exact = false; + } + check(exact, "windowed MDCT + half-IMDCT overlap-add reconstructs sine wave within 1e-3"); + } + + // 6. Decode 2 packets of 3 silent mono frames each + overlap flush. + { + std::vector data(2u * kPacketBytes, 0xffu); + for (std::size_t pkt = 0; pkt < 2u; ++pkt) { + const std::size_t base = pkt * kPacketBits; + put_bits(data, base, 32, 3u << 26); + for (std::size_t f = 0; f < 3u; ++f) { + const std::size_t at = base + 32u + f * 31u; + put_bits(data, at, 15, 31u); + put_bits(data, at + 15u, 2, 0b10u); // fixed layout, 1x 512-sample subframe + put_bits(data, at + 17u, 14, 0u); // gain, no trim, empty subframe + } + } + Decoder dec(1, 48000); + std::vector pcm; + std::optional cursor = 32u; + int frames = 0; + int errors = 0; + while (cursor) { + const auto frame = read_frame(data.data(), data.size(), *cursor); + if (!frame) break; + if (!dec.decode(frame->data.data(), frame->bits, pcm)) ++errors; + ++frames; + cursor = frame->next; + } + dec.flush(pcm); + bool all_zero = true; + for (std::int16_t s : pcm) { + if (s != 0) all_zero = false; + } + check(frames == 6 && errors == 0 && pcm.size() == 6u * kFrameSamples + kFrameSamples / 2u && all_zero, + "6 silent mono frames + flush produce 3328 zero PCM samples with 0 errors"); + } + + std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 8bd74d1cf1..baa8f8d759 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -81,7 +81,7 @@ $build || exit /b 1 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." $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\$_`"" } + $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "src\xma2_decoder.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\$_`"" } $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } $body = @" From 12536c2ab33072b8f49a8d012c970093c90c0866 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 03:15:02 -0300 Subject: [PATCH 2/9] acphal: stop the XMA worker it was meant to stop stop_worker set a shared stopping_ flag, moved the thread out and joined it after releasing worker_mutex_. A wake in that window reset stopping_ and started a second worker, so the old one kept running and the join could hang. Each worker is now a std::jthread with its own stop_token (waits use condition_variable_any with the token), so a stop only reaches its own thread. acphal_test races 20000 context alloc/release rounds against ENABLE_XMA on a second thread (the unfixed code hung there intermittently). AI-assisted. Tested: acphal_test 115 checks, 0 failures, repeated runs (clang 23 / mingw x64). Co-Authored-By: Claude Opus 5.5 --- runtime/shims/acphal.cpp | 32 +++++++++++++++---------------- runtime/test/acphal_test.cpp | 37 ++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 16 deletions(-) diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp index c1d375c1c1..3741a0c833 100644 --- a/runtime/shims/acphal.cpp +++ b/runtime/shims/acphal.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -666,34 +667,34 @@ class XmaEngine { void ensure_worker_and_wake() { std::lock_guard lock(worker_mutex_); if (!worker_.joinable()) { - stopping_ = false; - worker_ = std::thread([this]() { worker_loop(); }); + 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::thread to_join; + std::jthread to_join; { std::lock_guard lock(worker_mutex_); if (!worker_.joinable()) return; - stopping_ = true; - wake_requested_ = true; - worker_cv_.notify_one(); + worker_.request_stop(); + worker_cv_.notify_all(); to_join = std::move(worker_); } if (to_join.joinable()) to_join.join(); } - void worker_loop() { + void worker_loop(std::stop_token stop) { for (;;) { { std::unique_lock lock(worker_mutex_); - if (stopping_) return; + if (stop.stop_requested()) return; if (active_count_.load(std::memory_order_relaxed) == 0 && !wake_requested_) { - worker_cv_.wait(lock, [this]() { return stopping_ || wake_requested_; }); - if (stopping_) return; + worker_cv_.wait(lock, stop, [this]() { return wake_requested_; }); + if (stop.stop_requested()) return; } wake_requested_ = false; } @@ -701,11 +702,11 @@ class XmaEngine { pump_all(); std::unique_lock lock(worker_mutex_); - if (stopping_) return; + 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, std::chrono::milliseconds(2), - [this]() { return stopping_ || wake_requested_; }); + worker_cv_.wait_for(lock, stop, std::chrono::milliseconds(2), + [this]() { return wake_requested_; }); } } } @@ -716,9 +717,8 @@ class XmaEngine { std::atomic active_count_{0}; std::mutex worker_mutex_; - std::condition_variable worker_cv_; - std::thread worker_; - bool stopping_ = false; + std::condition_variable_any worker_cv_; + std::jthread worker_; bool wake_requested_ = false; }; diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp index ca3167e64e..276d5815a9 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp @@ -6,10 +6,12 @@ #include +#include #include #include #include #include +#include #include #include "shims.h" @@ -462,6 +464,41 @@ int main() { check(release_ctx(&xma_ctx) == S_OK, "Release XMA SHAPE contexts joins decoder cleanly"); } + // 9. ENABLE_XMA (starts/wakes the decoder worker) racing bind/release (stops it). + // Every release must return; a lost stop would hang this block. + { + 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); + } + }); + 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(); + check(bind_failures == 0, "20000 bind/release cycles race ENABLE_XMA without hanging"); + 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; } From cfcedb58e2802c5cd38afd1cbde877ae9d71c2a5 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 03:53:37 -0300 Subject: [PATCH 3/9] 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/CMakeLists.txt | 45 +- runtime/shims/acphal.cpp | 155 +-- runtime/src/xma2_decoder.cpp | 1094 -------------------- runtime/src/xma2_decoder.h | 116 --- runtime/test/acphal_test.cpp | 93 ++ runtime/test/xma2_decoder_test.cpp | 178 ---- runtime/xma_decoder/README.md | 6 + runtime/xma_decoder/leonida_xma2_decoder.h | 4 + runtime/xma_decoder/src/lib.rs | 44 +- scripts/build_runtime.ps1 | 4 +- third_party/xma/NOTICE.md | 2 + 11 files changed, 266 insertions(+), 1475 deletions(-) delete mode 100644 runtime/src/xma2_decoder.cpp delete mode 100644 runtime/src/xma2_decoder.h delete mode 100644 runtime/test/xma2_decoder_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e64748c1f5..871c48c675 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -106,11 +106,39 @@ 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. + find_program(LEONIDA_CARGO cargo) + if(LEONIDA_CARGO) + set(_xma_target_dir ${CMAKE_BINARY_DIR}/xma_decoder) + set(_xma_lib ${_xma_target_dir}/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 + --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/xma_decoder/Cargo.toml + --target-dir ${_xma_target_dir} + RESULT_VARIABLE _xma_result) + if(_xma_result EQUAL 0 AND EXISTS ${_xma_lib}) + add_library(leonida_xma2_decoder STATIC IMPORTED) + 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 "ws2_32;userenv;ntdll") + 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() + add_executable(gta6rt src/main.cpp src/host_cpu.cpp src/pe_loader.cpp - src/xma2_decoder.cpp shims/registry.cpp shims/file_system.cpp shims/winhttp_offline.cpp @@ -244,14 +272,18 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) add_executable(acphal_test test/acphal_test.cpp shims/acphal.cpp - src/xma2_decoder.cpp shims/registry.cpp ) - target_include_directories(acphal_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims ${CMAKE_CURRENT_SOURCE_DIR}/src) + target_include_directories(acphal_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) target_compile_definitions(acphal_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) 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) @@ -555,13 +587,6 @@ if(BUILD_TESTING) add_test(NAME vulkan_device_filter COMMAND vulkan_device_filter_test) add_executable(vk_presenter_capture_colour_test test/vk_presenter_capture_colour_test.cpp) add_test(NAME vk_presenter_capture_colour COMMAND vk_presenter_capture_colour_test) - # Portable XMA2 packet parser and WMA Pro frame decoder (src/xma2_decoder.cpp): pure stdlib, no GPU. - add_executable(xma2_decoder_test test/xma2_decoder_test.cpp src/xma2_decoder.cpp) - target_include_directories(xma2_decoder_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) - if(MSVC) - target_compile_options(xma2_decoder_test PRIVATE /W4 /permissive- /utf-8) - endif() - add_test(NAME xma2_decoder COMMAND xma2_decoder_test) if(TARGET gta6rt) if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") add_executable(cpp_unwind_test test/cpp_unwind_test.cpp) diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp index 3741a0c833..7f4de8fd83 100644 --- a/runtime/shims/acphal.cpp +++ b/runtime/shims/acphal.cpp @@ -41,7 +41,9 @@ #include "shims.h" #include "startup_trace.h" -#include "../src/xma2_decoder.h" +#if defined(LEONIDA_HAVE_XMA2_DECODER) +#include "leonida_xma2_decoder.h" +#endif namespace { @@ -355,11 +357,29 @@ constexpr uint64_t kAudioFramesPerSecond = 375; // 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 { volatile uint32_t* words = nullptr; @@ -381,14 +401,12 @@ struct XmaContextView { }; struct XmaVoice { - std::optional decoder; +#if defined(LEONIDA_HAVE_XMA2_DECODER) + std::unique_ptr decoder; +#endif std::deque pcm; std::size_t skip = 0; // samples per channel to drop (start/loop subframe skip) bool ended = false; - std::size_t produced = 0; - uint32_t frames = 0; - uint32_t bad_frames = 0; - int16_t peak = 0; }; struct XmaVoiceSlot { @@ -474,8 +492,7 @@ class XmaEngine { ctx.set_field(2, 26, 6, 0); XmaVoice voice; - voice.skip = static_cast(ctx.field(1, 24, 3)) * - leonida::xma2::kSubframeSamples; + voice.skip = static_cast(ctx.field(1, 24, 3)) * kXmaSubframeSamples; voices_[index]->voice.emplace(std::move(voice)); if (!was_active) { active_count_.fetch_add(1, std::memory_order_relaxed); @@ -520,7 +537,39 @@ class XmaEngine { return XmaContextView{array_ + static_cast(index) * 16}; } - static bool decode_one_frame(XmaContextView ctx, XmaVoice& voice) { + // Fills `pcm` (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(XmaContextView ctx, XmaVoice& voice, const uint8_t* bytes, + std::vector& pcm) { + const std::size_t channels = ctx.channels(); +#if defined(LEONIDA_HAVE_XMA2_DECODER) + if (!voice.decoder) { + LeonidaXma2Decoder* raw = nullptr; + if (leonida_xma2_decoder_create_hardware(kXmaRates[ctx.field(1, 27, 2) & 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()); + pcm.assign(samples, samples + count); + return; + } + } +#else + (void)voice; +#endif + pcm.assign(static_cast(bytes[0] >> 2) * kXmaFrameSamples * channels, 0); + } + + // 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 = ctx.channels(); @@ -530,12 +579,6 @@ class XmaEngine { if ((valid & (1u << current)) == 0) { const uint32_t other = 1u - current; if ((valid & (1u << other)) == 0) { - // Both inputs exhausted: flush remaining overlap tail, then signal INPUT_INVALID. - if (voice.decoder.has_value()) { - std::vector tail; - voice.decoder->flush(tail); - voice.pcm.insert(voice.pcm.end(), tail.begin(), tail.end()); - } voice.ended = true; ctx.set_field(2, 26, 5, kXmaErrorInputInvalid); ctx.set_field(2, 31, 1, 1); @@ -547,69 +590,39 @@ class XmaEngine { } const uint32_t address = (current == 0) ? ctx.get(5) : ctx.get(6); - const uint32_t packets = (current == 0) ? ctx.field(0, 0, 12) : ctx.field(1, 0, 12); - const std::size_t input_bytes = - static_cast(packets) * leonida::xma2::kPacketBytes; - const uint8_t* data = apu_span(address & ~0x7FFu, input_bytes); - if (!data) { - ctx.set_field(0, 20 + current, 1, 0); - return true; - } - - std::size_t at = static_cast(ctx.field(2, 0, 26)); - if (at < leonida::xma2::kHeaderBits) { - const auto pkt = leonida::xma2::parse_packet(data, input_bytes, 0); - at = leonida::xma2::kHeaderBits + (pkt.has_value() ? pkt->first_frame_bit : 0u); - } - - const auto frame = leonida::xma2::read_frame(data, input_bytes, at); - if (!frame.has_value()) { + 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) { ctx.set_field(0, 20 + current, 1, 0); + ctx.set_field(2, 0, 26, 0); return true; } - if (!voice.decoder.has_value()) { - static constexpr uint32_t kRates[4] = {24000, 32000, 44100, 48000}; - const uint32_t rate_idx = ctx.field(1, 27, 2) & 3u; - voice.decoder.emplace(channels, kRates[rate_idx]); - } - std::vector pcm; - pcm.reserve(leonida::xma2::kFrameSamples * channels); - ++voice.frames; - if (!voice.decoder->decode(frame->data.data(), frame->bits, pcm)) { - ++voice.bad_frames; - } - - std::size_t next = frame->next.value_or(0); - const uint32_t loops = ctx.field(0, 12, 8); - const std::size_t loop_end = static_cast(ctx.field(4, 0, 26)); - const bool ends_loop = - loop_end != 0 && - (frame->start == loop_end || - (frame->start < loop_end && (!frame->next.has_value() || loop_end < *frame->next))); - if (loops > 0 && ends_loop) { - const std::size_t keep = - (static_cast(ctx.field(1, 12, 2)) + 1u) * - leonida::xma2::kSubframeSamples * channels; - if (keep < pcm.size()) pcm.resize(keep); - next = static_cast(ctx.field(3, 0, 26)); - voice.skip = static_cast(ctx.field(1, 17, 3)) * - leonida::xma2::kSubframeSamples; - if (loops != 255u) { - ctx.set_field(0, 12, 8, loops - 1u); - } - } - + decode_packet(ctx, voice, data + packet * kXmaPacketBytes, pcm); const std::size_t skip_samples = std::min(voice.skip * channels, pcm.size()); voice.skip -= skip_samples / channels; - voice.pcm.insert(voice.pcm.end(), pcm.begin() + static_cast(skip_samples), - pcm.end()); + voice.pcm.insert(voice.pcm.end(), pcm.begin() + static_cast(skip_samples), pcm.end()); - if (next == 0) { + std::size_t next = packet + 1; + 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.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) { ctx.set_field(0, 20 + current, 1, 0); + next = 0; } - ctx.set_field(2, 0, 26, static_cast(next)); + ctx.set_field(2, 0, 26, static_cast(next * kXmaPacketBits)); return true; } @@ -620,7 +633,7 @@ class XmaEngine { while (ctx.field(1, 31, 1) == 1) { int decode_guard = 0; while (voice.pcm.size() < kXmaSamplesPerBlock && decode_guard++ < 16) { - if (!decode_one_frame(ctx, voice)) break; + if (!decode_one_packet(ctx, voice)) break; } if (voice.pcm.empty()) return; @@ -636,15 +649,11 @@ class XmaEngine { sample = voice.pcm.front(); voice.pcm.pop_front(); } - const int32_t mag = - (sample == INT16_MIN) ? INT16_MAX : std::abs(static_cast(sample)); - if (mag > voice.peak) voice.peak = static_cast(mag); const uint16_t raw = static_cast(sample); out[2 * i] = static_cast(raw & 0xFFu); out[2 * i + 1] = static_cast((raw >> 8) & 0xFFu); } - voice.produced += kXmaSamplesPerBlock / ctx.channels(); const uint32_t next_write = (write + 1u) % size; ctx.set_field(0, 27, 5, next_write); if (next_write == ctx.field(9, 0, 5)) { diff --git a/runtime/src/xma2_decoder.cpp b/runtime/src/xma2_decoder.cpp deleted file mode 100644 index a257c873a1..0000000000 --- a/runtime/src/xma2_decoder.cpp +++ /dev/null @@ -1,1094 +0,0 @@ -// Portable XMA2 packet parser and WMA Pro frame decoder. -// -// Canonical Huffman / run-level tables and decoding structure follow FFmpeg's libavcodec/wmaprodec.c and -// libavcodec/wmaprodata.h (LGPL-2.1-or-later, used under GPL-3.0-or-later), specialized for Xbox XMA2 streams -// (1–2 channels, 512-sample frames, 128/256/512 subframes, 2048-byte packets). -#include "xma2_decoder.h" - -#include -#include -#include -#include -#include - -namespace leonida::xma2 { -namespace { - -constexpr std::uint32_t kLengthBits = 15; -constexpr double kPi = 3.14159265358979323846264338327950288; - -struct SymLen { - std::uint16_t sym; - std::uint8_t len; -}; - -// Critical band cutoff frequencies (Hz) and canonical VLC tables from FFmpeg libavcodec/wmaprodata.h. -constexpr std::uint16_t kCriticalFreq[28] = { - 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, - 2700, 3150, 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500, 20675, 28575, 41375, 63875, -}; - -constexpr SymLen kScaleTable[121] = { - {58, 5}, {64, 6}, {66, 7}, {65, 7}, {62, 5}, {63, 6}, {68, 9}, {69, 10}, {54, 15}, {19, 19}, {20, 19}, - {21, 19}, {22, 19}, {23, 19}, {24, 19}, {25, 19}, {26, 19}, {27, 19}, {28, 19}, {29, 19}, {30, 19}, {31, 19}, - {32, 19}, {33, 19}, {34, 19}, {17, 19}, {36, 19}, {37, 19}, {38, 19}, {39, 19}, {40, 19}, {41, 19}, {42, 19}, - {43, 19}, {44, 19}, {45, 19}, {46, 19}, {47, 19}, {48, 19}, {49, 19}, {50, 19}, {51, 19}, {52, 19}, {15, 19}, - {16, 19}, {14, 19}, {13, 19}, {12, 19}, {11, 19}, {10, 19}, {0, 19}, {9, 19}, {8, 19}, {7, 19}, {6, 19}, - {5, 19}, {4, 19}, {55, 13}, {70, 13}, {3, 19}, {2, 19}, {1, 19}, {35, 19}, {71, 19}, {72, 19}, {73, 19}, - {74, 19}, {75, 19}, {76, 19}, {77, 19}, {78, 19}, {79, 19}, {80, 19}, {81, 19}, {82, 19}, {83, 19}, {84, 19}, - {85, 19}, {86, 19}, {87, 19}, {88, 19}, {89, 19}, {90, 19}, {91, 19}, {92, 19}, {93, 19}, {94, 19}, {95, 19}, - {96, 19}, {97, 19}, {98, 19}, {99, 19}, {100, 19},{101, 19},{102, 19},{103, 19},{104, 19},{105, 19},{106, 19}, - {107, 19},{108, 19},{109, 19},{110, 19},{111, 19},{112, 19},{113, 19},{114, 19},{115, 19},{116, 19},{117, 19}, - {118, 19},{119, 19},{120, 19},{18, 18}, {53, 16}, {56, 11}, {57, 8}, {67, 7}, {61, 3}, {59, 2}, {60, 1}, -}; - -constexpr SymLen kScaleRlTable[120] = { - {103, 7}, {80, 11}, {60, 11}, {18, 10}, {56, 10}, {21, 12}, {90, 12}, {58, 11}, {27, 11}, {69, 12}, {84, 15}, - {48, 15}, {86, 14}, {47, 13}, {19, 10}, {32, 9}, {78, 6}, {5, 5}, {28, 4}, {53, 5}, {9, 7}, {31, 8}, - {38, 8}, {10, 7}, {88, 11}, {25, 12}, {105, 12},{118, 11},{23, 12}, {82, 14}, {98, 16}, {110, 16},{108, 15}, - {93, 13}, {68, 10}, {72, 12}, {97, 12}, {81, 12}, {42, 12}, {64, 8}, {4, 4}, {1, 2}, {7, 6}, {14, 7}, - {0, 9}, {55, 9}, {61, 9}, {117, 10},{24, 12}, {44, 12}, {67, 12}, {70, 16}, {99, 18}, {96, 21}, {95, 21}, - {2, 21}, {77, 21}, {52, 21}, {111, 21},{102, 20},{101, 17},{46, 15}, {73, 15}, {109, 15},{51, 14}, {92, 14}, - {30, 7}, {11, 7}, {66, 7}, {15, 8}, {16, 8}, {116, 9}, {65, 9}, {57, 10}, {59, 10}, {115, 9}, {12, 7}, - {35, 9}, {17, 9}, {41, 9}, {20, 11}, {91, 11}, {26, 12}, {75, 15}, {45, 15}, {107, 14},{83, 14}, {100, 15}, - {89, 15}, {43, 11}, {62, 9}, {37, 9}, {104, 8}, {6, 5}, {39, 8}, {40, 9}, {34, 9}, {79, 7}, {8, 6}, - {63, 6}, {87, 12}, {94, 14}, {49, 14}, {50, 13}, {22, 11}, {119, 10},{33, 9}, {36, 9}, {113, 11},{106, 12}, - {112, 13},{71, 15}, {85, 15}, {74, 14}, {76, 10}, {114, 7}, {29, 5}, {54, 6}, {13, 6}, {3, 2}, -}; - -constexpr std::uint8_t kScaleRlRun[120] = { - 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 0, 1, 0, 1, -}; - -constexpr std::uint8_t kScaleRlLevel[120] = { - 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, -}; - -constexpr std::uint8_t kCoef0Lens[272] = { - 2, 9, 14, 14, 13, 12, 13, 14, 15, 15, 12, 10, 10, 10, 13, 14, 15, 15, 12, 11, 13, 14, 14, 13, - 15, 15, 14, 12, 12, 8, 10, 10, 15, 15, 14, 13, 14, 14, 13, 15, 20, 20, 19, 21, 21, 20, 19, 17, - 17, 18, 18, 15, 15, 13, 12, 14, 15, 15, 14, 15, 15, 12, 11, 6, 7, 8, 9, 13, 13, 13, 14, 14, - 11, 10, 7, 8, 14, 14, 14, 14, 12, 13, 13, 12, 12, 12, 11, 9, 13, 14, 14, 12, 11, 11, 11, 9, - 8, 7, 14, 15, 15, 14, 14, 12, 13, 15, 16, 17, 17, 14, 12, 12, 12, 15, 15, 14, 14, 14, 13, 13, - 9, 9, 11, 11, 10, 7, 6, 13, 15, 15, 14, 14, 14, 13, 14, 15, 15, 13, 14, 14, 14, 14, 10, 9, - 10, 10, 11, 11, 10, 8, 9, 13, 14, 14, 12, 11, 14, 15, 15, 13, 12, 14, 14, 14, 14, 13, 14, 14, - 3, 5, 8, 10, 10, 15, 15, 14, 14, 16, 16, 15, 12, 11, 11, 11, 7, 8, 8, 9, 12, 13, 13, 12, - 14, 15, 15, 13, 10, 11, 11, 13, 14, 14, 13, 14, 14, 11, 10, 13, 15, 15, 14, 12, 11, 4, 6, 6, - 8, 12, 12, 12, 13, 13, 12, 13, 13, 14, 14, 13, 13, 13, 9, 7, 9, 11, 14, 14, 13, 14, 14, 13, - 10, 8, 7, 5, 9, 12, 13, 14, 15, 15, 12, 12, 10, 14, 14, 13, 12, 13, 14, 14, 12, 13, 13, 12, - 12, 12, 9, 7, 6, 3, 4, 4, -}; - -constexpr std::uint16_t kCoef0Syms[272] = { - 2, 25, 111, 94, 69, 58, 87, 93, 136, 135, 59, 37, 34, 36, 82, 182, 120, 138, 195, 45, 168, 216, 178, - 86, 140, 219, 186, 162, 239, 18, 156, 35, 127, 236, 109, 85, 180, 253, 88, 147, 268, 264, 256, 266, 270, 262, - 260, 248, 246, 252, 258, 137, 189, 230, 64, 179, 146, 208, 101, 118, 238, 163, 46, 9, 153, 0, 26, 247, 169, - 76, 202, 131, 194, 38, 13, 19, 132, 106, 191, 97, 65, 198, 77, 62, 66, 164, 48, 27, 81, 183, 102, 60, - 47, 49, 159, 227, 20, 14, 112, 263, 144, 217, 104, 63, 79, 209, 269, 250, 254, 203, 241, 196, 61, 220, 148, - 124, 185, 100, 80, 78, 193, 28, 50, 235, 41, 1, 10, 171, 226, 150, 103, 114, 115, 170, 105, 211, 149, 249, - 108, 188, 107, 255, 231, 155, 42, 40, 55, 160, 39, 21, 29, 215, 234, 184, 228, 51, 116, 142, 145, 172, 165, - 181, 130, 113, 117, 89, 128, 204, 3, 7, 154, 157, 43, 141, 265, 133, 225, 271, 244, 221, 74, 54, 56, 52, - 15, 222, 22, 30, 83, 199, 173, 73, 123, 210, 143, 175, 44, 53, 237, 174, 139, 134, 110, 218, 129, 161, 213, - 177, 267, 151, 125, 67, 223, 5, 11, 192, 23, 214, 243, 166, 200, 176, 68, 224, 187, 257, 261, 232, 96, 251, - 31, 16, 32, 57, 207, 121, 91, 126, 119, 99, 158, 24, 212, 8, 33, 70, 92, 205, 240, 242, 75, 197, 233, - 259, 190, 98, 71, 201, 122, 206, 72, 90, 95, 84, 167, 245, 229, 17, 12, 4, 152, 6, -}; - -constexpr SymLen kCoef1Table[244] = { - {2, 2}, {3, 3}, {102, 3}, {4, 4}, {148, 6}, {134, 9}, {171, 10},{18, 10}, {11, 8}, {159, 8}, {14, 9}, - {156, 14},{235, 15},{61, 15}, {38, 13}, {153, 13},{48, 14}, {49, 14}, {23, 11}, {203, 13},{208, 19},{204, 19}, - {129, 18},{94, 17}, {87, 16}, {62, 15}, {174, 15},{147, 15},{29, 12}, {191, 12},{64, 15}, {65, 15}, {146, 14}, - {164, 13},{142, 5}, {132, 4}, {103, 5}, {154, 7}, {165, 9}, {181, 11},{109, 12},{30, 12}, {86, 16}, {92, 16}, - {239, 15},{138, 14},{39, 13}, {50, 14}, {115, 15},{238, 21},{228, 21},{236, 21},{222, 21},{216, 20},{226, 20}, - {196, 18},{192, 17},{120, 16},{221, 14},{51, 14}, {24, 11}, {143, 8}, {7, 6}, {9, 7}, {152, 10},{136, 12}, - {160, 12},{241, 15},{66, 15}, {168, 14},{219, 14},{113, 14},{193, 12},{19, 10}, {173, 10},{105, 8}, {149, 9}, - {15, 9}, {205, 13},{207, 13},{125, 17},{190, 17},{182, 16},{68, 15}, {70, 15}, {67, 15}, {137, 13},{31, 12}, - {223, 14},{116, 15},{210, 19},{220, 19},{198, 18},{126, 17},{88, 16}, {41, 13}, {25, 11}, {40, 13}, {73, 15}, - {243, 15},{53, 14}, {195, 12},{183, 11},{225, 14},{52, 14}, {71, 15}, {121, 16},{89, 16}, {170, 14},{55, 14}, - {69, 15}, {83, 15}, {209, 13},{108, 11},{32, 12}, {54, 14}, {122, 16},{184, 16},{176, 15},{42, 13}, {12, 8}, - {161, 8}, {6, 5}, {167, 9}, {106, 9}, {20, 10}, {145, 12},{111, 13},{43, 13}, {26, 11}, {175, 10},{107, 10}, - {34, 12}, {33, 12}, {197, 12},{74, 15}, {128, 17},{232, 20},{212, 20},{224, 19},{202, 18},{90, 16}, {57, 14}, - {227, 14},{97, 16}, {93, 16}, {140, 15},{185, 11},{27, 11}, {16, 9}, {158, 11},{211, 13},{56, 14}, {117, 15}, - {72, 15}, {166, 13},{91, 16}, {95, 16}, {80, 15}, {101, 16},{194, 17},{127, 17},{82, 15}, {21, 10}, {144, 10}, - {177, 10},{151, 6}, {10, 7}, {157, 7}, {8, 6}, {5, 4}, {13, 8}, {0, 9}, {213, 13},{46, 13}, {199, 12}, - {35, 12}, {162, 12},{135, 10},{169, 9}, {45, 13}, {59, 14}, {114, 14},{44, 13}, {188, 16},{186, 16},{75, 15}, - {79, 15}, {118, 15},{187, 11},{112, 13},{139, 14},{178, 15},{81, 15}, {110, 12},{28, 11}, {163, 8}, {133, 6}, - {104, 6}, {17, 9}, {22, 10}, {229, 14},{172, 14},{217, 13},{201, 12},{36, 12}, {218, 20},{242, 22},{240, 22}, - {234, 21},{230, 19},{206, 18},{200, 18},{214, 18},{130, 17},{131, 17},{141, 15},{84, 15}, {76, 15}, {215, 13}, - {58, 14}, {231, 14},{233, 14},{180, 15},{77, 15}, {37, 12}, {189, 11},{179, 10},{155, 10},{47, 13}, {96, 16}, - {99, 16}, {119, 15},{63, 14}, {237, 14},{78, 15}, {85, 15}, {60, 14}, {98, 16}, {100, 16},{124, 16},{123, 16}, - {150, 11},{1, 7}, -}; - -constexpr std::uint16_t kCoef0Run[272] = { - 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, - 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, - 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, - 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, - 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, - 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 0, 1, 2, 3, 4, 5, 6, 7, 8, - 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, - 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, -}; - -constexpr float kCoef0Level[272] = { - 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, - 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, - 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, - 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, - 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 4.0f, 5.0f, 5.0f, - 5.0f, 5.0f, 5.0f, 6.0f, 6.0f, 7.0f, 7.0f, 8.0f, 8.0f, 9.0f, 9.0f, 10.0f, 10.0f, 11.0f, 11.0f, 12.0f, - 12.0f, 13.0f, 13.0f, 14.0f, 14.0f, 15.0f, 15.0f, 16.0f, 16.0f, 17.0f, 17.0f, 18.0f, 18.0f, 19.0f, 19.0f, 20.0f, - 20.0f, 21.0f, 21.0f, 22.0f, 22.0f, 23.0f, 23.0f, 24.0f, 24.0f, 25.0f, 25.0f, 26.0f, 26.0f, 27.0f, 27.0f, 28.0f, -}; - -constexpr std::uint16_t kCoef1Run[244] = { - 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, - 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, - 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 0, 1, 2, 3, 4, 5, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, -}; - -constexpr float kCoef1Level[244] = { - 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, - 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, - 2.0f, 2.0f, 2.0f, 2.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 3.0f, 4.0f, 4.0f, - 4.0f, 4.0f, 4.0f, 4.0f, 5.0f, 5.0f, 5.0f, 6.0f, 6.0f, 6.0f, 7.0f, 7.0f, 7.0f, 8.0f, 8.0f, 9.0f, - 9.0f, 10.0f, 10.0f, 11.0f, 11.0f, 12.0f, 12.0f, 13.0f, 13.0f, 14.0f, 14.0f, 15.0f, 15.0f, 16.0f, 16.0f, 17.0f, - 17.0f, 18.0f, 18.0f, 19.0f, 19.0f, 20.0f, 20.0f, 21.0f, 21.0f, 22.0f, 22.0f, 23.0f, 23.0f, 24.0f, 24.0f, 25.0f, - 25.0f, 26.0f, 26.0f, 27.0f, 27.0f, 28.0f, 28.0f, 29.0f, 29.0f, 30.0f, 30.0f, 31.0f, 31.0f, 32.0f, 32.0f, 33.0f, - 33.0f, 34.0f, 34.0f, 35.0f, 35.0f, 36.0f, 36.0f, 37.0f, 37.0f, 38.0f, 38.0f, 39.0f, 39.0f, 40.0f, 40.0f, 41.0f, - 41.0f, 42.0f, 42.0f, 43.0f, 43.0f, 44.0f, 44.0f, 45.0f, 45.0f, 46.0f, 46.0f, 47.0f, 47.0f, 48.0f, 48.0f, 49.0f, - 49.0f, 50.0f, 51.0f, 52.0f, -}; - -constexpr std::uint8_t kVec4Lens[127] = { - 1, 6, 8, 10, 10, 10, 10, 8, 8, 10, 10, 9, 8, 8, 9, 12, 12, 11, 12, 12, 11, 9, 9, 8, 8, 9, - 9, 8, 8, 9, 9, 12, 12, 12, 14, 14, 13, 11, 11, 9, 8, 9, 9, 11, 11, 10, 9, 8, 6, 6, 6, 6, - 6, 6, 11, 11, 10, 11, 11, 10, 10, 11, 11, 9, 7, 6, 7, 7, 6, 6, 6, 5, 7, 11, 11, 10, 9, 8, - 6, 9, 9, 10, 10, 9, 8, 8, 6, 6, 6, 8, 8, 9, 12, 12, 11, 10, 8, 8, 8, 10, 10, 10, 10, 9, - 9, 8, 10, 11, 11, 9, 8, 8, 8, 9, 9, 10, 11, 12, 12, 9, 9, 9, 8, 8, 7, 7, 7, -}; - -constexpr std::uint16_t kVec4Syms[127] = { - 0, 4370, 275, 8195, 4146, 12545, 8225, 290, 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, - 5121, 8961, 321, 1041, 51, 4641, 546, 4610, 530, 513, 8451, 4385, 4130, 33, 8211, 5, - 66, 4161, 1281, 81, 6, 801, 8196, 8481, 8449, 4611, 531, 561, 769, 12290, 8226, 19, - 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, 12305, 49, 12321, 260, 4100, 516, 21, 12546, - 8466, 4353, 4371, 4626, 257, 18, 17, 1, 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, - 276, 50, 785, 4116, 8209, 4099, 273, 4113, 258, 259, 4609, 35, 1026, 1025, 16401, 305, - 34, 529, 289, 770, 12289, 4, 4145, 4356, 12306, 8193, 12801, 261, 16386, 4881, 3, 514, - 4129, 545, 306, 36, 4101, 65, 20481, 786, 4401, 4866, 8721, 291, 8450, 8465, 4115, -}; - -constexpr SymLen kVec2Table[137] = { - {19, 5}, {165, 10},{211, 11},{46, 11}, {75, 10}, {177, 11},{12, 11}, {86, 8}, {83, 7}, {38, 7}, {133, 9}, - {178, 10},{28, 10}, {104, 9}, {73, 9}, {35, 5}, {52, 6}, {113, 9}, {8, 9}, {101, 8}, {69, 7}, {0, 3}, - {71, 8}, {119, 9}, {91, 10}, {179, 10},{114, 8}, {166, 10},{10, 10}, {44, 10}, {145, 10},{66, 6}, {21, 6}, - {24, 8}, {146, 9}, {26, 9}, {65, 7}, {5, 7}, {226, 11},{225, 12},{15, 12}, {180, 10},{147, 9}, {115, 8}, - {40, 8}, {89, 9}, {134, 9}, {84, 7}, {54, 7}, {42, 9}, {60, 10}, {31, 11}, {193, 11},{181, 10},{76, 10}, - {148, 9}, {37, 6}, {67, 6}, {33, 6}, {3, 6}, {17, 6}, {2, 6}, {102, 8}, {87, 8}, {116, 8}, {56, 8}, - {50, 5}, {20, 5}, {120, 9}, {58, 9}, {29, 10}, {194, 10},{135, 9}, {97, 8}, {7, 8}, {105, 9}, {13, 11}, - {241, 12},{16, 12}, {45, 10}, {149, 9}, {74, 9}, {98, 7}, {23, 7}, {85, 7}, {70, 7}, {195, 10},{161, 10}, - {129, 9}, {72, 8}, {51, 5}, {36, 5}, {117, 8}, {61, 10}, {11, 10}, {162, 9}, {1, 7}, {4, 6}, {49, 6}, - {68, 6}, {9, 9}, {27, 9}, {130, 8}, {39, 7}, {53, 6}, {99, 7}, {25, 8}, {150, 9}, {90, 9}, {103, 8}, - {163, 9}, {196, 10},{210, 10},{136, 9}, {121, 9}, {41, 8}, {131, 8}, {43, 9}, {164, 9}, {118, 8}, {88, 8}, - {81, 7}, {6, 7}, {55, 7}, {59, 9}, {30, 10}, {209, 11},{14, 11}, {151, 9}, {106, 9}, {82, 6}, {22, 6}, - {100, 7}, {132, 8}, {57, 8}, {18, 4}, {34, 4}, -}; - -constexpr SymLen kVec1Table[101] = { - {7, 5}, {32, 8}, {59, 10}, {60, 10}, {83, 11}, {82, 11}, {62, 10}, {33, 8}, {45, 9}, {61, 10}, {84, 11}, - {85, 11}, {1, 6}, {13, 5}, {19, 6}, {25, 7}, {34, 8}, {46, 9}, {47, 9}, {14, 5}, {6, 5}, {64, 10}, - {87, 11}, {86, 11}, {63, 10}, {88, 11}, {90, 11}, {35, 8}, {26, 7}, {0, 7}, {48, 9}, {65, 10}, {66, 10}, - {36, 8}, {15, 5}, {20, 6}, {91, 11}, {89, 11}, {67, 10}, {49, 9}, {50, 9}, {69, 10}, {92, 11}, {93, 11}, - {27, 7}, {5, 5}, {37, 8}, {68, 10}, {71, 10}, {51, 9}, {52, 9}, {70, 10}, {94, 11}, {96, 11}, {38, 8}, - {21, 6}, {16, 5}, {4, 5}, {28, 7}, {53, 9}, {95, 11}, {97, 11}, {73, 10}, {39, 8}, {29, 7}, {72, 10}, - {98, 11}, {99, 11}, {54, 9}, {40, 8}, {22, 6}, {30, 7}, {55, 9}, {74, 10}, {76, 10}, {56, 9}, {75, 10}, - {77, 10}, {17, 5}, {3, 5}, {23, 6}, {41, 8}, {57, 9}, {78, 10}, {79, 10}, {31, 7}, {10, 4}, {9, 4}, - {100, 5}, {2, 5}, {11, 4}, {8, 4}, {18, 5}, {42, 8}, {58, 9}, {80, 10}, {81, 10}, {43, 8}, {44, 8}, - {24, 6}, {12, 4}, -}; - -std::uint32_t floor_log2(std::size_t v) { - const std::size_t clamped = std::max(v, 1u); - return static_cast(std::bit_width(clamped) - 1u); -} - -struct PacketCursor { - const std::uint8_t* data; - std::size_t size; - std::size_t pos; - - bool read_bit(std::uint32_t& out) { - if ((pos % kPacketBits) == 0) { - const std::size_t prev = pos / kPacketBits; - if (prev > 0) { - const auto hdr = parse_packet(data, size, prev - 1); - if (!hdr) return false; - pos = (prev + static_cast(hdr->skip)) * kPacketBits; - } - pos += kHeaderBits; - } - const std::size_t byte_idx = pos / 8; - if (byte_idx >= size) return false; - out = static_cast((data[byte_idx] >> (7u - (pos % 8u))) & 1u); - ++pos; - return true; - } - - bool read_bits(std::uint32_t n, std::uint32_t& out) { - std::uint32_t v = 0; - for (std::uint32_t i = 0; i < n; ++i) { - std::uint32_t b = 0; - if (!read_bit(b)) return false; - v = (v << 1) | b; - } - out = v; - return true; - } -}; - -std::optional find_next_frame(const std::uint8_t* data, std::size_t size, std::size_t start, - std::size_t end) { - const std::size_t index = start / kPacketBits; - const auto header = parse_packet(data, size, index); - if (!header) return std::nullopt; - - std::size_t at = index * kPacketBits + kHeaderBits + static_cast(header->first_frame_bit); - std::uint32_t number = 0; - while (at < start) { - PacketCursor cur{data, size, at}; - std::uint32_t bits = 0; - if (!cur.read_bits(kLengthBits, bits) || bits <= kLengthBits) return std::nullopt; - at += static_cast(bits); - ++number; - } - const bool last = (number + 1u) >= header->frames; - if ((end % kPacketBits) == 0 || (last && (end / kPacketBits) == index)) { - const std::size_t end_pkt = (end - 1u) / kPacketBits; - const auto end_hdr = parse_packet(data, size, end_pkt); - if (!end_hdr) return std::nullopt; - const std::size_t next_pkt = end_pkt + 1u + static_cast(end_hdr->skip); - const auto next_hdr = parse_packet(data, size, next_pkt); - if (!next_hdr) return std::nullopt; - end = next_pkt * kPacketBits + kHeaderBits + static_cast(next_hdr->first_frame_bit); - } - if ((end / 8u) >= size) return std::nullopt; - return end; -} - -struct VlcEntry { - std::uint32_t code; - std::uint8_t len; - std::int32_t symbol; -}; - -struct Vlc { - std::vector codes; - - template - static Vlc build(std::size_t count, Fn&& get_sym_len) { - Vlc vlc; - vlc.codes.reserve(count); - std::uint64_t code = 0; - for (std::size_t i = 0; i < count; ++i) { - const auto [sym, len] = get_sym_len(i); - vlc.codes.push_back({static_cast(code), len, sym}); - code += (1ull << (32u - len)); - } - return vlc; - } - - std::int32_t read(std::uint32_t peek32, std::size_t& pos) const { - const auto it = std::upper_bound(codes.begin(), codes.end(), peek32, - [](std::uint32_t val, const VlcEntry& e) { return val < e.code; }); - const std::size_t idx = (it == codes.begin()) ? 0u : static_cast((it - codes.begin()) - 1); - pos += codes[idx].len; - return codes[idx].symbol; - } -}; - -struct CodeTables { - Vlc scale; - Vlc scale_rl; - Vlc coef[2]; - Vlc vec4; - Vlc vec2; - Vlc vec1; -}; - -const CodeTables& code_tables() { - static const CodeTables tables = [] { - CodeTables t; - t.scale = Vlc::build(std::size(kScaleTable), [](std::size_t i) { - return std::pair{static_cast(kScaleTable[i].sym) - 60, - kScaleTable[i].len}; - }); - t.scale_rl = Vlc::build(std::size(kScaleRlTable), [](std::size_t i) { - return std::pair{static_cast(kScaleRlTable[i].sym), - kScaleRlTable[i].len}; - }); - t.coef[0] = Vlc::build(std::size(kCoef0Syms), [](std::size_t i) { - return std::pair{static_cast(kCoef0Syms[i]), kCoef0Lens[i]}; - }); - t.coef[1] = Vlc::build(std::size(kCoef1Table), [](std::size_t i) { - return std::pair{static_cast(kCoef1Table[i].sym), - kCoef1Table[i].len}; - }); - t.vec4 = Vlc::build(std::size(kVec4Syms), [](std::size_t i) { - return std::pair{static_cast(kVec4Syms[i]) - 1, kVec4Lens[i]}; - }); - t.vec2 = Vlc::build(std::size(kVec2Table), [](std::size_t i) { - return std::pair{static_cast(kVec2Table[i].sym) - 1, - kVec2Table[i].len}; - }); - t.vec1 = Vlc::build(std::size(kVec1Table), [](std::size_t i) { - return std::pair{static_cast(kVec1Table[i].sym), - kVec1Table[i].len}; - }); - return t; - }(); - return tables; -} - -void fft_radix2(std::vector& re, std::vector& im) { - const std::size_t n = re.size(); - std::size_t j = 0; - for (std::size_t i = 1; i < n; ++i) { - std::size_t bit = n >> 1; - while ((j & bit) != 0) { - j ^= bit; - bit >>= 1; - } - j |= bit; - if (i < j) { - std::swap(re[i], re[j]); - std::swap(im[i], im[j]); - } - } - for (std::size_t len = 2; len <= n; len <<= 1) { - const double ang = -2.0 * kPi / static_cast(len); - const double wc = std::cos(ang); - const double ws = std::sin(ang); - for (std::size_t start = 0; start < n; start += len) { - double cr = 1.0; - double ci = 0.0; - for (std::size_t k = 0; k < len / 2; ++k) { - const std::size_t a = start + k; - const std::size_t b = a + len / 2; - const double tr = re[b] * cr - im[b] * ci; - const double ti = re[b] * ci + im[b] * cr; - re[b] = re[a] - tr; - im[b] = im[a] - ti; - re[a] += tr; - im[a] += ti; - const double next_cr = cr * wc - ci * ws; - const double next_ci = cr * ws + ci * wc; - cr = next_cr; - ci = next_ci; - } - } - } -} - -std::vector make_sine_window(std::size_t n) { - std::vector w(n); - for (std::size_t i = 0; i < n; ++i) { - w[i] = static_cast(std::sin((static_cast(i) + 0.5) * kPi / (2.0 * static_cast(n)))); - } - return w; -} - -std::int16_t float_to_i16(float v) { - const float scaled = std::round(v * 32768.0f); - const float clamped = std::clamp(scaled, -32768.0f, 32767.0f); - return static_cast(clamped); -} - -} // namespace - -struct Decoder::Bits { - const std::uint8_t* data; - std::size_t byte_len; - std::size_t pos; - std::size_t end; - - std::uint32_t peek32() const { - std::uint64_t v = 0; - const std::size_t byte = pos / 8u; - for (std::size_t i = 0; i < 5u; ++i) { - const std::uint8_t b = (byte + i < byte_len) ? data[byte + i] : 0u; - v = (v << 8) | static_cast(b); - } - return static_cast((v << (24u + (pos % 8u))) >> 32u); - } - - std::uint32_t read(std::uint32_t n) { - if (n == 0) return 0; - const std::uint32_t v = peek32() >> (32u - n); - pos += static_cast(n); - return v; - } - - bool bit() { return read(1) != 0; } - - std::int32_t read_signed(std::uint32_t n) { - const std::uint32_t u = read(n); - return static_cast(u << (32u - n)) >> static_cast(32u - n); - } - - std::int32_t read_vlc(const Vlc& vlc) { return vlc.read(peek32(), pos); } - - std::uint32_t large_value() { - std::uint32_t n = 8; - if (bit()) { - n += 8; - if (bit()) { - n += 8; - if (bit()) n += 7; - } - } - return read(n); - } - - bool overread() const { return pos > end; } -}; - -std::optional parse_packet(const std::uint8_t* data, std::size_t size, std::size_t packet_index) { - if (!data || packet_index > std::numeric_limits::max() / kPacketBytes) return std::nullopt; - const std::size_t start = packet_index * kPacketBytes; - if (start > size || (size - start) < 4u) return std::nullopt; - const std::uint32_t h = (static_cast(data[start]) << 24) | - (static_cast(data[start + 1]) << 16) | - (static_cast(data[start + 2]) << 8) | - static_cast(data[start + 3]); - return PacketHeader{h >> 26, (h >> 11) & 0x7fffu, h & 0xffu}; -} - -std::optional read_frame(const std::uint8_t* data, std::size_t size, std::size_t start_bit) { - if (!data || size == 0) return std::nullopt; - PacketCursor probe{data, size, start_bit}; - std::uint32_t bits_u32 = 0; - if (!probe.read_bits(kLengthBits, bits_u32)) return std::nullopt; - const std::size_t bits = static_cast(bits_u32); - if (bits <= kLengthBits || bits == 0x7fffu) return std::nullopt; - - std::vector out((bits + 7u) / 8u, 0u); - PacketCursor cur{data, size, start_bit}; - for (std::size_t i = 0; i < bits; ++i) { - std::uint32_t b = 0; - if (!cur.read_bit(b)) return std::nullopt; - out[i / 8u] |= static_cast(b << (7u - (i % 8u))); - } - const std::size_t end = cur.pos; - return FrameBits{std::move(out), bits, start_bit, find_next_frame(data, size, start_bit, end)}; -} - -void imdct_half(const float* input, float* output, std::size_t n, float scale) { - const std::size_t m = n / 2u; - std::vector re(m, 0.0); - std::vector im(m, 0.0); - for (std::size_t k = 0; k < m; ++k) { - const double a = static_cast(input[2u * k]); - const double b = static_cast(input[n - 1u - 2u * k]); - const double ang = -kPi * static_cast(k) / static_cast(n); - const double c = std::cos(ang); - const double s = std::sin(ang); - re[k] = a * c - b * s; - im[k] = a * s + b * c; - } - fft_radix2(re, im); - for (std::size_t k = 0; k < m; ++k) { - const double ang = -kPi * static_cast(4u * k + 1u) / static_cast(4u * n); - const double c = std::cos(ang); - const double s = std::sin(ang); - const double wr = re[k] * c - im[k] * s; - const double wi = re[k] * s + im[k] * c; - output[n - 1u - 2u * k] = static_cast(wr) * scale; - output[2u * k] = -static_cast(wi) * scale; - } -} - -void window_overlap(float* block, const float* window, std::size_t block_len) { - const std::size_t half = block_len / 2u; - for (std::size_t k = 0; k < half; ++k) { - const std::size_t i = k; - const std::size_t j = 2u * half - 1u - k; - const float s0 = block[i]; - const float s1 = block[j]; - const float wi = window[i]; - const float wj = window[j]; - block[i] = s0 * wj - s1 * wi; - block[j] = s0 * wi + s1 * wj; - } -} - -const std::vector& sine_window(std::size_t n) { - static const std::vector w128 = make_sine_window(128); - static const std::vector w256 = make_sine_window(256); - static const std::vector w512 = make_sine_window(512); - if (n == 128u) return w128; - if (n == 256u) return w256; - return w512; -} - -Decoder::Decoder(std::size_t channels, std::uint32_t sample_rate) : channels_(std::clamp(channels, 1u, 2u)) { - std::size_t rate = 24000u; - if (sample_rate > 44100u) rate = 48000u; - else if (sample_rate > 32000u) rate = 44100u; - else if (sample_rate > 24000u) rate = 32000u; - - for (std::size_t i = 0; i < kBlockSizes; ++i) { - const std::size_t sflen = kFrameSamples >> i; - auto& offsets = sfb_offsets_[i]; - offsets.fill(0); - std::size_t band = 1; - for (std::size_t f = 0; f < std::size(kCriticalFreq); ++f) { - if (offsets[band - 1u] >= sflen) break; - const std::size_t offset = (((sflen * 2u * static_cast(kCriticalFreq[f])) / rate) + 2u) & ~std::size_t(3u); - if (offset > offsets[band - 1u]) { - offsets[band] = offset; - ++band; - } - if (offset >= sflen) break; - } - offsets[band - 1u] = sflen; - num_sfb_[i] = band - 1u; - } - - for (std::size_t i = 0; i < kBlockSizes; ++i) { - for (std::size_t b = 0; b < num_sfb_[i]; ++b) { - const std::size_t offset = ((sfb_offsets_[i][b] + sfb_offsets_[i][b + 1u] - 1u) << i) >> 1u; - for (std::size_t x = 0; x < kBlockSizes; ++x) { - std::size_t v = 0; - while (v + 1u < kMaxBands && (sfb_offsets_[x][v + 1u] << x) < offset) ++v; - sf_offsets_[i][x][b] = v; - } - } - } - reset(); -} - -void Decoder::reset() { ch_ = {Channel{}, Channel{}}; } - -bool Decoder::decode(const std::uint8_t* data, std::size_t bits, std::vector& out, const char** error) { - const std::size_t byte_len = (bits + 7u) / 8u; - Bits b{data, byte_len, 0u, bits}; - const std::size_t len = static_cast(b.read(kLengthBits)); - const char* err = nullptr; - const bool ok = decode_frame(b, len, err); - if (!ok) { - if (error) *error = err ? err : "decode error"; - for (std::size_t c = 0; c < channels_; ++c) ch_[c].out.fill(0.0f); - } else if (error) { - *error = nullptr; - } - out.reserve(out.size() + kFrameSamples * channels_); - for (std::size_t i = 0; i < kFrameSamples; ++i) { - for (std::size_t c = 0; c < channels_; ++c) { - out.push_back(float_to_i16(ch_[c].out[i])); - } - } - for (std::size_t c = 0; c < channels_; ++c) { - std::copy(ch_[c].out.begin() + static_cast(kFrameSamples), ch_[c].out.end(), ch_[c].out.begin()); - } - return ok; -} - -void Decoder::flush(std::vector& out) { - out.reserve(out.size() + (kFrameSamples / 2u) * channels_); - for (std::size_t i = 0; i < kFrameSamples / 2u; ++i) { - for (std::size_t c = 0; c < channels_; ++c) { - out.push_back(float_to_i16(ch_[c].out[i])); - } - } - reset(); -} - -bool Decoder::decode_frame(Bits& b, std::size_t len, const char*& err) { - if (!decode_tile_header(b, err)) return false; - if (channels_ > 1u && b.bit() && b.bit()) { - b.read(static_cast(channels_ * channels_ * 4u)); - } - b.read(8); // dynamic range compression gain - if (b.bit()) { - if (b.bit()) b.read(floor_log2(kFrameSamples * 2u)); - if (b.bit()) b.read(floor_log2(kFrameSamples * 2u)); - } - parsed_all_subframes_ = false; - for (std::size_t c = 0; c < channels_; ++c) { - ch_[c].decoded_samples = 0; - ch_[c].cur_subframe = 0; - ch_[c].reuse_sf = false; - } - while (!parsed_all_subframes_) { - if (!decode_subframe(b, err)) return false; - } - if (b.overread() || b.pos > len) { - err = "frame overread"; - return false; - } - return true; -} - -bool Decoder::decode_subframe_length(Bits& b, std::size_t offset, std::size_t& out_len, const char*& err) const { - if (offset == kFrameSamples - kSubframeSamples) { - out_len = kSubframeSamples; - return true; - } - const std::uint32_t shift = b.bit() ? (1u + b.read(1)) : 0u; - const std::size_t len = kFrameSamples >> shift; - if (len < kSubframeSamples) { - err = "subframe length"; - return false; - } - out_len = len; - return true; -} - -bool Decoder::decode_tile_header(Bits& b, const char*& err) { - std::array num_samples{0, 0}; - std::array contains{false, false}; - std::size_t cur_channels = channels_; - std::size_t min_channel_len = 0; - for (std::size_t c = 0; c < channels_; ++c) ch_[c].num_subframes = 0; - const bool fixed = b.bit(); - for (;;) { - for (std::size_t c = 0; c < channels_; ++c) { - contains[c] = (num_samples[c] == min_channel_len) && - (fixed || cur_channels == 1u || min_channel_len == kFrameSamples - kSubframeSamples || b.bit()); - } - std::size_t sflen = 0; - if (!decode_subframe_length(b, min_channel_len, sflen, err)) return false; - min_channel_len += sflen; - for (std::size_t c = 0; c < channels_; ++c) { - auto& ch = ch_[c]; - if (contains[c]) { - if (ch.num_subframes >= kMaxSubframes) { - err = "too many subframes"; - return false; - } - ch.subframe_len[ch.num_subframes] = sflen; - num_samples[c] += sflen; - ++ch.num_subframes; - if (num_samples[c] > kFrameSamples) { - err = "channel longer than frame"; - return false; - } - } else if (num_samples[c] <= min_channel_len) { - if (num_samples[c] < min_channel_len) { - cur_channels = 0; - min_channel_len = num_samples[c]; - } - ++cur_channels; - } - } - if (min_channel_len >= kFrameSamples || b.overread()) break; - } - if (b.overread()) { - err = "tile header overread"; - return false; - } - return true; -} - -bool Decoder::decode_channel_transform(Bits& b, const char*& err) { - transform_ = false; - if (channels_ == 1u) return true; - if (b.bit()) { - err = "channel transform bit"; - return false; - } - if (channels_for_cur_subframe_ == 2u) { - if (b.bit()) { - if (b.bit()) { - err = "channel transform type"; - return false; - } - } else { - transform_ = true; - } - } - if (transform_) { - if (!b.bit()) { - for (std::size_t i = 0; i < num_bands_; ++i) transform_band_[i] = b.bit(); - } else { - transform_band_.fill(true); - } - } - return true; -} - -bool Decoder::decode_scale_factors(Bits& b, const char*& err) { - const auto& tables = code_tables(); - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const std::size_t c = channel_indexes_[i]; - const auto& sf_off = sf_offsets_[table_idx_][ch_[c].table_idx]; - auto& ch = ch_[c]; - const std::size_t target = 1u - ch.scale_factor_idx; - ch.scale_factors = target; - if (ch.reuse_sf) { - const auto from = ch.saved_scale_factors[ch.scale_factor_idx]; - for (std::size_t band = 0; band < num_bands_; ++band) { - ch.saved_scale_factors[target][band] = from[sf_off[band]]; - } - } - if (ch.cur_subframe == 0u || b.bit()) { - if (!ch.reuse_sf) { - ch.scale_factor_step = static_cast(b.read(2)) + 1; - std::int32_t val = 45 / ch.scale_factor_step; - for (std::size_t band = 0; band < num_bands_; ++band) { - val += b.read_vlc(tables.scale); - ch.saved_scale_factors[target][band] = val; - } - } else { - std::size_t band = 0; - while (band < num_bands_) { - const std::int32_t idx = b.read_vlc(tables.scale_rl); - std::uint32_t skip = 0; - std::int32_t val = 0; - bool neg = false; - if (idx == 0) { - const std::uint32_t code = b.read(14); - skip = (code & 0x3fu) >> 1u; - val = static_cast(code >> 6u); - neg = (code & 1u) == 0u; - } else if (idx == 1) { - break; - } else { - skip = kScaleRlRun[static_cast(idx)]; - val = static_cast(kScaleRlLevel[static_cast(idx)]); - neg = !b.bit(); - } - band += static_cast(skip); - if (band >= num_bands_) { - err = "scale factor run"; - return false; - } - ch.saved_scale_factors[target][band] += neg ? -val : val; - ++band; - } - } - ch.scale_factor_idx = target; - ch.table_idx = table_idx_; - ch.reuse_sf = true; - } - std::int32_t max_sf = 0; - if (num_bands_ > 0u) { - max_sf = ch.saved_scale_factors[ch.scale_factors][0]; - for (std::size_t band = 1; band < num_bands_; ++band) { - max_sf = std::max(max_sf, ch.saved_scale_factors[ch.scale_factors][band]); - } - } - ch.max_scale_factor = max_sf; - } - return true; -} - -bool Decoder::decode_coefficients(Bits& b, std::size_t c, const char*& err) { - const auto& tables = code_tables(); - const std::size_t table = b.bit() ? 1u : 0u; - const std::uint16_t* run = (table == 1u) ? kCoef1Run : kCoef0Run; - const float* level = (table == 1u) ? kCoef1Level : kCoef0Level; - auto& ch = ch_[c]; - - bool rl_mode = false; - std::size_t cur = 0; - std::size_t num_zeros = 0; - while ((transmit_num_vec_coeffs_ || !rl_mode) && cur + 3u < ch.num_vec_coeffs) { - std::array vals{}; - const std::int32_t idx4 = b.read_vlc(tables.vec4); - if (idx4 < 0) { - for (std::size_t i = 0; i < 4u; i += 2u) { - const std::int32_t idx2 = b.read_vlc(tables.vec2); - if (idx2 < 0) { - for (std::size_t k = 0; k < 2u; ++k) { - std::uint32_t x = static_cast(b.read_vlc(tables.vec1)); - if (x == static_cast(std::size(kVec1Table) - 1u)) { - x += b.large_value(); - } - vals[i + k] = x; - } - } else { - vals[i] = static_cast(idx2 >> 4); - vals[i + 1u] = static_cast(idx2 & 0xf); - } - } - } else { - vals[0] = static_cast((idx4 >> 12) & 0xf); - vals[1] = static_cast((idx4 >> 8) & 0xf); - vals[2] = static_cast((idx4 >> 4) & 0xf); - vals[3] = static_cast(idx4 & 0xf); - } - for (std::uint32_t v : vals) { - if (v != 0u) { - const bool neg = !b.bit(); - ch.coeffs[cur] = neg ? -static_cast(v) : static_cast(v); - num_zeros = 0; - } else { - ch.coeffs[cur] = 0.0f; - ++num_zeros; - if (num_zeros > (subframe_len_ >> 8u)) rl_mode = true; - } - ++cur; - } - if (b.overread()) { - err = "vector coefficients overread"; - return false; - } - } - - if (cur < subframe_len_) { - std::fill(ch.coeffs.begin() + static_cast(cur), - ch.coeffs.begin() + static_cast(subframe_len_), 0.0f); - const std::size_t mask = subframe_len_ - 1u; - std::size_t offset = cur; - while (offset < subframe_len_) { - const std::int32_t code = b.read_vlc(tables.coef[table]); - if (code > 1) { - offset += static_cast(run[static_cast(code)]); - const bool neg = !b.bit(); - const float v = level[static_cast(code)]; - ch.coeffs[offset & mask] = neg ? -v : v; - } else if (code == 1) { - break; - } else { - const std::int32_t value = static_cast(b.large_value()); - if (b.bit()) { - if (b.bit()) { - if (b.bit()) break; // escape terminator - offset += static_cast(b.read(esc_len_)) + 4u; - } else { - offset += static_cast(b.read(2)) + 1u; - } - } - const bool neg = !b.bit(); - ch.coeffs[offset & mask] = static_cast(neg ? -value : value); - } - if (b.overread()) { - err = "run-level coefficients overread"; - return false; - } - ++offset; - } - } - return true; -} - -void Decoder::inverse_channel_transform() { - if (!transform_ || channels_for_cur_subframe_ != 2u) return; - const auto& sfb = sfb_offsets_[table_idx_]; - auto& a = ch_[0]; - auto& b = ch_[1]; - for (std::size_t band = 0; band < num_bands_; ++band) { - const std::size_t end = std::min(sfb[band + 1u], subframe_len_); - if (transform_band_[band]) { - for (std::size_t y = sfb[band]; y < end; ++y) { - const float l = a.coeffs[y]; - const float r = b.coeffs[y]; - a.coeffs[y] = l - r; - b.coeffs[y] = l + r; - } - } else { - for (std::size_t y = sfb[band]; y < end; ++y) { - a.coeffs[y] *= 181.0f / 128.0f; - b.coeffs[y] *= 181.0f / 128.0f; - } - } - } -} - -bool Decoder::decode_subframe(Bits& b, const char*& err) { - std::size_t offset = kFrameSamples; - std::size_t sflen = kFrameSamples; - std::size_t total_samples = kFrameSamples * channels_; - for (std::size_t c = 0; c < channels_; ++c) { - const auto& ch = ch_[c]; - if (offset > ch.decoded_samples) { - offset = ch.decoded_samples; - sflen = ch.subframe_len[std::min(ch.cur_subframe, kMaxSubframes - 1u)]; - } - } - channels_for_cur_subframe_ = 0; - for (std::size_t c = 0; c < channels_; ++c) { - auto& ch = ch_[c]; - total_samples -= ch.decoded_samples; - if (offset == ch.decoded_samples && ch.cur_subframe < ch.num_subframes && - sflen == ch.subframe_len[ch.cur_subframe]) { - total_samples -= sflen; - ch.decoded_samples += sflen; - channel_indexes_[channels_for_cur_subframe_] = c; - ++channels_for_cur_subframe_; - } - } - if (channels_for_cur_subframe_ == 0u) { - err = "no channel in subframe"; - return false; - } - if (total_samples == 0u) parsed_all_subframes_ = true; - - table_idx_ = static_cast(floor_log2(kFrameSamples / sflen)); - num_bands_ = num_sfb_[table_idx_]; - subframe_len_ = sflen; - esc_len_ = floor_log2(sflen - 1u) + 1u; - - if (b.bit()) { - std::size_t fill = static_cast(b.read(2)); - if (fill == 0u) { - const std::uint32_t len = b.read(4); - fill = static_cast(b.read(len)) + 1u; - } - b.pos += fill; - } - if (b.bit()) { - err = "reserved bit set"; - return false; - } - if (!decode_channel_transform(b, err)) return false; - - bool transmit_coeffs = false; - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const std::size_t c = channel_indexes_[i]; - ch_[c].transmit_coefs = b.bit(); - transmit_coeffs = transmit_coeffs || ch_[c].transmit_coefs; - } - if (transmit_coeffs) { - transmit_num_vec_coeffs_ = b.bit(); - if (transmit_num_vec_coeffs_) { - const std::uint32_t num_bits = floor_log2((sflen + 3u) / 4u) + 1u; - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const std::size_t c = channel_indexes_[i]; - const std::size_t n = static_cast(b.read(num_bits)) << 2u; - if (n > sflen) { - err = "vector coefficient count"; - return false; - } - ch_[c].num_vec_coeffs = n; - } - } else { - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - ch_[channel_indexes_[i]].num_vec_coeffs = sflen; - } - } - std::int32_t quant_step = 90; - std::int32_t step = b.read_signed(6); - quant_step += step; - if (step == -32 || step == 31) { - const bool negative = (step == -32); - std::int32_t quant = 0; - while (b.pos + 5u < b.end) { - step = static_cast(b.read(5)); - if (step != 31) break; - quant += 31; - } - quant_step += negative ? -(quant + step) : (quant + step); - } - if (channels_for_cur_subframe_ == 1u) { - ch_[channel_indexes_[0]].quant_step = quant_step; - } else { - const std::uint32_t mod_len = b.read(3); - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const std::size_t c = channel_indexes_[i]; - ch_[c].quant_step = quant_step; - if (b.bit()) { - ch_[c].quant_step += (mod_len > 0u) ? (static_cast(b.read(mod_len)) + 1) : 1; - } - } - } - if (!decode_scale_factors(b, err)) return false; - } - - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - const std::size_t c = channel_indexes_[i]; - if (ch_[c].transmit_coefs && b.pos < b.end) { - if (!decode_coefficients(b, c, err)) return false; - } else { - std::fill(ch_[c].coeffs.begin(), ch_[c].coeffs.begin() + static_cast(sflen), 0.0f); - } - } - - const std::size_t at = offset + kFrameSamples / 2u; - if (transmit_coeffs) { - inverse_channel_transform(); - const float scale = 2.0f / static_cast(sflen) / 32768.0f; - const auto& sfb = sfb_offsets_[table_idx_]; - std::array tmp{}; - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - auto& ch = ch_[channel_indexes_[i]]; - const auto& sf = ch.saved_scale_factors[ch.scale_factors]; - for (std::size_t band = 0; band < num_bands_; ++band) { - const std::size_t end = std::min(sfb[band + 1u], sflen); - const std::int32_t exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; - const float quant = std::pow(10.0f, static_cast(exp) / 20.0f); - for (std::size_t y = sfb[band]; y < end; ++y) tmp[y] = ch.coeffs[y] * quant; - } - imdct_half(tmp.data(), ch.out.data() + at, sflen, scale); - } - } else { - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - auto& out_buf = ch_[channel_indexes_[i]].out; - std::fill(out_buf.begin() + static_cast(at), - out_buf.begin() + static_cast(at + sflen), 0.0f); - } - } - - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - auto& ch = ch_[channel_indexes_[i]]; - std::size_t winlen = ch.prev_block_len; - std::size_t start = at - winlen / 2u; - if (sflen < winlen) { - start += (winlen - sflen) / 2u; - winlen = sflen; - } - window_overlap(ch.out.data() + start, sine_window(winlen).data(), winlen); - ch.prev_block_len = sflen; - } - - for (std::size_t i = 0; i < channels_for_cur_subframe_; ++i) { - auto& ch = ch_[channel_indexes_[i]]; - if (ch.cur_subframe >= ch.num_subframes) { - err = "subframe overrun"; - return false; - } - ++ch.cur_subframe; - } - if (b.overread()) { - err = "subframe overread"; - return false; - } - return true; -} - -} // namespace leonida::xma2 diff --git a/runtime/src/xma2_decoder.h b/runtime/src/xma2_decoder.h deleted file mode 100644 index 3ee9fed17b..0000000000 --- a/runtime/src/xma2_decoder.h +++ /dev/null @@ -1,116 +0,0 @@ -// Portable XMA2 packet parser and WMA Pro frame decoder (1–2 channels, 512-sample frames, 128–512 subframes). -// -// Algorithm and canonical Huffman / quantization tables follow FFmpeg's libavcodec/wmaprodec.c and wmaprodata.h -// (LGPL-2.1-or-later, used here under GPL-3.0-or-later), specialized for Xbox XMA2 streams (up to 2 channels, no LFE, -// 2048-byte packets with 32-bit MSB-first packet headers). -#pragma once - -#include -#include -#include -#include -#include - -namespace leonida::xma2 { - -inline constexpr std::size_t kPacketBytes = 2048; -inline constexpr std::size_t kPacketBits = kPacketBytes * 8; -inline constexpr std::size_t kHeaderBits = 32; -inline constexpr std::size_t kFrameSamples = 512; -inline constexpr std::size_t kSubframeSamples = 128; - -struct PacketHeader { - std::uint32_t frames = 0; - std::uint32_t first_frame_bit = 0; - std::uint32_t skip = 0; -}; - -struct FrameBits { - std::vector data; - std::size_t bits = 0; - std::size_t start = 0; - std::optional next; -}; - -// Parses the 32-bit MSB-first header of packet `packet_index` inside `data[0..size)`. -std::optional parse_packet(const std::uint8_t* data, std::size_t size, std::size_t packet_index); - -// Gathers one XMA2 frame starting at bit offset `start_bit` inside a buffer of 2048-byte packets, crossing packet -// headers and skipped interleaved stream packets, and computes the bit offset of the next frame if present. -std::optional read_frame(const std::uint8_t* data, std::size_t size, std::size_t start_bit); - -// Half-length inverse MDCT (negated DCT-IV scaled by `scale`) and sine window overlap-add helpers. -void imdct_half(const float* input, float* output, std::size_t n, float scale); -void window_overlap(float* block, const float* window, std::size_t block_len); -const std::vector& sine_window(std::size_t n); - -class Decoder { -public: - static constexpr std::size_t kBlockSizes = 3; - static constexpr std::size_t kMaxBands = 29; - static constexpr std::size_t kMaxSubframes = 32; - - Decoder(std::size_t channels, std::uint32_t sample_rate); - - std::size_t channels() const { return channels_; } - void reset(); - - // Decodes one frame (`data`, `bits`) and appends kFrameSamples interleaved 16-bit PCM samples per channel to `out`. - // Returns false and optionally sets `*error` on a bitstream error (still emitting timing-preserving silence). - bool decode(const std::uint8_t* data, std::size_t bits, std::vector& out, - const char** error = nullptr); - - // Emits the remaining half-frame overlap tail (kFrameSamples / 2 samples per channel) and resets state. - void flush(std::vector& out); - -private: - struct Channel { - std::size_t prev_block_len = kFrameSamples; - bool transmit_coefs = false; - std::size_t num_subframes = 0; - std::array subframe_len{}; - std::size_t cur_subframe = 0; - std::size_t decoded_samples = 0; - std::int32_t quant_step = 0; - bool reuse_sf = false; - std::int32_t scale_factor_step = 1; - std::int32_t max_scale_factor = 0; - std::array, 2> saved_scale_factors{}; - std::size_t scale_factor_idx = 0; - std::size_t scale_factors = 0; - std::size_t table_idx = 0; - std::size_t num_vec_coeffs = 0; - std::array coeffs{}; - std::array out{}; - }; - - struct Bits; - - bool decode_frame(Bits& b, std::size_t len, const char*& err); - bool decode_tile_header(Bits& b, const char*& err); - bool decode_subframe_length(Bits& b, std::size_t offset, std::size_t& out_len, const char*& err) const; - bool decode_subframe(Bits& b, const char*& err); - bool decode_channel_transform(Bits& b, const char*& err); - bool decode_scale_factors(Bits& b, const char*& err); - bool decode_coefficients(Bits& b, std::size_t c, const char*& err); - void inverse_channel_transform(); - - std::size_t channels_ = 1; - std::array num_sfb_{}; - std::array, kBlockSizes> sfb_offsets_{}; - std::array, kBlockSizes>, kBlockSizes> sf_offsets_{}; - std::array ch_{}; - - std::size_t subframe_len_ = kFrameSamples; - std::size_t channels_for_cur_subframe_ = 0; - std::array channel_indexes_{0, 1}; - std::size_t num_bands_ = 0; - std::size_t table_idx_ = 0; - std::uint32_t esc_len_ = 0; - bool transmit_num_vec_coeffs_ = false; - bool transform_ = false; - std::array transform_band_{}; - bool parsed_all_subframes_ = false; -}; - -} // namespace leonida::xma2 diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp index 276d5815a9..94ff8fa96e 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp @@ -464,6 +464,99 @@ int main() { 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. + { + // Two packets with one silent mono frame each. + 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, 1u << 26, 32); // 1 frame, first_frame_bit = 0 + 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, + "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, 0x1000, 0x800, 1) == S_OK && in_va != nullptr, + "ApuAlloc 2-packet loop input buffer"); + std::memcpy(in_va, stream.data(), stream.size()); + + 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. + auto* 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"); + + // Decodes the stream once on voice 2 with the given loop count and returns the number of + // blocks written when the error flag rose, or -1 on timeout. + auto run_blocks = [&](uint32_t loops) -> int { + std::memset(out_va, 0x55, 0x1000); + words[0] = 2u | (loops << 12) | (1u << 20) | (16u << 22); + words[1] = (1u << 31) | (3u << 27); // 48 kHz, mono, writable + 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[7] = out_apu; + words[9] = 0u; + + const uint32_t enable_arg = 2u; + check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &enable_arg, 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; + const uint32_t disable_arg = 2u; + check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &disable_arg, 0) == S_OK, + "DISABLE_XMA voice 2 succeeds"); + return blocks; + }; + + check(run_blocks(0) == 8, "Two 1-frame packets without a loop write 8 blocks (1024 samples)"); + check(run_blocks(1) == 12, "One loop of packet 0 writes 12 blocks (packets 0, 0, 1)"); + check(((words[0] >> 12) & 0xFFu) == 0u, "Loop count is consumed by the single loop"); + + 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 (starts/wakes the decoder worker) racing bind/release (stops it). // Every release must return; a lost stop would hang this block. { diff --git a/runtime/test/xma2_decoder_test.cpp b/runtime/test/xma2_decoder_test.cpp deleted file mode 100644 index b8d64e9bb6..0000000000 --- a/runtime/test/xma2_decoder_test.cpp +++ /dev/null @@ -1,178 +0,0 @@ -// Portable unit tests for leonida::xma2 (runtime/src/xma2_decoder.h/.cpp): packet parsing, multi-packet frame walk, -// zero-length damaged packet guard, half-IMDCT accuracy, MDCT+IMDCT overlap-add signal reconstruction, and silent -// stream decoding. Needs no game data or Windows headers. -#include "../src/xma2_decoder.h" - -#include -#include -#include -#include -#include - -namespace { - -constexpr double kPi = 3.14159265358979323846264338327950288; - -int g_checks = 0; -int g_failures = 0; - -void check(bool condition, const char* what) { - ++g_checks; - std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); - if (!condition) ++g_failures; -} - -void put_bits(std::vector& data, std::size_t pos, std::uint32_t n, std::uint32_t value) { - for (std::size_t i = 0; i < n; ++i) { - const std::uint8_t bit = static_cast((value >> (n - 1u - i)) & 1u); - const std::size_t p = pos + i; - data[p / 8u] = static_cast((data[p / 8u] & ~(1u << (7u - (p % 8u)))) | (bit << (7u - (p % 8u)))); - } -} - -std::vector imdct_reference(const std::vector& input) { - const std::size_t n = input.size(); - std::vector out(n, 0.0f); - for (std::size_t j = 0; j < n; ++j) { - const double t = static_cast(j + n / 2u) + 0.5 + static_cast(n) / 2.0; - double sum = 0.0; - for (std::size_t k = 0; k < n; ++k) { - sum += static_cast(input[k]) * - std::cos(kPi / static_cast(n) * t * (static_cast(k) + 0.5)); - } - out[j] = -static_cast(sum); - } - return out; -} - -} // namespace - -int main() { - using namespace leonida::xma2; - - // 1. Out-of-range index and truncated packet header rejection. - { - const std::uint8_t tiny[4]{}; - check(!parse_packet(tiny, 4, std::numeric_limits::max() / kPacketBytes + 1u).has_value(), - "parse_packet rejects overflow packet index"); - check(!parse_packet(tiny, 3, 0).has_value(), "parse_packet rejects truncated header"); - } - - // 2. Zero-length damaged frame before start terminates search cleanly. - { - std::vector data(kPacketBytes, 0u); - put_bits(data, 0, 32, 2u << 26); - const std::size_t start = kHeaderBits + 100u; - put_bits(data, start, 15, 200u); - const auto frame = read_frame(data.data(), data.size(), start); - check(frame.has_value() && frame->bits == 200u && !frame->next.has_value(), - "zero-length damaged frame before start ends search safely"); - } - - // 3. Multi-packet frame walk (frame crossing boundary into next packet). - { - std::vector data(2u * kPacketBytes, 0xffu); - auto hdr = [](std::uint32_t frames, std::uint32_t first) { return (frames << 26) | (first << 11); }; - put_bits(data, 0, 32, hdr(2, 0)); - put_bits(data, kPacketBits, 32, hdr(1, 48)); - put_bits(data, 32, 15, 100u); - put_bits(data, 132, 15, 16300u); - const std::size_t c_start = kPacketBits + 32u + 48u; - put_bits(data, c_start, 15, 60u); - - const auto a = read_frame(data.data(), data.size(), 32u); - const auto b = read_frame(data.data(), data.size(), 132u); - const auto c = read_frame(data.data(), data.size(), c_start); - check(a && a->bits == 100u && a->next == 132u, "frame A walks to frame B"); - check(b && b->bits == 16300u && b->next == c_start && b->data.size() == (16300u + 7u) / 8u, - "frame B crosses packet header into packet 1"); - check(c && c->bits == 60u && !c->next.has_value(), "frame C terminates at end of buffer"); - } - - // 4. Fast half-IMDCT matches direct cosine sum for n = 128, 256, 512. - { - bool all_close = true; - for (const std::size_t n : {std::size_t(128), std::size_t(256), std::size_t(512)}) { - std::vector input(n); - for (std::size_t i = 0; i < n; ++i) input[i] = static_cast((i * 7919u) % 97u) - 48.0f; - std::vector fast(n, 0.0f); - imdct_half(input.data(), fast.data(), n, 1.0f); - const auto ref = imdct_reference(input); - for (std::size_t i = 0; i < n; ++i) { - if (std::fabs(fast[i] - ref[i]) >= 1e-2f * (1.0f + std::fabs(ref[i]))) all_close = false; - } - } - check(all_close, "fast imdct_half matches direct cosine sum for 128/256/512"); - } - - // 5. MDCT + imdct_half + window_overlap reconstructs a continuous sine wave. - { - constexpr std::size_t n = 256; - std::vector signal(n * 6u); - for (std::size_t i = 0; i < signal.size(); ++i) { - signal[i] = std::sin(static_cast(i) * 0.05f) * 0.3f; - } - auto win = [&](std::size_t i) { - return std::sin((static_cast(i) + 0.5) * kPi / (2.0 * static_cast(n))); - }; - std::vector out(n * 7u, 0.0f); - for (std::size_t block = 0; block < 5u; ++block) { - const std::size_t base = block * n; - std::vector coeffs(n, 0.0f); - for (std::size_t k = 0; k < n; ++k) { - double sum = 0.0; - for (std::size_t i = 0; i < 2u * n; ++i) { - const double t = static_cast(i) + 0.5 + static_cast(n) / 2.0; - sum += -static_cast(signal[base + i]) * win(i) * - std::cos(kPi / static_cast(n) * t * (static_cast(k) + 0.5)); - } - coeffs[k] = static_cast(sum); - } - const std::size_t at = base + n / 2u; - imdct_half(coeffs.data(), out.data() + at, n, 2.0f / static_cast(n)); - if (block > 0u) window_overlap(out.data() + (at - n / 2u), sine_window(n).data(), n); - } - bool exact = true; - for (std::size_t i = n; i < 5u * n; ++i) { - if (std::fabs(out[i] - signal[i]) >= 1e-3f) exact = false; - } - check(exact, "windowed MDCT + half-IMDCT overlap-add reconstructs sine wave within 1e-3"); - } - - // 6. Decode 2 packets of 3 silent mono frames each + overlap flush. - { - std::vector data(2u * kPacketBytes, 0xffu); - for (std::size_t pkt = 0; pkt < 2u; ++pkt) { - const std::size_t base = pkt * kPacketBits; - put_bits(data, base, 32, 3u << 26); - for (std::size_t f = 0; f < 3u; ++f) { - const std::size_t at = base + 32u + f * 31u; - put_bits(data, at, 15, 31u); - put_bits(data, at + 15u, 2, 0b10u); // fixed layout, 1x 512-sample subframe - put_bits(data, at + 17u, 14, 0u); // gain, no trim, empty subframe - } - } - Decoder dec(1, 48000); - std::vector pcm; - std::optional cursor = 32u; - int frames = 0; - int errors = 0; - while (cursor) { - const auto frame = read_frame(data.data(), data.size(), *cursor); - if (!frame) break; - if (!dec.decode(frame->data.data(), frame->bits, pcm)) ++errors; - ++frames; - cursor = frame->next; - } - dec.flush(pcm); - bool all_zero = true; - for (std::int16_t s : pcm) { - if (s != 0) all_zero = false; - } - check(frames == 6 && errors == 0 && pcm.size() == 6u * kFrameSamples + kFrameSamples / 2u && all_zero, - "6 silent mono frames + flush produce 3328 zero PCM samples with 0 errors"); - } - - std::printf("%d check(s), %d failure(s)\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..5ef66abbcc 100644 --- a/runtime/xma_decoder/README.md +++ b/runtime/xma_decoder/README.md @@ -17,3 +17,9 @@ 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 at configure time when `cargo` is on `PATH` (the first build fetches the pinned `xma` git dependency) and links it into `gta6rt` and `acphal_test` with `LEONIDA_HAVE_XMA2_DECODER` defined. `runtime/shims/acphal.cpp` calls `leonida_xma2_decoder_create_hardware` once per XMA context and decodes whole 2048-byte packets, so loop points are rounded to packets. + +Without `cargo`, when that build fails, or with the cl.exe fallback of `scripts/build_runtime.ps1`, XMA voices output silence. 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..cda2721fb1 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(); diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index baa8f8d759..d575b42004 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -78,10 +78,10 @@ $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", "src\xma2_decoder.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\$_`"" } + $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\$_`"" } $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } $body = @" diff --git a/third_party/xma/NOTICE.md b/third_party/xma/NOTICE.md index 1e21768294..a7066b383d 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 `cargo` is found, `runtime/CMakeLists.txt` links this package statically into `gta6rt`; the runtime is GPL-3.0 and its full source is in this repository. From a99a3fb6ad419bf7f0a255d8b31fbd8112da1b39 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 04:03:38 -0300 Subject: [PATCH 4/9] acphal: preserve XMA packet chains and context lifetime --- runtime/shims/acphal.cpp | 113 +++++++++++++++++------------------ runtime/test/acphal_test.cpp | 44 +++++++++----- 2 files changed, 86 insertions(+), 71 deletions(-) diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp index 7f4de8fd83..2688f96e52 100644 --- a/runtime/shims/acphal.cpp +++ b/runtime/shims/acphal.cpp @@ -303,6 +303,7 @@ ApuRegion g_cached_heap; ApuRegion g_noncached_heap; // Tracked SHAPE context arrays +std::mutex g_shape_mutex; std::vector g_active_shape_arrays; // Resolves a contiguous [apu, apu + len) byte range inside the APU heap. @@ -419,7 +420,7 @@ class XmaEngine { ~XmaEngine() { unbind(); } void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) { - stop_worker(); + unbind(); std::unique_lock lock(table_mutex_); array_ = reinterpret_cast(array); voices_.clear(); @@ -427,15 +428,17 @@ class XmaEngine { for (uint32_t i = 0; i < count; ++i) { voices_.push_back(std::make_unique()); } - active_count_.store(0, std::memory_order_relaxed); } 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(); - std::unique_lock lock(table_mutex_); - array_ = nullptr; - voices_.clear(); - active_count_.store(0, std::memory_order_relaxed); } bool handle_command(uint32_t command, const void* config) { @@ -481,11 +484,11 @@ class XmaEngine { } void enable(uint32_t index) { - { - std::shared_lock table_lock(table_mutex_); - XmaContextView ctx = context_locked(index); - if (!ctx.words) return; + std::shared_lock table_lock(table_mutex_); + XmaContextView ctx = context_locked(index); + if (!ctx.words) return; + { std::lock_guard slot_lock(voices_[index]->mutex); const bool was_active = voices_[index]->voice.has_value(); // Clear error_status (26..30) and error flag (31). @@ -512,16 +515,16 @@ class XmaEngine { } 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::shared_lock table_lock(table_mutex_); - XmaContextView ctx = context_locked(index); - if (!ctx.words) return; - std::lock_guard slot_lock(voices_[index]->mutex); const uint32_t raw_size = ctx.field(0, 22, 5); const uint32_t size = raw_size ? raw_size : 1u; - const uint32_t read = (ctx.field(9, 0, 5) + blocks) % size; + 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); @@ -559,6 +562,7 @@ class XmaEngine { pcm.assign(samples, samples + count); return; } + voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence. } #else (void)voice; @@ -599,13 +603,16 @@ class XmaEngine { return true; } + const uint8_t* packet_data = data + packet * kXmaPacketBytes; + const uint8_t packet_skip = packet_data[3]; std::vector pcm; - decode_packet(ctx, voice, data + packet * kXmaPacketBytes, 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; voice.pcm.insert(voice.pcm.end(), pcm.begin() + static_cast(skip_samples), pcm.end()); - std::size_t next = packet + 1; + // 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) { @@ -921,45 +928,38 @@ HRESULT __stdcall AcpHalCreate(void** ppAcpHal) { HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { if (!ctx) return E_POINTER; - SHAPE_XMA_CONTEXT* xma_array = nullptr; - uint32_t xma_count = 0; - { - 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* { - if (count == 0) return nullptr; - void* ptr = std::calloc(count, elem_size); - if (ptr) g_active_shape_arrays.push_back(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}; - - xma_array = ctx->xmaContextArray; - xma_count = ctx->numXmaContexts; - } - - g_xma_engine.bind(xma_array, xma_count); + 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); + 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) + @@ -971,11 +971,10 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { // ---- AcpHalReleaseShapeContexts ---- HRESULT __stdcall AcpHalReleaseShapeContexts(SHAPE_CONTEXTS* ctx = nullptr) { + std::lock_guard lock(g_shape_mutex); // Stop and detach the XMA worker before freeing backing arrays. g_xma_engine.unbind(); - std::lock_guard lock(g_apu_mutex); - // Free all recorded context allocations for (void* p : g_active_shape_arrays) { if (p) std::free(p); diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp index 94ff8fa96e..58bb48227a 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp @@ -467,8 +467,9 @@ 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. { - // Two packets with one silent mono frame each. - std::vector stream(2 * 2048, 0xFFu); + // 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; @@ -478,9 +479,9 @@ int main() { (bit << (7 - (p % 8)))); } }; - for (size_t packet = 0; packet < 2; ++packet) { + for (size_t packet = 0; packet < 3; ++packet) { const size_t base = packet * 2048 * 8; - put_bits(base, 1u << 26, 32); // 1 frame, first_frame_bit = 0 + 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 @@ -494,8 +495,8 @@ int main() { 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 loop input buffer"); + 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()); void* out_va = nullptr; @@ -520,14 +521,16 @@ int main() { // Decodes the stream once on voice 2 with the given loop count and returns the number of // blocks written when the error flag rose, or -1 on timeout. - auto run_blocks = [&](uint32_t loops) -> int { + auto run_blocks = [&](uint32_t loops, bool split_inputs = false) -> int { std::memset(out_va, 0x55, 0x1000); - words[0] = 2u | (loops << 12) | (1u << 20) | (16u << 22); - words[1] = (1u << 31) | (3u << 27); // 48 kHz, mono, writable + words[0] = (split_inputs ? 2u : 3u) | (loops << 12) | + ((split_inputs ? 3u : 1u) << 20) | (16u << 22); + words[1] = (1u << 31) | (3u << 27) | (split_inputs ? 1u : 0u); 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 + 0x1000u; words[7] = out_apu; words[9] = 0u; @@ -547,9 +550,17 @@ int main() { return blocks; }; - check(run_blocks(0) == 8, "Two 1-frame packets without a loop write 8 blocks (1024 samples)"); - check(run_blocks(1) == 12, "One loop of packet 0 writes 12 blocks (packets 0, 0, 1)"); + 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"); + check(run_blocks(0, true) == 8 && (words[4] >> 31) == 1u, + "A skip to the end of input 0 continues at input 1"); + + 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"); check(fn_release(x_acp) == S_OK, "Release packet loop AcpHal succeeds"); free_mem(in_va); @@ -557,8 +568,7 @@ int main() { check(release_ctx(&xma_ctx) == S_OK, "Release packet loop SHAPE contexts"); } - // 9. ENABLE_XMA (starts/wakes the decoder worker) racing bind/release (stops it). - // Every release must return; a lost stop would hang this block. + // 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); @@ -581,6 +591,11 @@ int main() { &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; @@ -588,7 +603,8 @@ int main() { if (release_ctx(&race_ctx) != S_OK) ++bind_failures; } enabler.join(); - check(bind_failures == 0, "20000 bind/release cycles race ENABLE_XMA without hanging"); + 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"); } From a0327ee1af5bb44abfd1327d00167da526d1ac70 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 04:03:39 -0300 Subject: [PATCH 5/9] runtime: target the MSVC ABI for the Rust XMA2 decoder --- runtime/CMakeLists.txt | 13 +++++++++---- runtime/xma_decoder/README.md | 4 +++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 871c48c675..6b1b4af16f 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -110,24 +110,29 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) # Without it (or if that build fails) the runtime still builds and XMA voices output silence. 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}/release/leonida_xma2_decoder.lib) + 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 + 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 EQUAL 0 AND EXISTS ${_xma_lib}) + 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 "ws2_32;userenv;ntdll") + 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() diff --git a/runtime/xma_decoder/README.md b/runtime/xma_decoder/README.md index 5ef66abbcc..3cda1843a4 100644 --- a/runtime/xma_decoder/README.md +++ b/runtime/xma_decoder/README.md @@ -20,6 +20,8 @@ The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_3 ## Use in the runtime -`runtime/CMakeLists.txt` builds this crate at configure time when `cargo` is on `PATH` (the first build fetches the pinned `xma` git dependency) and links it into `gta6rt` and `acphal_test` with `LEONIDA_HAVE_XMA2_DECODER` defined. `runtime/shims/acphal.cpp` calls `leonida_xma2_decoder_create_hardware` once per XMA context and decodes whole 2048-byte packets, so loop points are rounded to packets. +`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. Without `cargo`, when that build fails, or with the cl.exe fallback of `scripts/build_runtime.ps1`, XMA voices output silence. From e02ec36bf315de960a9db244e971bf00cfd66406 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 04:29:18 -0300 Subject: [PATCH 6/9] acphal: synchronize XMA context words and bound the output ring --- runtime/shims/acphal.cpp | 64 ++++++++---------- runtime/test/acphal_test.cpp | 121 ++++++++++++++++++++++++---------- runtime/xma_decoder/README.md | 4 +- third_party/xma/NOTICE.md | 2 +- 4 files changed, 114 insertions(+), 77 deletions(-) diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp index 2688f96e52..05ceedd171 100644 --- a/runtime/shims/acphal.cpp +++ b/runtime/shims/acphal.cpp @@ -139,24 +139,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"); @@ -382,10 +365,9 @@ struct Xma2PcmFree { #endif struct XmaContextView { - volatile uint32_t* words = nullptr; + uint32_t* words = nullptr; - uint32_t get(std::size_t index) const { return words[index]; } - void set(std::size_t index, uint32_t value) const { words[index] = value; } + 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); @@ -395,7 +377,10 @@ struct XmaContextView { void 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; - set(index, (get(index) & ~mask) | ((value << shift) & mask)); + 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)) {} } std::size_t channels() const { return 1u + static_cast(field(1, 29, 1)); } @@ -407,6 +392,7 @@ struct XmaVoice { #endif std::deque pcm; std::size_t skip = 0; // samples per channel to drop (start/loop subframe skip) + std::optional next_input_packet; bool ended = false; }; @@ -422,7 +408,7 @@ class XmaEngine { void bind(SHAPE_XMA_CONTEXT* array, uint32_t count) { unbind(); std::unique_lock lock(table_mutex_); - array_ = reinterpret_cast(array); + array_ = array; voices_.clear(); voices_.reserve(count); for (uint32_t i = 0; i < count; ++i) { @@ -522,8 +508,8 @@ class XmaEngine { bool wake = false; { std::lock_guard slot_lock(voices_[index]->mutex); - const uint32_t raw_size = ctx.field(0, 22, 5); - const uint32_t size = raw_size ? raw_size : 1u; + 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) { @@ -537,7 +523,7 @@ class XmaEngine { private: XmaContextView context_locked(uint32_t index) const { if (!array_ || index >= voices_.size()) return {}; - return XmaContextView{array_ + static_cast(index) * 16}; + return XmaContextView{array_[index].words}; } // Fills `pcm` (interleaved s16) for one 2048-byte packet. Without the Rust decoder, or when it @@ -559,7 +545,7 @@ class XmaEngine { 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()); - pcm.assign(samples, samples + count); + if (count != 0) pcm.assign(samples, samples + count); return; } voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence. @@ -580,7 +566,7 @@ class XmaEngine { uint32_t current = ctx.field(4, 31, 1); const uint32_t valid = ctx.field(0, 20, 2); - if ((valid & (1u << current)) == 0) { + if (voice.next_input_packet || (valid & (1u << current)) == 0) { const uint32_t other = 1u - current; if ((valid & (1u << other)) == 0) { voice.ended = true; @@ -590,7 +576,9 @@ class XmaEngine { } current = other; ctx.set_field(4, 31, 1, current); - ctx.set_field(2, 0, 26, 0); + 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); @@ -599,6 +587,7 @@ class XmaEngine { 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); return true; } @@ -627,6 +616,7 @@ class XmaEngine { } if (next >= packets) { ctx.set_field(0, 20 + current, 1, 0); + voice.next_input_packet = next - packets; next = 0; } ctx.set_field(2, 0, 26, static_cast(next * kXmaPacketBits)); @@ -635,20 +625,18 @@ class XmaEngine { static void pump_voice(XmaContextView ctx, XmaVoice& voice) { const uint32_t size = ctx.field(0, 22, 5); - if (size == 0) return; + auto* ring = apu_span(ctx.get(7), size * kXmaBlockBytes); + if (!ring) return; - while (ctx.field(1, 31, 1) == 1) { + for (uint32_t blocks = 0; blocks < size && ctx.field(1, 31, 1) == 1; ++blocks) { int decode_guard = 0; while (voice.pcm.size() < kXmaSamplesPerBlock && decode_guard++ < 16) { if (!decode_one_packet(ctx, voice)) break; } if (voice.pcm.empty()) return; - const uint32_t write = ctx.field(0, 27, 5); - const uint32_t out_addr = - ctx.get(7) + write * static_cast(kXmaBlockBytes); - uint8_t* out = apu_span(out_addr, kXmaBlockBytes); - if (!out) 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; @@ -663,7 +651,7 @@ class XmaEngine { const uint32_t next_write = (write + 1u) % size; ctx.set_field(0, 27, 5, next_write); - if (next_write == ctx.field(9, 0, 5)) { + if (next_write == ctx.field(9, 0, 5) % size) { ctx.set_field(1, 31, 1, 0); } } @@ -728,7 +716,7 @@ class XmaEngine { } mutable std::shared_mutex table_mutex_; - volatile uint32_t* array_ = nullptr; + SHAPE_XMA_CONTEXT* array_ = nullptr; std::vector> voices_; std::atomic active_count_{0}; diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp index 58bb48227a..9ee2ee7ff3 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp @@ -6,6 +6,7 @@ #include +#include #include #include #include @@ -69,6 +70,14 @@ 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]); + } +}; + } // namespace int main() { @@ -348,7 +357,8 @@ int main() { // 8. End-to-end XMA2 context ring decoding via background decoder thread { - // Build a 2-packet XMA2 buffer with 3 silent mono frames per packet (6 frames total). + // 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) { @@ -361,12 +371,29 @@ int main() { }; for (size_t packet = 0; packet < 2; ++packet) { const size_t base = packet * 2048 * 8; - put_bits(base, 3u << 26, 32); // 3 frames, first_frame_bit = 0, skip = 0 + put_bits(base, (3u << 26) | (1u << 8), 32); + constexpr size_t frame_bits = 82; for (size_t f = 0; f < 3; ++f) { - const size_t at = base + 32 + f * 31; - 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) + 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. } } @@ -389,7 +416,7 @@ int main() { // Configure voice index 1: 2 packets in input 0, input 0 valid, 4 output blocks, // writable = 1, 48 kHz mono, read_bit = 32. - auto* words = static_cast(xma_ctx.xmaContextArray) + 16; + 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; @@ -418,27 +445,28 @@ int main() { for (int wait = 0; wait < 500 && ((words[1] >> 31) & 1u) == 1u; ++wait) { Sleep(1); } - check(((words[1] >> 31) & 1u) == 0u, - "Background XMA2 decoder fills ring and clears writable flag"); + 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"); - bool ring_zeroed = true; const auto* ring_bytes = static_cast(out_va); - for (size_t i = 0; i < 0x400; ++i) { - if (ring_bytes[i] != 0) { - ring_zeroed = false; - break; - } - } - check(ring_zeroed, "Decoded silent PCM overwrote sentinel bytes across all 4 ring blocks"); +#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}; - for (int step = 0; step < 20; ++step) { - check(fn_submit(x_acp, 18, 0xf2 + static_cast(step), - 0xffffffffu, advance_args, 0) == S_OK, - "ADVANCE_XMA_READ succeeds"); + 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]; @@ -449,7 +477,11 @@ int main() { 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"); 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)"); @@ -505,7 +537,7 @@ int main() { "ApuAlloc 16-block loop output ring"); // Voice index 2. - auto* words = static_cast(xma_ctx.xmaContextArray) + 32; + 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); @@ -519,23 +551,27 @@ int main() { const auto fn_release = reinterpret_cast(vt[5]); check(fn_connect(x_acp, 0x1000, 0x1000) == S_OK, "Connect for packet loop test"); - // Decodes the stream once on voice 2 with the given loop count and returns the number of - // blocks written when the error flag rose, or -1 on timeout. - auto run_blocks = [&](uint32_t loops, bool split_inputs = false) -> int { + 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); - words[0] = (split_inputs ? 2u : 3u) | (loops << 12) | - ((split_inputs ? 3u : 1u) << 20) | (16u << 22); - words[1] = (1u << 31) | (3u << 27) | (split_inputs ? 1u : 0u); + 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 + 0x1000u; + words[6] = in_apu + input_0_packets * 2048u; words[7] = out_apu; - words[9] = 0u; + words[9] = read; + }; - const uint32_t enable_arg = 2u; - check(fn_submit(x_acp, 5, 0xf3, 0xffffffffu, &enable_arg, 0) == S_OK, + 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 { + configure_voice(loops, input_0_packets, 16, 0, 0); + 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) { @@ -544,8 +580,7 @@ int main() { const int blocks = ((words[2] >> 31) & 1u) != 0u ? static_cast((words[0] >> 27) & 0x1Fu) : -1; - const uint32_t disable_arg = 2u; - check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &disable_arg, 0) == S_OK, + check(fn_submit(x_acp, 7, 0xf4, 0xffffffffu, &voice_index, 0) == S_OK, "DISABLE_XMA voice 2 succeeds"); return blocks; }; @@ -553,8 +588,24 @@ 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"); - check(run_blocks(0, true) == 8 && (words[4] >> 31) == 1u, + 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"); + + 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"); + 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"); words[0] = 3u << 22; // three ring blocks words[9] = 2u; diff --git a/runtime/xma_decoder/README.md b/runtime/xma_decoder/README.md index 3cda1843a4..44eb4288a1 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 @@ -22,6 +20,6 @@ The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_3 `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. +`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. diff --git a/third_party/xma/NOTICE.md b/third_party/xma/NOTICE.md index a7066b383d..760e6c77d6 100644 --- a/third_party/xma/NOTICE.md +++ b/third_party/xma/NOTICE.md @@ -11,4 +11,4 @@ The upstream NOTICE identifies this package as a Rust port of FFmpeg's WMA Pro/X 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 `cargo` is found, `runtime/CMakeLists.txt` links this package statically into `gta6rt`; the runtime is GPL-3.0 and its full source is in this repository. +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. From 0fe9c0bdfb844678209c0d0ffdd37d2533d1f57e Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 05:27:55 -0300 Subject: [PATCH 7/9] 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(-) 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 6b1b4af16f..98b10ed2af 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 05ceedd171..d273aaa85d 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 @@ class XmaEngine { ~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 @@ class XmaEngine { { 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 @@ class XmaEngine { 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 @@ class XmaEngine { 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 @@ class XmaEngine { 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 @@ class XmaEngine { 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 9ee2ee7ff3..540906ec86 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 44eb4288a1..9db8018104 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 cda2721fb1..69fedf49e0 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 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!( From 4e9407a409641b644393a66b41d35e431f1c5ddb Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 06:21:32 -0300 Subject: [PATCH 8/9] acphal: isolate voice failures and keep input transitions ordered --- runtime/shims/acphal.cpp | 162 +++++++++++++++++++++-------------- runtime/test/acphal_test.cpp | 134 ++++++++++++++++++++++++----- 2 files changed, 210 insertions(+), 86 deletions(-) diff --git a/runtime/shims/acphal.cpp b/runtime/shims/acphal.cpp index d273aaa85d..4b516cf8f7 100644 --- a/runtime/shims/acphal.cpp +++ b/runtime/shims/acphal.cpp @@ -37,6 +37,8 @@ #include #include #include +#include +#include #include #include @@ -193,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; @@ -291,10 +300,7 @@ struct ShapeArrayFree { void operator()(void* array) const noexcept { std::free(array); } }; -struct ShapeAllocation { - SHAPE_CONTEXTS* caller; - std::array, 6> arrays; -}; +using ShapeAllocation = std::array, 6>; std::mutex g_shape_mutex; std::vector g_shape_allocations; @@ -308,7 +314,7 @@ uint8_t* apu_span(uint32_t apu, std::size_t len) { return g_cached_heap.span_from_offset(offset, len); } if (g_noncached_heap.base) { - const uint64_t cached_span = g_cached_heap.size; + 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); @@ -393,16 +399,18 @@ struct XmaContextView { while (!word.compare_exchange_weak(previous, (previous & ~mask) | field_value)) {} } - std::size_t channels() const { return 1u + static_cast(field(1, 29, 1)); } }; struct XmaVoice { + explicit XmaVoice(uint32_t format_bits) : format(format_bits) {} + std::size_t channels() const { return 1u + (format >> 2); } + #if defined(LEONIDA_HAVE_XMA2_DECODER) std::unique_ptr decoder; #endif std::deque pcm; std::size_t loop_skip = 0; // samples per channel to drop after a rewind - std::optional exhausted_input; + uint32_t format; // SHAPE word 1 bits 27..29, rate and channel layout bool ended = false; }; @@ -487,16 +495,23 @@ class XmaEngine { { std::lock_guard slot_lock(voices_[index]->mutex); auto& voice = voices_[index]->voice; - // Clear error_status (26..30) and error flag (31). - ctx.set_field(2, 26, 6, 0); - + 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(); + voice.emplace(format); active_count_.fetch_add(1, std::memory_order_relaxed); + } else if (voice->format != format) { + voice->pcm.clear(); + 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); } - ensure_worker_and_wake(); } void disable(uint32_t index) { @@ -537,13 +552,13 @@ class XmaEngine { // Fills `pcm` (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(XmaContextView ctx, XmaVoice& voice, const uint8_t* bytes, + static void decode_packet(XmaVoice& voice, const uint8_t* bytes, std::vector& pcm) { - const std::size_t channels = ctx.channels(); + 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[ctx.field(1, 27, 2) & 3u], + if (leonida_xma2_decoder_create_hardware(kXmaRates[voice.format & 3u], static_cast(channels), &raw) == LEONIDA_XMA2_OK) { voice.decoder.reset(raw); } @@ -559,8 +574,6 @@ class XmaEngine { } voice.decoder.reset(); // Resume with a clean state after replacing a packet with silence. } -#else - (void)voice; #endif pcm.assign(static_cast(bytes[0] >> 2) * kXmaFrameSamples * channels, 0); } @@ -571,7 +584,7 @@ class XmaEngine { static bool decode_one_packet(XmaContextView ctx, XmaVoice& voice) { if (voice.ended) return false; - const std::size_t channels = ctx.channels(); + const std::size_t channels = voice.channels(); uint32_t current = ctx.field(4, 31, 1); const uint32_t valid = ctx.field(0, 20, 2); @@ -580,11 +593,8 @@ class XmaEngine { 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; + if ((valid & (1u << current)) == 0) { + current ^= 1u; ctx.set_field(4, 31, 1, current); } @@ -593,15 +603,15 @@ class XmaEngine { 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, voice, current, packet >= packets ? packet - packets : 0); + finish_input(ctx, 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); + // The sized constructor can propagate even an MSVC Debug allocation failure. + std::vector pcm(0); + decode_packet(voice, packet_data, pcm); 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); @@ -629,18 +639,19 @@ class XmaEngine { if (loops != 255u) ctx.set_field(0, 12, 8, loops - 1u); } if (next >= packets) { - finish_input(ctx, voice, current, 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, XmaVoice& voice, uint32_t current, + static void finish_input(XmaContextView ctx, 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)); + const uint32_t other = 1u - current; + if (ctx.field(0, 20 + other, 1) != 0) ctx.set_field(4, 31, 1, other); ctx.set_field(0, 20 + current, 1, 0); } @@ -684,8 +695,16 @@ class XmaEngine { if (!array_) return; for (std::size_t i = 0; i < voices_.size(); ++i) { std::lock_guard slot_lock(voices_[i]->mutex); - if (voices_[i]->voice.has_value()) { - pump_voice(context_locked(static_cast(i)), *voices_[i]->voice); + 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); } } } @@ -812,12 +831,16 @@ struct AcpHalImpl final : IAcpHal { AcpMessage msg{}; msg.kind = kind; msg.dropped = dropped_; - dropped_ = 0; msg.usec = static_cast(elapsed_usec_locked()); if (payload && len > 0) { std::memcpy(msg.data, payload, std::min(len, sizeof(msg.data))); } - messages_.push_back(msg); + 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) @@ -844,7 +867,7 @@ struct AcpHalImpl final : IAcpHal { // 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 { + const void* config, uint32_t notification) override try { (void)frame; auto read_word = [config](std::size_t index) -> uint32_t { if (!config) return 0u; @@ -898,6 +921,10 @@ struct AcpHalImpl final : IAcpHal { trace_call("AcpHal::SubmitCommand", ""); return S_OK; + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } catch (const std::system_error&) { + return E_FAIL; } // Slot 3: PopMessage — returns 0 without touching `out` when the queue is empty. @@ -928,7 +955,12 @@ struct AcpHalImpl final : IAcpHal { 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; } @@ -940,13 +972,13 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { std::lock_guard lock(g_shape_mutex); - ShapeAllocation pending{ctx, {}}; + 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) throw std::bad_alloc(); - pending.arrays[array_index++].reset(ptr); + pending[array_index++].reset(ptr); return ptr; }; @@ -980,7 +1012,7 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { result.apuPcmContextArray = {result.pcmContextArray ? kApuBaseAddress + 0x5000 : 0}; g_shape_allocations.reserve(g_shape_allocations.size() + 1); - g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts); + if (result.xmaContextArray) g_xma_engine.bind(result.xmaContextArray, result.numXmaContexts); } catch (const std::bad_alloc&) { return E_OUTOFMEMORY; } @@ -1003,24 +1035,13 @@ HRESULT __stdcall AcpHalAllocateShapeContexts(SHAPE_CONTEXTS* ctx) { // ---- AcpHalReleaseShapeContexts ---- -HRESULT __stdcall AcpHalReleaseShapeContexts(void* argument = nullptr) { +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(); - // 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; - 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", ""); @@ -1033,6 +1054,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( @@ -1052,9 +1076,15 @@ 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; } @@ -1062,7 +1092,7 @@ HRESULT __stdcall ApuCreateHeap(uint32_t cachedSizeInBytes, HRESULT __stdcall ApuAlloc(void** virtualAddress, uint32_t* physicalAddress, uint32_t sizeInBytes, uint32_t alignmentInBytes, - uint32_t flags) { + uint32_t flags) try { if (!virtualAddress) return E_POINTER; *virtualAddress = nullptr; if (physicalAddress) *physicalAddress = 0; @@ -1107,17 +1137,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 ---- @@ -1152,7 +1182,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); } @@ -1169,7 +1199,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 540906ec86..3ef8df4cd6 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp @@ -21,11 +21,17 @@ // 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 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 (allocations_before_failure > 0) --allocations_before_failure; if (void* memory = std::malloc(size ? size : 1)) return memory; throw std::bad_alloc(); @@ -94,9 +100,13 @@ 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; +// 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) { @@ -110,17 +120,24 @@ void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip) { 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. - put(1, 1); // Coefficients are present. + 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); // Use only run/level coding. + put(0, 8 * channels); // 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. + 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); } @@ -130,6 +147,7 @@ void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip) { int main() { 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( @@ -174,12 +192,19 @@ int main() { "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); @@ -200,8 +225,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"); @@ -211,8 +236,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)"); @@ -329,8 +354,12 @@ int main() { "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) @@ -410,6 +439,11 @@ int main() { 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"); @@ -534,8 +568,9 @@ int main() { void* in_va = nullptr; uint32_t in_apu = 0; - check(alloc(&in_va, &in_apu, 0x2000, 0x800, 1) == S_OK && in_va != nullptr, - "ApuAlloc 4-packet loop and refill input buffer"); + 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); @@ -651,6 +686,10 @@ int main() { 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"); @@ -681,6 +720,61 @@ int main() { 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 + + // 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); From 713eec5031a6a7d1b1626f090d742531007b28e5 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 06:47:57 -0300 Subject: [PATCH 9/9] acphal: stabilize APU mappings and reuse XMA PCM storage --- runtime/CMakeLists.txt | 1 + runtime/shims/acphal.cpp | 61 ++++++++++++++++++++++-------------- runtime/test/acphal_test.cpp | 53 +++++++++++++++++++++++++++++-- 3 files changed, 88 insertions(+), 27 deletions(-) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 98b10ed2af..e3d2b8eba2 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1205,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 4b516cf8f7..f1c33ddd9e 100644 --- a/runtime/shims/acphal.cpp +++ b/runtime/shims/acphal.cpp @@ -390,25 +390,28 @@ struct XmaContextView { return (get(index) >> shift) & mask; } - void set_field(std::size_t index, uint32_t shift, uint32_t bits, uint32_t value) const { + 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) : format(format_bits) {} + 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::deque pcm; + 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; @@ -503,6 +506,7 @@ class XmaEngine { 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) @@ -550,10 +554,9 @@ class XmaEngine { return XmaContextView{array_[index].words}; } - // Fills `pcm` (interleaved s16) for one 2048-byte packet. Without the Rust decoder, or when it + // 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, - std::vector& pcm) { + 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) { @@ -569,13 +572,13 @@ class XmaEngine { 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) pcm.assign(samples, samples + count); + 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 - pcm.assign(static_cast(bytes[0] >> 2) * kXmaFrameSamples * channels, 0); + 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. @@ -591,7 +594,7 @@ class XmaEngine { if (valid == 0) { voice.ended = true; ctx.set_field(2, 26, 6, kXmaErrorInputInvalid | 32u); - return !voice.pcm.empty(); + return voice.queued_samples() != 0; } if ((valid & (1u << current)) == 0) { current ^= 1u; @@ -609,20 +612,28 @@ class XmaEngine { const uint8_t* packet_data = data + packet * kXmaPacketBytes; const uint8_t packet_skip = packet_data[3]; - // The sized constructor can propagate even an MSVC Debug allocation failure. - std::vector pcm(0); - decode_packet(voice, packet_data, pcm); + // 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, pcm.size() / subframe_samples); + 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)); } - 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. std::size_t next = packet_skip == 0xFFu ? packets : packet + 1 + packet_skip; @@ -651,8 +662,10 @@ class XmaEngine { // 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; - if (ctx.field(0, 20 + other, 1) != 0) ctx.set_field(4, 31, 1, other); - ctx.set_field(0, 20 + current, 1, 0); + 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) { @@ -663,19 +676,18 @@ class XmaEngine { for (uint32_t blocks = 0; blocks < size && ctx.field(1, 31, 1) == 1; ++blocks) { int decode_guard = 0; - while (voice.pcm.size() < kXmaSamplesPerBlock && decode_guard++ < 16) { + while (voice.queued_samples() < kXmaSamplesPerBlock && decode_guard++ < 16) { if (!decode_one_packet(ctx, voice)) break; } - if (voice.pcm.empty()) return; + 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.empty()) { - sample = voice.pcm.front(); - voice.pcm.pop_front(); + 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); @@ -1111,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, diff --git a/runtime/test/acphal_test.cpp b/runtime/test/acphal_test.cpp index 3ef8df4cd6..be2c6f1e1a 100644 --- a/runtime/test/acphal_test.cpp +++ b/runtime/test/acphal_test.cpp @@ -22,6 +22,8 @@ // 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) { @@ -32,6 +34,9 @@ void* operator new(std::size_t size) { 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(); @@ -145,7 +150,7 @@ void write_xma_packet(uint8_t* packet, uint32_t frames, uint8_t packet_skip, } // 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"); @@ -186,6 +191,25 @@ 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, @@ -500,6 +524,8 @@ int main() { // 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"); @@ -544,6 +570,11 @@ int main() { } 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)"); @@ -647,9 +678,9 @@ int main() { #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, + check(run_blocks(0, 2) == 8, "A skip to the end of input 0 continues at input 1"); - check(run_blocks(0, 1) == 8 && (words[4] >> 31) == 1u, + 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), @@ -740,6 +771,22 @@ int main() { 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) {