Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/audio_hal_exe_calls.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
26 changes: 14 additions & 12 deletions docs/runtime_imports.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
73 changes: 72 additions & 1 deletion runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -338,6 +387,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.
Expand Down Expand Up @@ -368,9 +420,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
)
Expand All @@ -379,6 +433,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.
Expand Down Expand Up @@ -1542,6 +1610,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()
Expand Down
23 changes: 23 additions & 0 deletions runtime/cmake/opus_decoder.cmake
Original file line number Diff line number Diff line change
@@ -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 changes: 16 additions & 0 deletions runtime/opus_decoder/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions runtime/opus_decoder/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
33 changes: 33 additions & 0 deletions runtime/opus_decoder/README.md
Original file line number Diff line number Diff line change
@@ -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.
44 changes: 44 additions & 0 deletions runtime/opus_decoder/leonida_opus_decoder.h
Original file line number Diff line number Diff line change
@@ -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
Loading