Merge #2044 from BubsMcgee: decode Opus packets through a Rust sidecar (RT-XAPU-OPUS-DECODE), with #1144 from nicoco23: xapu.dll as a command queue (RT-XAPU-CONNECT-LAYOUTS)

Head 4cfbdfc0b, which contains #1144's head 6ee7ef89b.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jan Trencansky
2026-11-26 09:16:29 -05:00
14 changed files with 1340 additions and 172 deletions

View File

@ -52,6 +52,26 @@ turns such an address back into a pointer. That is an inference from the shapes;
`XApuEnqueueCommand` and `XApuDequeueResult` share one handle global, which `XApuDisconnect` clears: a command queue
with a result queue, connected once and torn down once. How `chad.dll`'s handle relates to it is not read.
`runtime/shims/xapu_queue.cpp` serves the five `xapu.dll` imports and `runtime/shims/xapu_chad.cpp` the five
`chad.dll` ones.
The `xapu.dll` signatures, structure layouts, command kinds, option bits and error codes come from Marvisak/VIctory
(<https://github.com/Marvisak/VIctory>, GPL-3.0-or-later, `crates/victory-hle/src/modules/apu.rs` at commit `ffe310e`),
which runs the retail executable through these calls. Only the facts are used (see
[related_projects.md](related_projects.md)); the top of `xapu_queue.cpp` lists them. They agree with the shapes above:
| Shape measured here | What the layout says |
|---|---|
| `XApuConnect`: a 24-byte title global first, a 16-byte output second | the global is an input of six dwords (processing kind, streams, commands per stream, memory bytes, frames per output, options); the output is the zeroed memory and a result event |
| `XApuEnqueueCommand`: a stack-built command whose first dword is 1, 2 or 3 and second a stream slot, then 0 | a 24-byte command id (kind, stream, sequence, options, context): 1 activates, 2 deactivates, 3 processes an Opus packet; the third argument is an optional count of the commands accepted |
| `XApuDequeueResult`: a 0x50-byte result, read at +0, +4 and +0x34 | the command id at +0, the output byte count at +0x34; `0x8AC81001` while none is ready |
| `XApuDisconnect`: the handle, then `0x20` | the second argument is not read |
What the results carry is the shim's own: each accepted command gets one result in command order, with the error codes
of the layout. A process result carries the frame count and PCM when `runtime/opus_decoder` is built, and otherwise the
frame count of the Opus packet's table-of-contents byte (RFC 6716, section 3.1) with zeros in its output (silence).
`xapu_chad_test` covers the layouts and the silent path; `xapu_opus_test` covers the decoded path with a generated
packet.
## `xg_xs.dll` and `XCRDAPI.dll`
| Import | Sites | What the sites show |

View File

@ -170,7 +170,7 @@ policy "other" (none is counted as returning an `HRESULT`), and they come from s
| `xg_xs.dll` | 2: `XGCreateTextureComputer`, `XGSuggestSwizzleMode` | texture layout computation |
| `XCRDAPI.dll` | 1: `DStorageGetFactory` | DirectStorage |
| `chad.dll` | 5: `XDspActivate`, `XDspConnectWithMaximumStreamLimit`, `XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand` | the audio DSP |
| `xapu.dll` | 5: `XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, `XApuEnqueueCommand`, `XApuGetResultCount` | the audio processing unit |
| `xapu.dll` | 5: `XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, `XApuEnqueueCommand`, `XApuGetResultCount` | the audio processing unit (Opus decode when `runtime/opus_decoder` is built) |
| `AcpHal.dll` | 9: `AcpHalAllocateShapeContexts`, `AcpHalCreate`, `AcpHalReleaseShapeContexts`, `ApuAlloc`, `ApuCreateHeap`, `ApuFree`, `ApuIsVirtualAddressValid`, `ApuMapApuAddress`, `ApuMapVirtualAddress` | the audio hardware layer |
The game executable imports two functions from `xg_xs.dll`, the console's texture layout library:
@ -203,17 +203,19 @@ again at detach (reason 0), and there is no `exception`, `error` or `unimplement
unimplemented imports is reached by the TLS callbacks or the `DllMain`s.
The executable's audio imports `xapu.dll` (`XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`,
`XApuEnqueueCommand`, `XApuGetResultCount`) and `chad.dll` (`XDspActivate`, `XDspConnectWithMaximumStreamLimit`,
`XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand`) are served by `runtime/shims/xapu_chad.cpp`. The shapes were
read statically from the executable's call sites: one each, four for `XApuEnqueueCommand`. Both connects succeed with
a handle; the APU connect also returns a zeroed shared buffer the title writes stream input to and reads output from.
Commands are accepted and not processed, so the audio stays silent. A stream open (type 1) and a stream close
(type 2) each queue one result of the same type and slot, because the title frees a stream id only when the close
result arrives. `XDspActivate` writes its two outputs as pointers to zeroed memory, which the title reads as "command
done" after each `XDspSubmitCommand`. `XApuConnect` leaves its first argument, a global of the title, untouched. The
buffer size (128 stream slots), the two results and the zeroed DSP status are hypotheses, explained in the file.
`xapu_chad_test` calls all ten in those shapes. With `--trace`, the first call of each, and the first command of each type, is an
`audio_queue` event.
`XApuEnqueueCommand`, `XApuGetResultCount`) are served by `runtime/shims/xapu_queue.cpp`; `chad.dll`
(`XDspActivate`, `XDspConnectWithMaximumStreamLimit`, `XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand`) by
`runtime/shims/xapu_chad.cpp`. The shapes were read statically from the executable's call sites: one each, four for
`XApuEnqueueCommand`. `XApuConnect` reads the title's 24-byte `ConnectInput` (process 1 = Opus at 48 kHz, stream
count, commands per stream, a shared buffer, options) and returns `{shared buffer, result event}`; it never writes the
input. Activate, process, deactivate and reset commands are copied from the title's stack command, and each queues one
result in order. A process command decodes its Opus packet through `runtime/opus_decoder` (Rust over the BSD-3-Clause
`opus-pure`) into the slot's output, honouring first frame, frame count, output length and the deinterleaved option;
without the crate the result carries the table-of-contents frame count and silence. The layouts follow Marvisak/VIctory
`crates/victory-hle/src/modules/apu.rs` (GPL-3.0-or-later). `XDspActivate` writes its two outputs as pointers to zeroed
memory, which the title reads as "command done" after each `XDspSubmitCommand`; the DSP stays silent. `xapu_chad_test`
covers the layouts, the queue and the silent path; `xapu_opus_test` the decoded path. With `--trace`, the first call of
each, and the first command of each type, is an `audio_queue` event.
The table above was measured before this shim and still lists these ten as unimplemented; they are served now. The call shapes agree with `docs/audio_hal_exe_calls.md`, which was measured with `tools/import_call_sites.py`.
What this does not show: `--run` has not been run, so the entry point has not been called and no import is known to be

View File

@ -158,6 +158,54 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable")
endif()
# Rust Opus decoder (runtime/opus_decoder), the same pattern as the XMA2 decoder: cargo at
# configure time, a prebuilt -DLEONIDA_OPUS_DECODER_LIB, or the silent path in xapu_queue.cpp.
option(LEONIDA_REQUIRE_OPUS_DECODER "Fail configure if the Rust Opus decoder is unavailable" OFF)
set(LEONIDA_OPUS_DECODER_LIB "" CACHE FILEPATH
"Prebuilt leonida_opus_decoder.lib (skips running cargo at configure time)")
include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/opus_decoder.cmake")
leonida_resolve_prebuilt_opus_decoder("${LEONIDA_OPUS_DECODER_LIB}" "${CMAKE_BINARY_DIR}" _opus_lib_resolved)
if(_opus_lib_resolved)
message(STATUS "Using prebuilt Rust Opus decoder: ${_opus_lib_resolved}")
else()
if(NOT LEONIDA_CARGO)
find_program(LEONIDA_CARGO cargo)
endif()
if(LEONIDA_CARGO)
set(_opus_target x86_64-pc-windows-msvc)
set(_opus_target_dir ${CMAKE_BINARY_DIR}/opus_decoder)
set(_opus_lib ${_opus_target_dir}/${_opus_target}/release/leonida_opus_decoder.lib)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.toml
${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.lock
${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/src/lib.rs)
execute_process(
COMMAND ${LEONIDA_CARGO} build --release --locked --target ${_opus_target}
--manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.toml
--target-dir ${_opus_target_dir}
TIMEOUT 300
RESULT_VARIABLE _opus_result)
if(_opus_result STREQUAL "0" AND EXISTS "${_opus_lib}")
set(_opus_lib_resolved "${_opus_lib}")
else()
message(WARNING "cargo build of runtime/opus_decoder failed: the XAPU Opus path will be silent")
endif()
else()
message(STATUS "cargo not found: runtime/opus_decoder not built, the XAPU Opus path will be silent")
endif()
endif()
if(_opus_lib_resolved)
add_library(leonida_opus_decoder STATIC IMPORTED)
set_target_properties(leonida_opus_decoder PROPERTIES
IMPORTED_LOCATION "${_opus_lib_resolved}"
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder"
INTERFACE_COMPILE_DEFINITIONS LEONIDA_HAVE_OPUS_DECODER=1
INTERFACE_LINK_LIBRARIES "kernel32;ntdll;userenv;ws2_32;dbghelp;synchronization")
endif()
if(LEONIDA_REQUIRE_OPUS_DECODER AND NOT TARGET leonida_opus_decoder)
message(FATAL_ERROR "LEONIDA_REQUIRE_OPUS_DECODER is enabled, but the Rust Opus decoder is unavailable")
endif()
find_package(Python3 COMPONENTS Interpreter REQUIRED)
set(bcpack_tools "${CMAKE_CURRENT_SOURCE_DIR}/../tools")
set(bcpack_tables "${CMAKE_CURRENT_BINARY_DIR}/bcpack_tables.inc")
@ -199,6 +247,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
shims/com_shim.cpp
shims/silent_audio.cpp
shims/bcrypt_rng.cpp
shims/xapu_queue.cpp
shims/xapu_chad.cpp
shims/dstorage.cpp
)
@ -352,6 +401,9 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder)
target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder)
endif()
if(TARGET leonida_opus_decoder)
target_link_libraries(gta6rt PRIVATE leonida_opus_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.
@ -382,9 +434,11 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
target_link_options(dstorage_test PRIVATE /OPT:NOREF)
target_link_libraries(dstorage_test PRIVATE gta6rt_bcpack psapi)
# xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test.
# xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test; Opus
# frame counts from hand-made packets.
add_executable(xapu_chad_test
test/xapu_chad_test.cpp
shims/xapu_queue.cpp
shims/xapu_chad.cpp
shims/registry.cpp
)
@ -393,6 +447,20 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
target_compile_options(xapu_chad_test PRIVATE /W4 /permissive- /utf-8)
target_link_options(xapu_chad_test PRIVATE /OPT:NOREF)
if(TARGET leonida_opus_decoder)
# xapu_queue.cpp with the decoder compiled in, against the generated Opus tone.
add_executable(xapu_opus_test
test/xapu_opus_test.cpp
shims/xapu_queue.cpp
shims/registry.cpp
)
target_include_directories(xapu_opus_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims)
target_compile_definitions(xapu_opus_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_options(xapu_opus_test PRIVATE /W4 /permissive- /utf-8)
target_link_options(xapu_opus_test PRIVATE /OPT:NOREF)
target_link_libraries(xapu_opus_test PRIVATE leonida_opus_decoder)
endif()
# The boot stack's earlier xapu.dll and chad.dll shims (shims/xapu.cpp, shims/chad.cpp), which gta6rt no longer
# links (it serves both DLLs from xapu_chad.cpp): their ABI tests stay as tests of those files.
# xapu shim ABI test: resolves the registered xapu.dll exports through the registry.
@ -1599,6 +1667,9 @@ if(BUILD_TESTING)
if(WIN32 AND TARGET xapu_chad_test)
add_test(NAME xapu_chad COMMAND xapu_chad_test)
endif()
if(WIN32 AND TARGET xapu_opus_test)
add_test(NAME xapu_opus COMMAND xapu_opus_test)
endif()
if(WIN32 AND TARGET xapu_test)
add_test(NAME xapu COMMAND xapu_test)
endif()

View File

@ -0,0 +1,23 @@
# Resolves -DLEONIDA_OPUS_DECODER_LIB=<path> for runtime/CMakeLists.txt.
#
# When LEONIDA_OPUS_DECODER_LIB is set, the runtime links that prebuilt static library directly and
# skips running cargo at configure time. A value that does not name an existing file is a configure
# error rather than a silent fallback to silent XAPU output.
function(leonida_resolve_prebuilt_opus_decoder lib_input base_dir out_var)
if(NOT lib_input)
set(${out_var} "" PARENT_SCOPE)
return()
endif()
if(IS_ABSOLUTE "${lib_input}")
set(_resolved "${lib_input}")
else()
cmake_path(ABSOLUTE_PATH lib_input BASE_DIRECTORY "${base_dir}" NORMALIZE OUTPUT_VARIABLE _resolved)
endif()
if(EXISTS "${_resolved}" AND NOT IS_DIRECTORY "${_resolved}")
set(${out_var} "${_resolved}" PARENT_SCOPE)
else()
message(FATAL_ERROR
"LEONIDA_OPUS_DECODER_LIB does not point to an existing file: ${_resolved} "
"(pass the path to leonida_opus_decoder.lib or leave it empty to build with cargo)")
endif()
endfunction()

16
runtime/opus_decoder/Cargo.lock generated Normal file
View File

@ -0,0 +1,16 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "leonida-opus-decoder"
version = "0.1.0"
dependencies = [
"opus-pure",
]
[[package]]
name = "opus-pure"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da6dcc20af557d030b6f206e75c764bcda8c28a5bd03c73935c7e8fcf5f4f4a"

View File

@ -0,0 +1,16 @@
[package]
name = "leonida-opus-decoder"
version = "0.1.0"
edition = "2021"
license = "GPL-3.0-or-later"
publish = false
[lib]
name = "leonida_opus_decoder"
crate-type = ["staticlib", "rlib"]
[dependencies]
opus-pure = "0.2.4"
[profile.release]
panic = "unwind"

View File

@ -0,0 +1,33 @@
# Opus decoder C ABI
This crate exposes a C ABI around the BSD-3-Clause `opus-pure` package for the console audio
decoder (`xapu.dll`). The command protocol lives in `runtime/shims/xapu_chad.cpp`; this crate only
decodes one Opus packet into interleaved f32 PCM, resets the decoder, and (for tests) encodes a
synthetic tone.
## Build
```sh
cargo fmt --manifest-path runtime/opus_decoder/Cargo.toml -- --check
cargo test --manifest-path runtime/opus_decoder/Cargo.toml --locked
cargo build --release --manifest-path runtime/opus_decoder/Cargo.toml --locked
```
`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 `xapu_chad_test` with
`LEONIDA_HAVE_OPUS_DECODER` defined. The first build fetches `opus-pure` from crates.io. Set
`CARGO_NET_OFFLINE=true` for a configure that uses only the local Cargo cache.
Without `cargo`, when the build fails, or with the `cl.exe` fallback of `scripts/build_runtime.ps1`,
the XAPU path stays silent. Use `-DLEONIDA_REQUIRE_OPUS_DECODER=ON` to require the decoder in a
CMake build.
To link an already-built `leonida_opus_decoder.lib` without invoking `cargo` during CMake
configure, pass `-DLEONIDA_OPUS_DECODER_LIB=<path>`.
## Facts and credit
The `xapu.dll` command protocol (connect input/output, per-stream command budget, activate /
process / reset / deactivate, result order) follows Marvisak/VIctory
`crates/victory-hle/src/modules/apu.rs` (GPL-3.0-or-later), which this repository already credits for
other modules. `opus-pure` is BSD-3-Clause and stays a dependency; no code from it is copied.

View File

@ -0,0 +1,44 @@
#ifndef LEONIDA_OPUS_DECODER_H
#define LEONIDA_OPUS_DECODER_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* 120 ms at 48 kHz: the longest Opus packet, in samples per channel. */
#define LEONIDA_OPUS_MAX_FRAMES 5760u
typedef struct LeonidaOpusDecoder LeonidaOpusDecoder;
enum LeonidaOpusStatus {
LEONIDA_OPUS_OK = 0,
LEONIDA_OPUS_INVALID_ARGUMENT = 1,
LEONIDA_OPUS_INVALID_FORMAT = 2,
LEONIDA_OPUS_DECODER_FAILURE = 3,
LEONIDA_OPUS_OUT_OF_MEMORY = 4,
LEONIDA_OPUS_PANIC = 5,
LEONIDA_OPUS_BUFFER_TOO_SMALL = 6,
};
int32_t leonida_opus_decoder_create(uint32_t sample_rate, uint32_t channels,
LeonidaOpusDecoder **out_decoder);
uint32_t leonida_opus_decoder_channels(const LeonidaOpusDecoder *decoder);
int32_t leonida_opus_decode_packet(LeonidaOpusDecoder *decoder,
const uint8_t *input, size_t input_len,
float *out, size_t out_capacity_frames,
uint32_t *out_frames);
int32_t leonida_opus_decoder_reset(LeonidaOpusDecoder *decoder);
void leonida_opus_decoder_destroy(LeonidaOpusDecoder *decoder);
/* Test helper: encodes frame_count interleaved f32 frames to one packet at 48 kHz. */
int32_t leonida_opus_encode_test(const float *input, uint32_t frame_count,
uint32_t channels, uint8_t *out,
size_t out_capacity, size_t *out_len);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,244 @@
#![deny(unsafe_op_in_unsafe_fn)]
//! C ABI around the pure-Rust `opus-pure` decoder, for the console audio decoder (`xapu.dll`).
//!
//! The command protocol lives in `runtime/shims/xapu_chad.cpp`; this crate only turns one Opus
//! packet into interleaved f32 PCM, resets the decoder, and (for tests) encodes a synthetic tone.
//! `opus-pure` is BSD-3-Clause; this wrapper is GPL-3.0-or-later, like the rest of the runtime.
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::ptr;
use std::sync::Mutex;
use opus_pure::{Application, OpusDecoder, OpusEncoder};
pub const LEONIDA_OPUS_OK: i32 = 0;
pub const LEONIDA_OPUS_INVALID_ARGUMENT: i32 = 1;
pub const LEONIDA_OPUS_INVALID_FORMAT: i32 = 2;
pub const LEONIDA_OPUS_DECODER_FAILURE: i32 = 3;
pub const LEONIDA_OPUS_OUT_OF_MEMORY: i32 = 4;
pub const LEONIDA_OPUS_PANIC: i32 = 5;
pub const LEONIDA_OPUS_BUFFER_TOO_SMALL: i32 = 6;
/// 120 ms at 48 kHz, the longest Opus packet, in samples per channel.
pub const LEONIDA_OPUS_MAX_FRAMES: usize = 5760;
#[repr(C)]
pub struct LeonidaOpusDecoder {
decoder: Mutex<OpusDecoder>,
channels: usize,
}
#[no_mangle]
pub unsafe extern "C" fn leonida_opus_decoder_channels(decoder: *const LeonidaOpusDecoder) -> u32 {
if decoder.is_null() {
return 0;
}
unsafe { (*decoder).channels as u32 }
}
/// Creates a decoder for one mono or stereo Opus stream at `sample_rate` (the title uses 48000).
///
/// # Safety
/// `out` must be writable for one pointer. The returned decoder must be destroyed once, after
/// every call that uses it has finished.
#[no_mangle]
pub unsafe extern "C" fn leonida_opus_decoder_create(
sample_rate: u32,
channels: u32,
out: *mut *mut LeonidaOpusDecoder,
) -> i32 {
if out.is_null() {
return LEONIDA_OPUS_INVALID_ARGUMENT;
}
unsafe { *out = ptr::null_mut() };
if sample_rate == 0 || sample_rate > i32::MAX as u32 || !(1..=2).contains(&channels) {
return LEONIDA_OPUS_INVALID_FORMAT;
}
match catch_unwind(AssertUnwindSafe(|| {
OpusDecoder::new(sample_rate as i32, channels as usize).map(|decoder| {
Box::new(LeonidaOpusDecoder {
decoder: Mutex::new(decoder),
channels: channels as usize,
})
})
})) {
Ok(Ok(decoder)) => {
unsafe { *out = Box::into_raw(decoder) };
LEONIDA_OPUS_OK
}
Ok(Err(_)) => LEONIDA_OPUS_INVALID_FORMAT,
Err(_) => LEONIDA_OPUS_PANIC,
}
}
/// Decodes one Opus packet into `out` as interleaved f32 frames.
///
/// # Safety
/// `decoder` must come from `leonida_opus_decoder_create`. `input` must reference `input_len`
/// readable bytes; `out` must hold `out_capacity_frames * channels` floats; `out_frames` must be
/// writable. Do not destroy the decoder concurrently with this call.
#[no_mangle]
pub unsafe extern "C" fn leonida_opus_decode_packet(
decoder: *mut LeonidaOpusDecoder,
input: *const u8,
input_len: usize,
out: *mut f32,
out_capacity_frames: usize,
out_frames: *mut u32,
) -> i32 {
if decoder.is_null()
|| input.is_null()
|| input_len == 0
|| out.is_null()
|| out_frames.is_null()
{
return LEONIDA_OPUS_INVALID_ARGUMENT;
}
let decoder = unsafe { &*decoder };
let channels = decoder.channels;
let Ok(mut guard) = decoder.decoder.lock() else {
return LEONIDA_OPUS_DECODER_FAILURE;
};
let packet = unsafe { std::slice::from_raw_parts(input, input_len) };
let mut pcm = vec![0f32; LEONIDA_OPUS_MAX_FRAMES * channels];
match guard.decode(packet, LEONIDA_OPUS_MAX_FRAMES, &mut pcm) {
Ok(frames) => {
if frames > out_capacity_frames {
return LEONIDA_OPUS_BUFFER_TOO_SMALL;
}
let samples = frames * channels;
unsafe {
ptr::copy_nonoverlapping(pcm.as_ptr(), out, samples);
*out_frames = frames as u32;
}
LEONIDA_OPUS_OK
}
Err(_) => LEONIDA_OPUS_DECODER_FAILURE,
}
}
/// # Safety
/// `decoder` must come from `leonida_opus_decoder_create` and not be used concurrently.
#[no_mangle]
pub unsafe extern "C" fn leonida_opus_decoder_reset(decoder: *mut LeonidaOpusDecoder) -> i32 {
if decoder.is_null() {
return LEONIDA_OPUS_INVALID_ARGUMENT;
}
let decoder = unsafe { &*decoder };
let Ok(mut guard) = decoder.decoder.lock() else {
return LEONIDA_OPUS_DECODER_FAILURE;
};
let _ = guard.reset_state();
LEONIDA_OPUS_OK
}
/// # Safety
/// `decoder` must be a live handle and must not be used after this call.
#[no_mangle]
pub unsafe extern "C" fn leonida_opus_decoder_destroy(decoder: *mut LeonidaOpusDecoder) {
if !decoder.is_null() {
unsafe { drop(Box::from_raw(decoder)) };
}
}
/// Test helper: encodes `frame_count` interleaved f32 frames to one Opus packet at 48 kHz.
///
/// # Safety
/// `input` must hold `frame_count * channels` floats; `out` must hold `out_capacity` bytes;
/// `out_len` must be writable.
#[no_mangle]
pub unsafe extern "C" fn leonida_opus_encode_test(
input: *const f32,
frame_count: u32,
channels: u32,
out: *mut u8,
out_capacity: usize,
out_len: *mut usize,
) -> i32 {
if input.is_null()
|| out.is_null()
|| out_len.is_null()
|| frame_count == 0
|| !(1..=2).contains(&channels)
{
return LEONIDA_OPUS_INVALID_ARGUMENT;
}
let samples = frame_count as usize * channels as usize;
let input = unsafe { std::slice::from_raw_parts(input, samples) };
let mut encoder = match OpusEncoder::new(48_000, channels as usize, Application::Audio) {
Ok(encoder) => encoder,
Err(_) => return LEONIDA_OPUS_INVALID_FORMAT,
};
let mut packet = vec![0u8; out_capacity.max(4000)];
match encoder.encode(input, frame_count as usize, &mut packet) {
Ok(bytes) if bytes <= out_capacity => {
unsafe {
ptr::copy_nonoverlapping(packet.as_ptr(), out, bytes);
*out_len = bytes;
}
LEONIDA_OPUS_OK
}
Ok(_) => LEONIDA_OPUS_BUFFER_TOO_SMALL,
Err(_) => LEONIDA_OPUS_DECODER_FAILURE,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encodes_and_decodes_a_tone() {
const FRAMES: u32 = 960;
const CHANNELS: u32 = 2;
let mut tone = Vec::with_capacity((FRAMES * CHANNELS) as usize);
for i in 0..FRAMES {
let sample = ((i as f32) * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5;
tone.push(sample);
tone.push(sample);
}
let mut packet = [0u8; 1500];
let mut packet_len = 0usize;
// SAFETY: the buffers are owned by this test.
let encoded = unsafe {
leonida_opus_encode_test(
tone.as_ptr(),
FRAMES,
CHANNELS,
packet.as_mut_ptr(),
packet.len(),
&mut packet_len,
)
};
assert_eq!(encoded, LEONIDA_OPUS_OK);
assert!(packet_len > 0);
let mut decoder = ptr::null_mut();
// SAFETY: `decoder` is writable for one pointer.
assert_eq!(
unsafe { leonida_opus_decoder_create(48_000, CHANNELS, &mut decoder) },
LEONIDA_OPUS_OK
);
let mut pcm = vec![0f32; LEONIDA_OPUS_MAX_FRAMES * CHANNELS as usize];
let mut frames = 0u32;
// SAFETY: the packet and PCM buffers are owned by this test.
let decoded = unsafe {
leonida_opus_decode_packet(
decoder,
packet.as_ptr(),
packet_len,
pcm.as_mut_ptr(),
LEONIDA_OPUS_MAX_FRAMES,
&mut frames,
)
};
assert_eq!(decoded, LEONIDA_OPUS_OK);
assert_eq!(frames, FRAMES);
let energy: f32 =
pcm[..(frames * CHANNELS) as usize].iter().map(|s| s * s).sum::<f32>() / (frames * CHANNELS) as f32;
assert!(energy > 0.01, "decoded a tone, energy {energy}");
// SAFETY: created above, destroyed once.
unsafe { leonida_opus_decoder_destroy(decoder) };
}
}

View File

@ -1,24 +1,8 @@
// xapu.dll and chad.dll: the console's audio processing unit (APU) and audio DSP command queues. No PC has either,
// so these give the title connections whose calls succeed, a zeroed shared buffer, a result for each stream open and
// close, and zeroed DSP status: the audio the APU would render stays silent, and nothing the title submits is processed.
// chad.dll: the console's audio DSP command queue. No PC has one, so this gives the title a connection whose calls
// succeed and zeroed DSP status: nothing the title submits is processed. xapu.dll, the APU command queue, is in
// xapu_queue.cpp.
//
// Read from the executable's call sites (counts in docs/runtime_imports.md), statically, never run:
// XApuConnect(block24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte
// output is read later as the base of a CPU-visible buffer: per-stream
// input at base + slot * 0x280 and output at base + 0x14000 +
// slot * 0x1E00. The first argument is a 24-byte global of the title
// that other title code also addresses; whether it is an input or an
// output is not known, so it is left untouched.
// XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type
// (1, 2 and 3 seen), the second a stream slot.
// XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues.
// XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative
// HRESULT skips that result. The loop reads a type at +0, a stream slot
// at +4 and a dword at +0x34. Its per-slot state machine takes a type 1
// result as "opened" and returns the slot to the title's free list only
// on a type 2 result, after the title enqueued a type 2 command.
// XApuDisconnect(handle, 0x20) 1 site; the return value is never read. The constant second
// argument is not declared here: nothing reads it.
// XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*) 1 site; success is a return of 0. The
// buffer comes from the title's XMemAlloc and stays the title's.
// XDspActivate(handle, desc*, out*, out*) 1 site; success is a return of 0, else the caller returns -1. The two
@ -30,12 +14,6 @@
// at +4 equals *id.
// XDspDeactivate, XDspDisconnect 1 site each, tail calls: the caller returns what they return.
//
// HYPOTHESIS: the shared buffer is 0x14000 + 128 * 0x1E00 bytes. 128 slots is what fits 0x14000 at the 0x280 input
// stride, and the DSP connect passes 0x80 as its stream limit; no call site shows a bound. The 16-byte output is
// written as {base, size}; only the base is measured.
// HYPOTHESIS: a type 1 (open) or type 2 (close) command produces one result of the same type for the same slot; the
// title's state machine fits that, the console is not measured. Without the close result the title's 256 stream ids
// run out. Only the two dwords are written; other command types are accepted with S_OK and produce no result.
// HYPOTHESIS: XDspActivate's outputs point at zeroed memory owned by the connection. XDspSubmitCommand leaves *id at
// the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait.
#include <windows.h>
@ -43,7 +21,6 @@
#include <cstdint>
#include <cstring>
#include <deque>
#include <mutex>
#include <new>
#include <set>
@ -54,30 +31,13 @@
namespace {
constexpr size_t kApuBufferSize = 0x14000 + 128 * 0x1E00;
// shortcut: results past this cap are dropped (each leaks one stream id); raise it if a title that never dequeues
// must still work.
constexpr size_t kMaxResults = 4096;
struct ApuResult {
uint32_t type;
uint32_t slot;
};
struct ApuConnection {
void* buffer;
std::mutex mutex;
std::deque<ApuResult> results;
};
struct DspConnection {
uint8_t status[256];
uint8_t stream[256];
};
// gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command type, with
// the caller, so the first boot shows what the title sends without a line per call.
// gta6rt --trace FILE: the first call of each function, with the caller, so the first boot shows what the title sends
// without a line per call.
void note(const char* api, uint64_t value, const void* caller) {
if (!rt::startup_trace::enabled()) return;
static std::mutex mutex;
@ -92,71 +52,6 @@ void note(const char* api, uint64_t value, const void* caller) {
rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller))));
}
HRESULT __stdcall XApuConnect(void* block24, void* out16, void** handle) {
note("XApuConnect", 0, _ReturnAddress());
if (!handle) return E_INVALIDARG;
*handle = nullptr;
void* buffer = VirtualAlloc(nullptr, kApuBufferSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed
if (!buffer) return E_OUTOFMEMORY;
auto* c = new (std::nothrow) ApuConnection; // a throwing new would unwind into the title
if (!c) {
VirtualFree(buffer, 0, MEM_RELEASE);
return E_OUTOFMEMORY;
}
c->buffer = buffer;
*handle = c;
(void)block24;
if (out16) {
const uint64_t info[2] = {reinterpret_cast<uint64_t>(buffer), kApuBufferSize};
std::memcpy(out16, info, sizeof info);
}
return S_OK;
}
HRESULT __stdcall XApuDisconnect(void* handle) {
note("XApuDisconnect", 0, _ReturnAddress());
auto* c = static_cast<ApuConnection*>(handle);
if (!c) return E_INVALIDARG;
VirtualFree(c->buffer, 0, MEM_RELEASE);
delete c;
return S_OK;
}
HRESULT __stdcall XApuEnqueueCommand(void* handle, const uint32_t* command, uint64_t flags) {
note("XApuEnqueueCommand", command ? command[0] : ~0ull, _ReturnAddress());
(void)flags;
auto* c = static_cast<ApuConnection*>(handle);
if (!c || !command) return E_INVALIDARG;
if (command[0] == 1 || command[0] == 2) {
try {
const std::lock_guard lock(c->mutex);
if (c->results.size() < kMaxResults) c->results.push_back({command[0], command[1]});
} catch (...) { // out of memory: the result is lost, nothing may unwind into the title
}
}
return S_OK;
}
uint32_t __stdcall XApuGetResultCount(void* handle, uint64_t flags) {
note("XApuGetResultCount", 0, _ReturnAddress());
(void)flags;
auto* c = static_cast<ApuConnection*>(handle);
if (!c) return 0;
const std::lock_guard lock(c->mutex);
return static_cast<uint32_t>(c->results.size());
}
HRESULT __stdcall XApuDequeueResult(void* handle, void* result) {
note("XApuDequeueResult", 0, _ReturnAddress());
auto* c = static_cast<ApuConnection*>(handle);
if (!c || !result) return E_INVALIDARG;
const std::lock_guard lock(c->mutex);
if (c->results.empty()) return E_FAIL;
std::memcpy(result, &c->results.front(), sizeof(ApuResult)); // the rest stays as the caller zeroed it
c->results.pop_front();
return S_OK;
}
HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams,
uint32_t flags, void** handle) {
note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress());
@ -199,14 +94,6 @@ HRESULT __stdcall XDspSubmitCommand(void*, void*, uint32_t*) {
} // namespace
SHIM_TABLE(xapu,
{"xapu.dll", "XApuConnect", reinterpret_cast<void*>(&XApuConnect)},
{"xapu.dll", "XApuDequeueResult", reinterpret_cast<void*>(&XApuDequeueResult)},
{"xapu.dll", "XApuDisconnect", reinterpret_cast<void*>(&XApuDisconnect)},
{"xapu.dll", "XApuEnqueueCommand", reinterpret_cast<void*>(&XApuEnqueueCommand)},
{"xapu.dll", "XApuGetResultCount", reinterpret_cast<void*>(&XApuGetResultCount)},
);
SHIM_TABLE(chad,
{"chad.dll", "XDspActivate", reinterpret_cast<void*>(&XDspActivate)},
{"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast<void*>(&XDspConnectWithMaximumStreamLimit)},

View File

@ -0,0 +1,438 @@
// xapu.dll: the console's audio processing unit (APU) command queue. No PC has one, so this keeps the queue the title
// talks to - one result per accepted command, in command order, with the console's error codes. With
// runtime/opus_decoder built (LEONIDA_HAVE_OPUS_DECODER) a process command decodes its Opus packet to PCM; without
// it the result carries the frame count its table-of-contents byte gives and silence in its output.
//
// Read from the executable's call sites (counts in docs/runtime_imports.md, shapes in docs/audio_hal_exe_calls.md),
// statically, never run:
// XApuConnect(input24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte
// output is read later as the base of a CPU-visible buffer: per-stream
// input at base + slot * 0x280 and output at base + 0x14000 +
// slot * 0x1E00. The first argument is a 24-byte global of the title
// that other title code also addresses.
// XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type
// (1, 2 and 3 seen), the second a stream slot.
// XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues.
// XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative
// HRESULT skips that result. The loop reads a type at +0, a stream slot
// at +4 and a dword at +0x34. Its per-slot state machine takes a type 1
// result as "opened" and returns the slot to the title's free list only
// on a type 2 result, after the title enqueued a type 2 command.
// XApuDisconnect(handle, 0x20) 1 site; the return value is never read.
//
// Where the layouts come from. The signatures, structure layouts, command kinds, option bits and error codes below
// are facts recorded by Marvisak/VIctory (GPL-3.0-or-later, crates/victory-hle/src/modules/apu.rs at commit ffe310e),
// whose runtime runs the retail executable through these calls; see docs/related_projects.md. Nothing of its code is
// copied; this file is written from those facts. They agree with every shape above: the first argument of
// XApuConnect is an input, the dword the title reads at +0x34 of a result is its output byte count, and a type 1
// (activate) or type 2 (deactivate) command gives a result of the same kind for the same stream.
// HRESULT XApuConnect(const ConnectInput*, ConnectOutput*, Connection** out)
// HRESULT XApuDisconnect(Connection*, uint32_t) the second argument is not read
// HRESULT XApuEnqueueCommand(Connection*, const void* command, uint32_t* accepted_so_far) may be null
// HRESULT XApuDequeueResult(Connection*, Result* out) 0x8AC81001 while no result is ready
// uint32_t XApuGetResultCount(Connection*, uint32_t* dequeued_so_far) may be null; returns the results ready
// A connection is for one kind of processing; kind 1 is Opus decoding to 32-bit float PCM at 48 kHz, and any other
// kind is E_NOTIMPL. Every command starts with the 24-byte CommandId. A command refused at once (unknown kind,
// stream out of range, or the stream already holding `commands_per_stream` results not dequeued) gives no result;
// every other command gives one, with its error, if any, in the result.
//
// Without runtime/opus_decoder a process command's frame count comes from the Opus packet's table-of-contents byte
// (RFC 6716, section 3.1), clipped from first_frame, to frame_count and to what output_bytes holds, and that output
// range is written with zeros, so the title sees streams advance at the right rate and the audio stays silent. With
// the crate, fill() decodes the packet and writes its PCM instead.
#include <windows.h>
#include <intrin.h>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <deque>
#include <mutex>
#include <new>
#include <set>
#include <string>
#include <vector>
#if defined(LEONIDA_HAVE_OPUS_DECODER)
#include "leonida_opus_decoder.h"
#endif
#include "shims.h"
#include "startup_trace.h"
namespace {
constexpr HRESULT kNotImpl = static_cast<HRESULT>(rt::shims::kENotImpl);
constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u);
constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u);
constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u);
constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u);
constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u);
constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u);
constexpr uint32_t kDecodeOpus = 1; // ConnectInput::processing
constexpr uint32_t kActivate = 1; // CommandId::kind
constexpr uint32_t kDeactivate = 2;
constexpr uint32_t kProcess = 3;
constexpr uint32_t kReset = 5; // 4 is notify; neither carries anything to do while nothing is decoded
constexpr uint32_t kSignalWhenDone = 0x1; // CommandId::options: set the result event when the result is ready
constexpr uint32_t kResultEvent = 0x8; // ConnectInput::options: create an auto-reset event and hand it out
constexpr uint32_t kDeinterleavedOutput = 0x4; // ConnectInput::options: split stereo into two planes
constexpr uint32_t kOpusSampleRate = 48000;
constexpr uint32_t kMaxStreams = 500;
constexpr uint32_t kMaxCommandsPerStream = 16;
constexpr uint32_t kMaxFrames = 5760; // 120 ms at 48 kHz, the longest Opus packet (RFC 6716, section 3.2.5)
#pragma pack(push, 1)
struct ConnectInput {
uint32_t processing;
uint32_t streams;
uint32_t commands_per_stream;
uint32_t memory_bytes;
uint32_t frames_per_output; // 0 for decoding
uint32_t options;
};
struct ConnectOutput {
void* memory; // zeroed, for the title's packets and output
HANDLE result_event;
};
struct CommandId {
uint32_t kind;
uint32_t stream;
uint32_t sequence;
uint32_t options;
uint64_t context;
};
struct ActivateCommand {
CommandId id;
uint32_t channels; // 1 or 2
uint32_t init_bytes;
const void* init;
float start_pitch;
uint32_t processing_bytes;
void* processing;
};
struct ProcessCommand {
CommandId id;
float pitch_ramp;
float target_pitch;
uint32_t first_frame;
uint32_t frame_count;
uint32_t input_bytes;
const uint8_t* input;
uint32_t output_bytes;
uint8_t* output;
};
struct Result {
CommandId id;
uint32_t state;
uint64_t state_data;
uint64_t usec;
HRESULT error;
uint32_t frames;
uint32_t output_bytes;
uint8_t* output;
float pitch;
uint32_t input_bytes;
const uint8_t* input;
};
#pragma pack(pop)
static_assert(sizeof(ConnectInput) == 24, "six dwords");
static_assert(sizeof(ConnectOutput) == 16, "memory and event");
static_assert(sizeof(CommandId) == 24, "kind, stream, sequence, options, context");
static_assert(sizeof(ActivateCommand) == 56, "CommandId and the activate fields");
static_assert(sizeof(ProcessCommand) == 64, "CommandId and the process fields");
static_assert(sizeof(Result) == 0x50, "the result the title dequeues");
static_assert(offsetof(Result, state) == 0x18 && offsetof(Result, error) == 0x2C &&
offsetof(Result, output_bytes) == 0x34 && offsetof(Result, pitch) == 0x40 &&
offsetof(Result, input) == 0x48,
"the offsets the title and the layout agree on");
struct Stream {
bool active = false;
uint32_t channels = 0;
uint32_t pending = 0; // results queued and not dequeued
#if defined(LEONIDA_HAVE_OPUS_DECODER)
LeonidaOpusDecoder* decoder = nullptr;
#endif
};
struct Connection {
void* memory = nullptr;
HANDLE event = nullptr;
uint32_t commands_per_stream = 0;
bool deinterleaved = false;
std::mutex mutex;
std::vector<Stream> streams;
std::deque<Result> results;
uint32_t accepted = 0;
uint32_t dequeued = 0;
};
// gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command kind, with
// the caller, so the first boot shows what the title sends without a line per call.
void note(const char* api, uint64_t value, const void* caller) {
if (!rt::startup_trace::enabled()) return;
static std::mutex mutex;
static std::set<std::pair<std::string, uint64_t>> seen;
{
const std::lock_guard lock(mutex);
if (!seen.insert({api, value}).second) return;
}
rt::startup_trace::event(
"audio_queue", std::string("\"api\":") + rt::startup_trace::quote(api) +
",\"value\":" + rt::startup_trace::quote(rt::startup_trace::hex(value)) + ",\"caller\":" +
rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller))));
}
// Samples per channel at 48 kHz in one Opus packet, from its table-of-contents byte and frame count code (RFC 6716,
// section 3.1); 0 for a packet that is not valid. The no-decoder path counts frames this way.
uint32_t opus_packet_frames(const uint8_t* packet, uint32_t bytes) {
if (!packet || bytes == 0) return 0;
static constexpr uint32_t kSilk[4] = {480, 960, 1920, 2880}; // 10, 20, 40, 60 ms
static constexpr uint32_t kHybrid[2] = {480, 960}; // 10, 20 ms
static constexpr uint32_t kCelt[4] = {120, 240, 480, 960}; // 2.5, 5, 10, 20 ms
const uint32_t config = packet[0] >> 3;
const uint32_t per_frame = config < 12 ? kSilk[config & 3] : config < 16 ? kHybrid[config & 1] : kCelt[config & 3];
uint32_t count = 0;
switch (packet[0] & 3) {
case 0: count = 1; break;
case 1:
case 2: count = 2; break;
default:
if (bytes < 2) return 0;
count = packet[1] & 0x3F;
break;
}
if (count == 0 || count * per_frame > kMaxFrames) return 0;
return count * per_frame;
}
// Fills a process command's result: the packet's PCM when runtime/opus_decoder is built, silence (with the frame
// count from the table-of-contents byte) otherwise.
void fill(Connection& connection, Stream& stream, const ProcessCommand& c, Result& r) {
r.input = c.input;
r.input_bytes = c.input_bytes;
r.output = c.output;
if (!c.input || !c.output || c.input_bytes == 0) {
r.error = E_INVALIDARG;
return;
}
#if defined(LEONIDA_HAVE_OPUS_DECODER)
if (stream.decoder) {
const uint32_t channels = leonida_opus_decoder_channels(stream.decoder);
if (channels == 0) {
r.error = kInvalidStream;
return;
}
std::vector<float> pcm;
try {
pcm.resize(size_t(kMaxFrames) * channels);
} catch (...) {
r.error = E_OUTOFMEMORY;
return;
}
uint32_t decoded = 0;
if (leonida_opus_decode_packet(stream.decoder, c.input, c.input_bytes, pcm.data(), kMaxFrames, &decoded) !=
LEONIDA_OPUS_OK) {
r.error = kBadPacket;
return;
}
const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded;
uint32_t frames = decoded - first;
if (frames > c.frame_count) frames = c.frame_count;
const uint32_t room = c.output_bytes / (4 * channels);
if (frames > room) frames = room;
const uint32_t bytes = frames * channels * 4;
if (connection.deinterleaved && channels == 2) {
float* out = reinterpret_cast<float*>(c.output);
for (uint32_t i = 0; i < frames; ++i) {
out[i] = pcm[(first + i) * 2];
out[frames + i] = pcm[(first + i) * 2 + 1];
}
} else if (bytes != 0) {
std::memcpy(c.output, pcm.data() + first * channels, bytes);
}
r.frames = frames;
r.output_bytes = bytes;
return;
}
#endif
const uint32_t decoded = opus_packet_frames(c.input, c.input_bytes);
if (decoded == 0) {
r.error = kBadPacket;
return;
}
const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded;
uint32_t frames = decoded - first;
if (frames > c.frame_count) frames = c.frame_count;
const uint32_t room = c.output_bytes / (4 * stream.channels);
if (frames > room) frames = room;
const uint32_t bytes = frames * stream.channels * 4;
std::memset(c.output, 0, bytes); // interleaved or not, silence is zeros
r.frames = frames;
r.output_bytes = bytes;
}
HRESULT __stdcall XApuConnect(const ConnectInput* input, ConnectOutput* output, Connection** out) {
note("XApuConnect", input ? input->processing : ~0ull, _ReturnAddress());
if (!input || !output || !out) return E_INVALIDARG;
*out = nullptr;
ConnectInput in;
std::memcpy(&in, input, sizeof(in));
if (in.streams == 0 || in.streams > kMaxStreams || in.commands_per_stream == 0 ||
in.commands_per_stream > kMaxCommandsPerStream || in.memory_bytes == 0)
return E_INVALIDARG;
if (in.processing != kDecodeOpus) {
std::fprintf(stderr, "[rt] xapu: XApuConnect for processing kind %u: only Opus decoding (1); E_NOTIMPL\n",
in.processing);
return kNotImpl;
}
if (in.frames_per_output != 0) return E_INVALIDARG;
auto* c = new (std::nothrow) Connection; // a throwing new would unwind into the title
if (!c) return E_OUTOFMEMORY;
try {
c->streams.resize(in.streams);
} catch (...) {
delete c;
return E_OUTOFMEMORY;
}
c->memory = VirtualAlloc(nullptr, in.memory_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed
if (!c->memory) {
delete c;
return E_OUTOFMEMORY;
}
if (in.options & kResultEvent) {
c->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // auto-reset
if (!c->event) {
const HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
VirtualFree(c->memory, 0, MEM_RELEASE);
delete c;
return hr;
}
}
c->commands_per_stream = in.commands_per_stream;
c->deinterleaved = (in.options & kDeinterleavedOutput) != 0;
const ConnectOutput o{c->memory, c->event};
std::memcpy(output, &o, sizeof(o));
*out = c;
#if defined(LEONIDA_HAVE_OPUS_DECODER)
std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets decoded\n", in.streams);
#else
std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets counted, not decoded\n",
in.streams);
#endif
return S_OK;
}
HRESULT __stdcall XApuDisconnect(Connection* c, uint32_t /*0x20 at the measured site*/) {
note("XApuDisconnect", 0, _ReturnAddress());
if (!c) return E_INVALIDARG;
#if defined(LEONIDA_HAVE_OPUS_DECODER)
for (Stream& s : c->streams)
if (s.decoder) leonida_opus_decoder_destroy(s.decoder);
#endif
if (c->event) CloseHandle(c->event);
VirtualFree(c->memory, 0, MEM_RELEASE);
delete c;
return S_OK;
}
HRESULT __stdcall XApuEnqueueCommand(Connection* c, const void* command, uint32_t* accepted_so_far) {
if (!c || !command) return E_INVALIDARG;
CommandId id;
std::memcpy(&id, command, sizeof(id));
note("XApuEnqueueCommand", id.kind, _ReturnAddress());
if (id.kind < kActivate || id.kind > kReset) return kInvalidCommand;
const std::lock_guard lock(c->mutex);
if (id.stream >= c->streams.size()) return kInvalidStream;
Stream& stream = c->streams[id.stream];
if (stream.pending >= c->commands_per_stream) return kQueueFull;
Result r{};
r.id = id;
r.pitch = 1.0f;
if (id.kind == kActivate) {
ActivateCommand a;
std::memcpy(&a, command, sizeof(a));
if (stream.active) {
r.error = kAlreadyActive;
} else if (a.channels < 1 || a.channels > 2) {
r.error = E_INVALIDARG;
} else {
stream.active = true;
stream.channels = a.channels;
#if defined(LEONIDA_HAVE_OPUS_DECODER)
if (leonida_opus_decoder_create(kOpusSampleRate, a.channels, &stream.decoder) != LEONIDA_OPUS_OK) {
stream.active = false;
stream.channels = 0;
r.error = E_INVALIDARG;
}
#endif
}
} else if (id.kind == kDeactivate) {
stream.active = false;
#if defined(LEONIDA_HAVE_OPUS_DECODER)
if (stream.decoder) {
leonida_opus_decoder_destroy(stream.decoder);
stream.decoder = nullptr;
}
#endif
} else if (id.kind == kReset) {
#if defined(LEONIDA_HAVE_OPUS_DECODER)
if (stream.decoder) leonida_opus_decoder_reset(stream.decoder);
#endif
} else if (id.kind == kProcess) {
ProcessCommand p;
std::memcpy(&p, command, sizeof(p));
if (!stream.active) r.error = kInvalidStream;
else fill(*c, stream, p, r);
}
try {
c->results.push_back(r);
} catch (...) { // out of memory: refuse the command, nothing may unwind into the title
return E_OUTOFMEMORY;
}
++stream.pending;
++c->accepted;
if (accepted_so_far) *accepted_so_far = c->accepted;
if ((id.options & kSignalWhenDone) && c->event) SetEvent(c->event);
return S_OK;
}
HRESULT __stdcall XApuDequeueResult(Connection* c, Result* out) {
note("XApuDequeueResult", 0, _ReturnAddress());
if (!c || !out) return E_INVALIDARG;
const std::lock_guard lock(c->mutex);
if (c->results.empty()) return kNoResult;
const Result r = c->results.front();
c->results.pop_front();
--c->streams[r.id.stream].pending;
++c->dequeued;
std::memcpy(out, &r, sizeof(r));
return S_OK;
}
uint32_t __stdcall XApuGetResultCount(Connection* c, uint32_t* dequeued_so_far) {
note("XApuGetResultCount", 0, _ReturnAddress());
if (!c) return 0;
const std::lock_guard lock(c->mutex);
if (dequeued_so_far) *dequeued_so_far = c->dequeued;
return static_cast<uint32_t>(c->results.size());
}
} // namespace
SHIM_TABLE(xapu,
{"xapu.dll", "XApuConnect", reinterpret_cast<void*>(&XApuConnect)},
{"xapu.dll", "XApuDequeueResult", reinterpret_cast<void*>(&XApuDequeueResult)},
{"xapu.dll", "XApuDisconnect", reinterpret_cast<void*>(&XApuDisconnect)},
{"xapu.dll", "XApuEnqueueCommand", reinterpret_cast<void*>(&XApuEnqueueCommand)},
{"xapu.dll", "XApuGetResultCount", reinterpret_cast<void*>(&XApuGetResultCount)},
);

View File

@ -1,7 +1,11 @@
// Checks the registered xapu.dll and chad.dll shims in the call shapes the executable uses (runtime/shims/xapu_chad.cpp):
// the connections succeed, the APU's shared buffer is zeroed and writable at the offsets the title reaches, commands
// are accepted, an open and a close each give one result and nothing else does, XDspActivate hands out zeroed status
// and stream memory, and both disconnect.
// Checks the registered xapu.dll and chad.dll shims (runtime/shims/xapu_queue.cpp and runtime/shims/xapu_chad.cpp)
// in the call shapes the executable uses and against the layouts xapu_queue.cpp documents.
//
// xapu.dll: the connection's limits and its zeroed memory, writable at the offsets the title reaches; one result per
// accepted command, in command order, with its id echoed; the per-stream queue limit; the error codes, returned or in
// the result; a process command's frame count taken from the Opus packet's table-of-contents byte (RFC 6716, section
// 3.1) and clipped, with silence written; and the result event. The packets are hand-made TOC bytes, not audio.
// chad.dll: XDspActivate hands out zeroed status and stream memory, and both disconnect.
#include <windows.h>
#include <cstdint>
@ -12,10 +16,10 @@
namespace {
using XApuConnectFn = HRESULT(__stdcall*)(void*, void*, void**);
using XApuDisconnectFn = HRESULT(__stdcall*)(void*);
using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const uint32_t*, uint64_t);
using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint64_t);
using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**);
using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t);
using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*);
using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*);
using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*);
using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**);
using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**);
@ -23,6 +27,55 @@ using XDspDeactivateFn = HRESULT(__stdcall*)(void*, uint64_t, uint64_t, uint64_t
using XDspDisconnectFn = HRESULT(__stdcall*)(void*);
using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*);
constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u);
constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u);
constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u);
constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u);
constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u);
constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u);
#pragma pack(push, 1)
struct ConnectInput {
uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options;
};
struct ConnectOutput {
void* memory;
HANDLE result_event;
};
struct CommandId {
uint32_t kind, stream, sequence, options;
uint64_t context;
};
struct ActivateCommand {
CommandId id;
uint32_t channels, init_bytes;
const void* init;
float start_pitch;
uint32_t processing_bytes;
void* processing;
};
struct ProcessCommand {
CommandId id;
float pitch_ramp, target_pitch;
uint32_t first_frame, frame_count, input_bytes;
const uint8_t* input;
uint32_t output_bytes;
uint8_t* output;
};
struct Result {
CommandId id;
uint32_t state;
uint64_t state_data, usec;
HRESULT error;
uint32_t frames, output_bytes;
uint8_t* output;
float pitch;
uint32_t input_bytes;
const uint8_t* input;
};
#pragma pack(pop)
static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts");
int g_checks = 0;
int g_failures = 0;
@ -39,6 +92,8 @@ T get(const char* dll, const char* name) {
return reinterpret_cast<T>(fn);
}
CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; }
} // namespace
int main() {
@ -56,39 +111,165 @@ int main() {
check(rt::shims::owns_dll("xapu.dll") && rt::shims::owns_dll("chad.dll"), "the shims own xapu.dll and chad.dll");
if (g_failures) return 1;
// XApuConnect(block24*, out16*, handle*), success read as SUCCEEDED.
uint8_t out24[24];
uint64_t out16[2] = {};
std::memset(out24, 0xcc, sizeof out24);
// XApuConnect(const ConnectInput*, ConnectOutput*, handle*): the first argument is read, never written.
ConnectOutput out{};
void* apu = nullptr;
check(SUCCEEDED(connect(out24, out16, &apu)) && apu, "XApuConnect succeeds with a handle");
check(out24[0] == 0xcc && out24[23] == 0xcc, "XApuConnect leaves the title's 24-byte block alone");
auto* base = reinterpret_cast<uint8_t*>(out16[0]);
check(base != nullptr && out16[1] >= 0x14000 + 128 * 0x1E00, "XApuConnect returns the shared buffer and its size");
if (base) {
const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output
check(base[0] == 0 && base[last_output] == 0, "the shared buffer is zeroed");
base[127 * 0x280] = 1;
base[last_output] = 1;
check(base[127 * 0x280] == 1 && base[last_output] == 1, "the shared buffer is writable at slot 127");
}
check(connect(out24, out16, nullptr) == E_INVALIDARG, "XApuConnect without a handle pointer fails");
ConnectInput bad{1, 0, 2, 0x10000, 0, 0};
check(connect(&bad, &out, &apu) == E_INVALIDARG, "zero streams is E_INVALIDARG");
bad = {1, 501, 2, 0x10000, 0, 0};
check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 500 streams is E_INVALIDARG");
bad = {1, 4, 17, 0x10000, 0, 0};
check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 16 commands per stream is E_INVALIDARG");
bad = {1, 4, 2, 0, 0, 0};
check(connect(&bad, &out, &apu) == E_INVALIDARG, "no memory is E_INVALIDARG");
bad = {1, 4, 2, 0x10000, 256, 0};
check(connect(&bad, &out, &apu) == E_INVALIDARG, "frames per output for decoding is E_INVALIDARG");
bad = {2, 4, 2, 0x10000, 0, 0};
check(connect(&bad, &out, &apu) == static_cast<HRESULT>(rt::shims::kENotImpl),
"a processing kind other than Opus decoding is E_NOTIMPL");
check(apu == nullptr, "a failed XApuConnect hands out no handle");
// Command types 1, 2 and 3 as the title builds them; the third argument is 0 at every site.
for (uint32_t type = 1; type <= 3; ++type) {
uint32_t command[16] = {type, 5};
check(enqueue(apu, command, 0) == S_OK, "XApuEnqueueCommand accepts a command");
// The memory the title addresses: input at base + slot * 0x280, output at base + 0x14000 + slot * 0x1E00.
constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00;
const ConnectInput in{1, 128, 2, kMemory, 0, 8};
const ConnectInput in_copy = in;
check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding, 128 streams, 2 commands each");
check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone");
check(out.memory != nullptr && out.result_event != nullptr, "it hands out memory and a result event");
if (!apu || !out.memory) return 1;
auto* base = static_cast<uint8_t*>(out.memory);
const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output
check(base[0] == 0 && base[last_output] == 0, "the memory is zeroed");
base[127 * 0x280] = 1;
base[last_output] = 1;
check(base[127 * 0x280] == 1 && base[last_output] == 1, "the memory is writable at slot 127");
base[127 * 0x280] = 0;
base[last_output] = 0;
Result r{};
check(dequeue(apu, &r) == kNoResult, "XApuDequeueResult with nothing queued is 0x8AC81001");
uint32_t dequeued = 99;
check(count(apu, &dequeued) == 0 && dequeued == 0, "XApuGetResultCount: nothing ready, none dequeued");
// Activate stream 3 (stereo) and process one packet; the title's sites pass a null third argument.
const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr};
check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 with a null count pointer");
check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "a command not asking for it leaves the event");
uint8_t* const packet = base + 3 * 0x280;
uint8_t* const pcm = base + 0x14000 + 3 * 0x1E00;
packet[0] = (31 << 3) | 0; // one 20 ms CELT frame (config 31, code 0): 960 frames per channel
std::memset(pcm, 0x55, 0x1E00 + 16); // the slot and the start of the next, to see nothing past it is written
ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, 40, packet, 960 * 8, pcm};
uint32_t total = 0;
check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted");
check(WaitForSingleObject(out.result_event, 0) == WAIT_OBJECT_0, "a command asking for it signals the event");
check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "the event resets itself");
check(enqueue(apu, &process, &total) == kQueueFull && total == 2,
"a third command on a stream of two is 0x8AC81000 and not counted");
check(count(apu, nullptr) == 2, "two results ready, with a null dequeued pointer");
check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.id.sequence == 7 &&
r.id.context == 0x1234 && r.error == S_OK && r.pitch == 1.0f,
"results come in command order: the activate first, its id echoed");
check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows");
uint32_t dword34 = 0;
std::memcpy(&dword34, reinterpret_cast<const uint8_t*>(&r) + 0x34, 4);
check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == packet && r.input_bytes == 40,
"960 stereo float frames, the byte count at +0x34, the buffers echoed");
bool silent = true;
for (int i = 0; i < 960 * 8; ++i) silent = silent && pcm[i] == 0;
check(silent && pcm[960 * 8] == 0x55, "the output range is silence, and nothing past it is written");
check(count(apu, &dequeued) == 0 && dequeued == 2, "nothing ready, two dequeued");
// The TOC byte's frame size and count (RFC 6716, section 3.1), one stereo packet each.
struct Toc {
uint8_t toc, count;
uint32_t frames;
const char* what;
} const tocs[] = {
{(0 << 3) | 0, 0, 480, "SILK 10 ms, code 0: 480 frames"},
{(3 << 3) | 1, 0, 5760, "SILK 60 ms, code 1 (two frames): 5760 frames"},
{(13 << 3) | 2, 0, 1920, "hybrid 20 ms, code 2 (two frames): 1920 frames"},
{(16 << 3) | 3, 5, 600, "CELT 2.5 ms, code 3 with five frames: 600 frames"},
};
for (const Toc& t : tocs) {
packet[0] = t.toc;
packet[1] = t.count;
process = {id(3, 3), 0.0f, 1.0f, 0, 6000, 40, packet, 0x1E00 * 4, pcm};
r = {};
check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK &&
r.frames == (t.frames < 0x1E00 * 4 / 8 ? t.frames : 0x1E00 * 4 / 8),
t.what);
}
check(count(apu, 0) == 2, "the open and the close each queued a result, the type 3 command none");
for (uint32_t type = 1; type <= 2; ++type) {
uint32_t queued[0x50 / 4] = {};
check(dequeue(apu, queued) == S_OK && queued[0] == type && queued[1] == 5 && queued[2] == 0 && queued[13] == 0,
"XApuDequeueResult returns the type and slot and leaves the rest zeroed");
// first_frame and frame_count clip like a decode: three 20 ms frames (code 3, count 3) = 2880, from frame 2000.
packet[0] = (31 << 3) | 3;
packet[1] = 3;
process = {id(3, 3), 0.0f, 1.0f, 2000, 4000, 40, packet, 0x1E00, pcm};
enqueue(apu, &process, nullptr);
dequeue(apu, &r);
check(r.error == S_OK && r.frames == 880 && r.output_bytes == 880 * 8, "frames from first_frame to the packet's end");
process.frame_count = 300;
enqueue(apu, &process, nullptr);
dequeue(apu, &r);
check(r.frames == 300, "no more than frame_count");
process.frame_count = 4000;
process.output_bytes = 100 * 8 + 7;
enqueue(apu, &process, nullptr);
dequeue(apu, &r);
check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds");
// Errors carried in the result: the command is accepted and its result says what went wrong.
packet[1] = 7; // seven 20 ms frames: 140 ms, longer than an Opus packet may be
enqueue(apu, &process, nullptr);
dequeue(apu, &r);
check(r.error == kBadPacket && r.frames == 0, "an impossible packet: 0x8AC81008 in the result");
packet[0] = (31 << 3) | 3;
packet[1] = 0;
enqueue(apu, &process, nullptr);
dequeue(apu, &r);
check(r.error == kBadPacket, "a code 3 packet of zero frames: 0x8AC81008");
ProcessCommand empty = process;
empty.input_bytes = 0;
check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
"an empty input: E_INVALIDARG in the result");
empty = process;
empty.output = nullptr;
check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
"a null output: E_INVALIDARG in the result");
ProcessCommand stray = process;
stray.id.stream = 4;
check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream,
"a process on a stream never activated: 0x8AC81003 in the result");
check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kAlreadyActive,
"activating an active stream: 0x8AC81005 in the result");
ActivateCommand surround = activate;
surround.id.stream = 5;
surround.channels = 6;
check(enqueue(apu, &surround, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
"six channels: E_INVALIDARG in the result");
// Errors returned at once, with no result.
stray.id.stream = 128;
check(enqueue(apu, &stray, nullptr) == kInvalidStream, "a stream past the connection's is 0x8AC81003");
const CommandId unknown = id(9, 3);
check(enqueue(apu, &unknown, nullptr) == kInvalidCommand, "an unknown kind is 0x8AC81002");
check(count(apu, nullptr) == 0, "neither left a result");
// Notify and reset give a result; deactivate gives one and closes the stream.
for (uint32_t kind : {4u, 5u, 2u}) {
const CommandId command = id(kind, 3);
check(enqueue(apu, &command, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.id.kind == kind &&
r.id.stream == 3 && r.error == S_OK,
"notify, reset and deactivate each give a result of their kind for their stream");
}
check(count(apu, 0) == 0, "XApuGetResultCount is 0 again");
uint8_t result[0x50] = {};
check(FAILED(dequeue(apu, result)), "XApuDequeueResult on the empty queue fails");
check(disconnect(apu) == S_OK, "XApuDisconnect succeeds");
process.id.stream = 3;
enqueue(apu, &process, nullptr);
dequeue(apu, &r);
check(r.error == kInvalidStream, "after deactivate the stream takes no process command");
check(enqueue(apu, &activate, &total) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK,
"and it can be activated again");
check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)");
// XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*), success read as a return of 0.
alignas(64) static uint8_t dsp_buffer[4096];
@ -99,10 +280,10 @@ int main() {
void* stream = nullptr;
check(dsp_activate(dsp, description, reinterpret_cast<void**>(&status), &stream) == 0, "XDspActivate returns 0");
check(status && stream && static_cast<void*>(status) != stream, "XDspActivate writes both outputs");
uint32_t id = 0;
check(dsp_submit(stream, dsp_buffer, &id) == 0, "XDspSubmitCommand returns 0");
uint32_t dsp_id = 0;
check(dsp_submit(stream, dsp_buffer, &dsp_id) == 0, "XDspSubmitCommand returns 0");
// What the title's wait reads: no error at +0xc and the submitted id at +4.
check(status && status[3] == 0 && status[1] == id, "the status block reports the submitted command as done");
check(status && status[3] == 0 && status[1] == dsp_id, "the status block reports the submitted command as done");
check(dsp_deactivate(dsp, 0, 0, 0) == 0, "XDspDeactivate returns 0");
check(dsp_disconnect(dsp) == 0, "XDspDisconnect returns 0");

View File

@ -0,0 +1,193 @@
// Checks the decoded path of the registered xapu.dll shim (runtime/shims/xapu_queue.cpp) with
// runtime/opus_decoder built: the title's ConnectInput, activate/process/deactivate, one result per
// command in order, the 0x50-byte result layout, and a generated 440 Hz stereo packet decoded to
// 960 frames of f32 PCM, then clipped by first_frame / frame_count / output_bytes. The packet is
// encoded here; no game data.
#include <windows.h>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <vector>
#include "leonida_opus_decoder.h"
#include "shims.h"
namespace {
using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**);
using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t);
using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*);
using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*);
using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*);
constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u);
constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u);
#pragma pack(push, 1)
struct ConnectInput {
uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options;
};
struct ConnectOutput {
void* memory;
HANDLE result_event;
};
struct CommandId {
uint32_t kind, stream, sequence, options;
uint64_t context;
};
struct ActivateCommand {
CommandId id;
uint32_t channels, init_bytes;
const void* init;
float start_pitch;
uint32_t processing_bytes;
void* processing;
};
struct ProcessCommand {
CommandId id;
float pitch_ramp, target_pitch;
uint32_t first_frame, frame_count, input_bytes;
const uint8_t* input;
uint32_t output_bytes;
uint8_t* output;
};
struct Result {
CommandId id;
uint32_t state;
uint64_t state_data, usec;
HRESULT error;
uint32_t frames, output_bytes;
uint8_t* output;
float pitch;
uint32_t input_bytes;
const uint8_t* input;
};
#pragma pack(pop)
static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts");
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;
}
template <typename T>
T get(const char* dll, const char* name) {
void* fn = rt::shims::find(dll, name);
check(fn != nullptr, name);
return reinterpret_cast<T>(fn);
}
CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; }
} // namespace
int main() {
std::printf("xapu_opus_test: decoded xapu.dll path\n");
const auto connect = get<XApuConnectFn>("xapu.dll", "XApuConnect");
const auto disconnect = get<XApuDisconnectFn>("xapu.dll", "XApuDisconnect");
const auto enqueue = get<XApuEnqueueCommandFn>("xapu.dll", "XApuEnqueueCommand");
const auto count = get<XApuGetResultCountFn>("xapu.dll", "XApuGetResultCount");
const auto dequeue = get<XApuDequeueResultFn>("xapu.dll", "XApuDequeueResult");
if (g_failures) return 1;
constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00;
const ConnectInput in{1, 128, 2, kMemory, 0, 0};
const ConnectInput in_copy = in;
ConnectOutput out{};
void* apu = nullptr;
check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding");
check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone");
auto* base = static_cast<uint8_t*>(out.memory);
if (!apu || !base) return 1;
check(base[0] == 0 && base[kMemory - 1] == 0, "the shared memory is zeroed");
const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr};
check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 (stereo)");
std::vector<float> tone(960 * 2);
for (uint32_t i = 0; i < 960; ++i) {
const float sample = static_cast<float>(std::sin(double(i) * 440.0 * 6.283185307179586 / 48000.0)) * 0.5f;
tone[2 * i] = sample;
tone[2 * i + 1] = sample;
}
uint8_t encoded[1500];
size_t encoded_len = 0;
check(leonida_opus_encode_test(tone.data(), 960, 2, encoded, sizeof encoded, &encoded_len) == LEONIDA_OPUS_OK &&
encoded_len > 0,
"a synthetic 20 ms stereo Opus packet encodes");
std::memcpy(base, encoded, encoded_len);
auto* const pcm = base + 0x14000 + 3 * 0x1E00;
std::memset(pcm, 0x55, 0x1E00 + 64);
ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, static_cast<uint32_t>(encoded_len), base, 0x1E00, pcm};
uint32_t total = 0;
check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted");
check(enqueue(apu, &process, &total) == kQueueFull && total == 2,
"a third command on a stream of two is 0x8AC81000");
check(count(apu, nullptr) == 2, "two results ready");
Result r{};
check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.error == S_OK,
"results come in command order: the activate first");
check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows");
uint32_t dword34 = 0;
std::memcpy(&dword34, reinterpret_cast<const uint8_t*>(&r) + 0x34, 4);
check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == base &&
r.input_bytes == static_cast<uint32_t>(encoded_len),
"960 stereo float frames, the byte count at +0x34, the buffers echoed");
float energy = 0.0f;
const auto* floats = reinterpret_cast<const float*>(pcm);
for (uint32_t i = 0; i < 960 * 2; ++i) energy += floats[i] * floats[i];
energy /= 960 * 2;
check(energy > 0.01f, "the decoded tone has energy");
check(pcm[960 * 8] == 0x55, "nothing past the decoded range is written");
check(count(apu, nullptr) == 0, "the queue is empty after both results");
// first_frame, frame_count and what output_bytes holds each clip the decoded frames.
process.first_frame = 500;
process.frame_count = 4000;
enqueue(apu, &process, nullptr);
dequeue(apu, &r);
check(r.error == S_OK && r.frames == 460 && r.output_bytes == 460 * 8, "frames from first_frame to the packet's end");
process.frame_count = 300;
enqueue(apu, &process, nullptr);
dequeue(apu, &r);
check(r.frames == 300 && r.output_bytes == 300 * 8, "no more than frame_count");
process.frame_count = 4000;
process.output_bytes = 100 * 8 + 7;
enqueue(apu, &process, nullptr);
dequeue(apu, &r);
check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds");
// Errors carried in the result.
ProcessCommand empty = process;
empty.input_bytes = 0;
check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
"an empty input: E_INVALIDARG in the result");
empty = process;
empty.output = nullptr;
check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG,
"a null output: E_INVALIDARG in the result");
ProcessCommand stray = process;
stray.id.stream = 4;
check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream,
"a process on a stream never activated: 0x8AC81003 in the result");
// Deactivate closes the stream; activating again creates a fresh decoder.
const CommandId deactivate = id(2, 3);
check(enqueue(apu, &deactivate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK,
"deactivate gives a result and closes the stream");
check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream,
"after deactivate the stream takes no process command");
check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK,
"the stream can be activated again");
check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)");
std::printf("%d checks, %d failures\n", g_checks, g_failures);
return g_failures ? 1 : 0;
}

View File

@ -86,7 +86,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) 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\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_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_pso_stream.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\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" }
$files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_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_pso_stream.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\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_queue.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 = @"