diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-26 09:16:29 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-26 09:16:29 -0500 |
| commit | 399ecdd511fe8499d2feb3681e82efda37ced17d (patch) | |
| tree | c6194830ee1d33870b9867329676c57366aff581 /runtime | |
| parent | f5f67b4a9daae13d5a8a68358c1167e6866ec293 (diff) | |
| parent | 4cfbdfc0b2e39e9137b7f40c48863f1e0e444adc (diff) | |
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>
Diffstat (limited to 'runtime')
| -rw-r--r-- | runtime/CMakeLists.txt | 73 | ||||
| -rw-r--r-- | runtime/cmake/opus_decoder.cmake | 23 | ||||
| -rw-r--r-- | runtime/opus_decoder/Cargo.lock | 16 | ||||
| -rw-r--r-- | runtime/opus_decoder/Cargo.toml | 16 | ||||
| -rw-r--r-- | runtime/opus_decoder/README.md | 33 | ||||
| -rw-r--r-- | runtime/opus_decoder/leonida_opus_decoder.h | 44 | ||||
| -rw-r--r-- | runtime/opus_decoder/src/lib.rs | 244 | ||||
| -rw-r--r-- | runtime/shims/xapu_chad.cpp | 123 | ||||
| -rw-r--r-- | runtime/shims/xapu_queue.cpp | 438 | ||||
| -rw-r--r-- | runtime/test/xapu_chad_test.cpp | 261 | ||||
| -rw-r--r-- | runtime/test/xapu_opus_test.cpp | 193 |
11 files changed, 1305 insertions, 159 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3efda223e..e18e5871e 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt | |||
| @@ -158,6 +158,54 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 158 | message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable") | 158 | message(FATAL_ERROR "LEONIDA_REQUIRE_XMA2_DECODER is enabled, but the Rust XMA2 decoder is unavailable") |
| 159 | endif() | 159 | endif() |
| 160 | 160 | ||
| 161 | # Rust Opus decoder (runtime/opus_decoder), the same pattern as the XMA2 decoder: cargo at | ||
| 162 | # configure time, a prebuilt -DLEONIDA_OPUS_DECODER_LIB, or the silent path in xapu_queue.cpp. | ||
| 163 | option(LEONIDA_REQUIRE_OPUS_DECODER "Fail configure if the Rust Opus decoder is unavailable" OFF) | ||
| 164 | set(LEONIDA_OPUS_DECODER_LIB "" CACHE FILEPATH | ||
| 165 | "Prebuilt leonida_opus_decoder.lib (skips running cargo at configure time)") | ||
| 166 | include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/opus_decoder.cmake") | ||
| 167 | leonida_resolve_prebuilt_opus_decoder("${LEONIDA_OPUS_DECODER_LIB}" "${CMAKE_BINARY_DIR}" _opus_lib_resolved) | ||
| 168 | if(_opus_lib_resolved) | ||
| 169 | message(STATUS "Using prebuilt Rust Opus decoder: ${_opus_lib_resolved}") | ||
| 170 | else() | ||
| 171 | if(NOT LEONIDA_CARGO) | ||
| 172 | find_program(LEONIDA_CARGO cargo) | ||
| 173 | endif() | ||
| 174 | if(LEONIDA_CARGO) | ||
| 175 | set(_opus_target x86_64-pc-windows-msvc) | ||
| 176 | set(_opus_target_dir ${CMAKE_BINARY_DIR}/opus_decoder) | ||
| 177 | set(_opus_lib ${_opus_target_dir}/${_opus_target}/release/leonida_opus_decoder.lib) | ||
| 178 | set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS | ||
| 179 | ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.toml | ||
| 180 | ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.lock | ||
| 181 | ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/src/lib.rs) | ||
| 182 | execute_process( | ||
| 183 | COMMAND ${LEONIDA_CARGO} build --release --locked --target ${_opus_target} | ||
| 184 | --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder/Cargo.toml | ||
| 185 | --target-dir ${_opus_target_dir} | ||
| 186 | TIMEOUT 300 | ||
| 187 | RESULT_VARIABLE _opus_result) | ||
| 188 | if(_opus_result STREQUAL "0" AND EXISTS "${_opus_lib}") | ||
| 189 | set(_opus_lib_resolved "${_opus_lib}") | ||
| 190 | else() | ||
| 191 | message(WARNING "cargo build of runtime/opus_decoder failed: the XAPU Opus path will be silent") | ||
| 192 | endif() | ||
| 193 | else() | ||
| 194 | message(STATUS "cargo not found: runtime/opus_decoder not built, the XAPU Opus path will be silent") | ||
| 195 | endif() | ||
| 196 | endif() | ||
| 197 | if(_opus_lib_resolved) | ||
| 198 | add_library(leonida_opus_decoder STATIC IMPORTED) | ||
| 199 | set_target_properties(leonida_opus_decoder PROPERTIES | ||
| 200 | IMPORTED_LOCATION "${_opus_lib_resolved}" | ||
| 201 | INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/opus_decoder" | ||
| 202 | INTERFACE_COMPILE_DEFINITIONS LEONIDA_HAVE_OPUS_DECODER=1 | ||
| 203 | INTERFACE_LINK_LIBRARIES "kernel32;ntdll;userenv;ws2_32;dbghelp;synchronization") | ||
| 204 | endif() | ||
| 205 | if(LEONIDA_REQUIRE_OPUS_DECODER AND NOT TARGET leonida_opus_decoder) | ||
| 206 | message(FATAL_ERROR "LEONIDA_REQUIRE_OPUS_DECODER is enabled, but the Rust Opus decoder is unavailable") | ||
| 207 | endif() | ||
| 208 | |||
| 161 | find_package(Python3 COMPONENTS Interpreter REQUIRED) | 209 | find_package(Python3 COMPONENTS Interpreter REQUIRED) |
| 162 | set(bcpack_tools "${CMAKE_CURRENT_SOURCE_DIR}/../tools") | 210 | set(bcpack_tools "${CMAKE_CURRENT_SOURCE_DIR}/../tools") |
| 163 | set(bcpack_tables "${CMAKE_CURRENT_BINARY_DIR}/bcpack_tables.inc") | 211 | set(bcpack_tables "${CMAKE_CURRENT_BINARY_DIR}/bcpack_tables.inc") |
| @@ -199,6 +247,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 199 | shims/com_shim.cpp | 247 | shims/com_shim.cpp |
| 200 | shims/silent_audio.cpp | 248 | shims/silent_audio.cpp |
| 201 | shims/bcrypt_rng.cpp | 249 | shims/bcrypt_rng.cpp |
| 250 | shims/xapu_queue.cpp | ||
| 202 | shims/xapu_chad.cpp | 251 | shims/xapu_chad.cpp |
| 203 | shims/dstorage.cpp | 252 | shims/dstorage.cpp |
| 204 | ) | 253 | ) |
| @@ -352,6 +401,9 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 352 | target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder) | 401 | target_link_libraries(gta6rt PRIVATE leonida_xma2_decoder) |
| 353 | target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder) | 402 | target_link_libraries(acphal_test PRIVATE leonida_xma2_decoder) |
| 354 | endif() | 403 | endif() |
| 404 | if(TARGET leonida_opus_decoder) | ||
| 405 | target_link_libraries(gta6rt PRIVATE leonida_opus_decoder) | ||
| 406 | endif() | ||
| 355 | 407 | ||
| 356 | # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for | 408 | # The Zen 2 instructions a desktop CPU may lack (src/cpu_emulation.h): decoded, emulated on a CONTEXT, and run for |
| 357 | # real with the #UD handler installed, so an Intel host takes the emulated path and an AMD one the native path. | 409 | # 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) | |||
| 382 | target_link_options(dstorage_test PRIVATE /OPT:NOREF) | 434 | target_link_options(dstorage_test PRIVATE /OPT:NOREF) |
| 383 | target_link_libraries(dstorage_test PRIVATE gta6rt_bcpack psapi) | 435 | target_link_libraries(dstorage_test PRIVATE gta6rt_bcpack psapi) |
| 384 | 436 | ||
| 385 | # xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test. | 437 | # xapu.dll and chad.dll, the APU and audio DSP command queues, resolved through the registry like xmem_test; Opus |
| 438 | # frame counts from hand-made packets. | ||
| 386 | add_executable(xapu_chad_test | 439 | add_executable(xapu_chad_test |
| 387 | test/xapu_chad_test.cpp | 440 | test/xapu_chad_test.cpp |
| 441 | shims/xapu_queue.cpp | ||
| 388 | shims/xapu_chad.cpp | 442 | shims/xapu_chad.cpp |
| 389 | shims/registry.cpp | 443 | shims/registry.cpp |
| 390 | ) | 444 | ) |
| @@ -393,6 +447,20 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) | |||
| 393 | target_compile_options(xapu_chad_test PRIVATE /W4 /permissive- /utf-8) | 447 | target_compile_options(xapu_chad_test PRIVATE /W4 /permissive- /utf-8) |
| 394 | target_link_options(xapu_chad_test PRIVATE /OPT:NOREF) | 448 | target_link_options(xapu_chad_test PRIVATE /OPT:NOREF) |
| 395 | 449 | ||
| 450 | if(TARGET leonida_opus_decoder) | ||
| 451 | # xapu_queue.cpp with the decoder compiled in, against the generated Opus tone. | ||
| 452 | add_executable(xapu_opus_test | ||
| 453 | test/xapu_opus_test.cpp | ||
| 454 | shims/xapu_queue.cpp | ||
| 455 | shims/registry.cpp | ||
| 456 | ) | ||
| 457 | target_include_directories(xapu_opus_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) | ||
| 458 | target_compile_definitions(xapu_opus_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) | ||
| 459 | target_compile_options(xapu_opus_test PRIVATE /W4 /permissive- /utf-8) | ||
| 460 | target_link_options(xapu_opus_test PRIVATE /OPT:NOREF) | ||
| 461 | target_link_libraries(xapu_opus_test PRIVATE leonida_opus_decoder) | ||
| 462 | endif() | ||
| 463 | |||
| 396 | # The boot stack's earlier xapu.dll and chad.dll shims (shims/xapu.cpp, shims/chad.cpp), which gta6rt no longer | 464 | # The boot stack's earlier xapu.dll and chad.dll shims (shims/xapu.cpp, shims/chad.cpp), which gta6rt no longer |
| 397 | # links (it serves both DLLs from xapu_chad.cpp): their ABI tests stay as tests of those files. | 465 | # links (it serves both DLLs from xapu_chad.cpp): their ABI tests stay as tests of those files. |
| 398 | # xapu shim ABI test: resolves the registered xapu.dll exports through the registry. | 466 | # xapu shim ABI test: resolves the registered xapu.dll exports through the registry. |
| @@ -1599,6 +1667,9 @@ if(BUILD_TESTING) | |||
| 1599 | if(WIN32 AND TARGET xapu_chad_test) | 1667 | if(WIN32 AND TARGET xapu_chad_test) |
| 1600 | add_test(NAME xapu_chad COMMAND xapu_chad_test) | 1668 | add_test(NAME xapu_chad COMMAND xapu_chad_test) |
| 1601 | endif() | 1669 | endif() |
| 1670 | if(WIN32 AND TARGET xapu_opus_test) | ||
| 1671 | add_test(NAME xapu_opus COMMAND xapu_opus_test) | ||
| 1672 | endif() | ||
| 1602 | if(WIN32 AND TARGET xapu_test) | 1673 | if(WIN32 AND TARGET xapu_test) |
| 1603 | add_test(NAME xapu COMMAND xapu_test) | 1674 | add_test(NAME xapu COMMAND xapu_test) |
| 1604 | endif() | 1675 | endif() |
diff --git a/runtime/cmake/opus_decoder.cmake b/runtime/cmake/opus_decoder.cmake new file mode 100644 index 000000000..1286b15fa --- /dev/null +++ b/runtime/cmake/opus_decoder.cmake | |||
| @@ -0,0 +1,23 @@ | |||
| 1 | # Resolves -DLEONIDA_OPUS_DECODER_LIB=<path> for runtime/CMakeLists.txt. | ||
| 2 | # | ||
| 3 | # When LEONIDA_OPUS_DECODER_LIB is set, the runtime links that prebuilt static library directly and | ||
| 4 | # skips running cargo at configure time. A value that does not name an existing file is a configure | ||
| 5 | # error rather than a silent fallback to silent XAPU output. | ||
| 6 | function(leonida_resolve_prebuilt_opus_decoder lib_input base_dir out_var) | ||
| 7 | if(NOT lib_input) | ||
| 8 | set(${out_var} "" PARENT_SCOPE) | ||
| 9 | return() | ||
| 10 | endif() | ||
| 11 | if(IS_ABSOLUTE "${lib_input}") | ||
| 12 | set(_resolved "${lib_input}") | ||
| 13 | else() | ||
| 14 | cmake_path(ABSOLUTE_PATH lib_input BASE_DIRECTORY "${base_dir}" NORMALIZE OUTPUT_VARIABLE _resolved) | ||
| 15 | endif() | ||
| 16 | if(EXISTS "${_resolved}" AND NOT IS_DIRECTORY "${_resolved}") | ||
| 17 | set(${out_var} "${_resolved}" PARENT_SCOPE) | ||
| 18 | else() | ||
| 19 | message(FATAL_ERROR | ||
| 20 | "LEONIDA_OPUS_DECODER_LIB does not point to an existing file: ${_resolved} " | ||
| 21 | "(pass the path to leonida_opus_decoder.lib or leave it empty to build with cargo)") | ||
| 22 | endif() | ||
| 23 | endfunction() | ||
diff --git a/runtime/opus_decoder/Cargo.lock b/runtime/opus_decoder/Cargo.lock new file mode 100644 index 000000000..1659ab14e --- /dev/null +++ b/runtime/opus_decoder/Cargo.lock | |||
| @@ -0,0 +1,16 @@ | |||
| 1 | # This file is automatically @generated by Cargo. | ||
| 2 | # It is not intended for manual editing. | ||
| 3 | version = 4 | ||
| 4 | |||
| 5 | [[package]] | ||
| 6 | name = "leonida-opus-decoder" | ||
| 7 | version = "0.1.0" | ||
| 8 | dependencies = [ | ||
| 9 | "opus-pure", | ||
| 10 | ] | ||
| 11 | |||
| 12 | [[package]] | ||
| 13 | name = "opus-pure" | ||
| 14 | version = "0.2.5" | ||
| 15 | source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 16 | checksum = "2da6dcc20af557d030b6f206e75c764bcda8c28a5bd03c73935c7e8fcf5f4f4a" | ||
diff --git a/runtime/opus_decoder/Cargo.toml b/runtime/opus_decoder/Cargo.toml new file mode 100644 index 000000000..e3ed59bc3 --- /dev/null +++ b/runtime/opus_decoder/Cargo.toml | |||
| @@ -0,0 +1,16 @@ | |||
| 1 | [package] | ||
| 2 | name = "leonida-opus-decoder" | ||
| 3 | version = "0.1.0" | ||
| 4 | edition = "2021" | ||
| 5 | license = "GPL-3.0-or-later" | ||
| 6 | publish = false | ||
| 7 | |||
| 8 | [lib] | ||
| 9 | name = "leonida_opus_decoder" | ||
| 10 | crate-type = ["staticlib", "rlib"] | ||
| 11 | |||
| 12 | [dependencies] | ||
| 13 | opus-pure = "0.2.4" | ||
| 14 | |||
| 15 | [profile.release] | ||
| 16 | panic = "unwind" | ||
diff --git a/runtime/opus_decoder/README.md b/runtime/opus_decoder/README.md new file mode 100644 index 000000000..2b516e496 --- /dev/null +++ b/runtime/opus_decoder/README.md | |||
| @@ -0,0 +1,33 @@ | |||
| 1 | # Opus decoder C ABI | ||
| 2 | |||
| 3 | This crate exposes a C ABI around the BSD-3-Clause `opus-pure` package for the console audio | ||
| 4 | decoder (`xapu.dll`). The command protocol lives in `runtime/shims/xapu_chad.cpp`; this crate only | ||
| 5 | decodes one Opus packet into interleaved f32 PCM, resets the decoder, and (for tests) encodes a | ||
| 6 | synthetic tone. | ||
| 7 | |||
| 8 | ## Build | ||
| 9 | |||
| 10 | ```sh | ||
| 11 | cargo fmt --manifest-path runtime/opus_decoder/Cargo.toml -- --check | ||
| 12 | cargo test --manifest-path runtime/opus_decoder/Cargo.toml --locked | ||
| 13 | cargo build --release --manifest-path runtime/opus_decoder/Cargo.toml --locked | ||
| 14 | ``` | ||
| 15 | |||
| 16 | `runtime/CMakeLists.txt` builds this crate for `x86_64-pc-windows-msvc` at configure time when | ||
| 17 | `cargo` is on `PATH` and links it into `gta6rt` and `xapu_chad_test` with | ||
| 18 | `LEONIDA_HAVE_OPUS_DECODER` defined. The first build fetches `opus-pure` from crates.io. Set | ||
| 19 | `CARGO_NET_OFFLINE=true` for a configure that uses only the local Cargo cache. | ||
| 20 | |||
| 21 | Without `cargo`, when the build fails, or with the `cl.exe` fallback of `scripts/build_runtime.ps1`, | ||
| 22 | the XAPU path stays silent. Use `-DLEONIDA_REQUIRE_OPUS_DECODER=ON` to require the decoder in a | ||
| 23 | CMake build. | ||
| 24 | |||
| 25 | To link an already-built `leonida_opus_decoder.lib` without invoking `cargo` during CMake | ||
| 26 | configure, pass `-DLEONIDA_OPUS_DECODER_LIB=<path>`. | ||
| 27 | |||
| 28 | ## Facts and credit | ||
| 29 | |||
| 30 | The `xapu.dll` command protocol (connect input/output, per-stream command budget, activate / | ||
| 31 | process / reset / deactivate, result order) follows Marvisak/VIctory | ||
| 32 | `crates/victory-hle/src/modules/apu.rs` (GPL-3.0-or-later), which this repository already credits for | ||
| 33 | other modules. `opus-pure` is BSD-3-Clause and stays a dependency; no code from it is copied. | ||
diff --git a/runtime/opus_decoder/leonida_opus_decoder.h b/runtime/opus_decoder/leonida_opus_decoder.h new file mode 100644 index 000000000..d5473510d --- /dev/null +++ b/runtime/opus_decoder/leonida_opus_decoder.h | |||
| @@ -0,0 +1,44 @@ | |||
| 1 | #ifndef LEONIDA_OPUS_DECODER_H | ||
| 2 | #define LEONIDA_OPUS_DECODER_H | ||
| 3 | |||
| 4 | #include <stddef.h> | ||
| 5 | #include <stdint.h> | ||
| 6 | |||
| 7 | #ifdef __cplusplus | ||
| 8 | extern "C" { | ||
| 9 | #endif | ||
| 10 | |||
| 11 | /* 120 ms at 48 kHz: the longest Opus packet, in samples per channel. */ | ||
| 12 | #define LEONIDA_OPUS_MAX_FRAMES 5760u | ||
| 13 | |||
| 14 | typedef struct LeonidaOpusDecoder LeonidaOpusDecoder; | ||
| 15 | |||
| 16 | enum LeonidaOpusStatus { | ||
| 17 | LEONIDA_OPUS_OK = 0, | ||
| 18 | LEONIDA_OPUS_INVALID_ARGUMENT = 1, | ||
| 19 | LEONIDA_OPUS_INVALID_FORMAT = 2, | ||
| 20 | LEONIDA_OPUS_DECODER_FAILURE = 3, | ||
| 21 | LEONIDA_OPUS_OUT_OF_MEMORY = 4, | ||
| 22 | LEONIDA_OPUS_PANIC = 5, | ||
| 23 | LEONIDA_OPUS_BUFFER_TOO_SMALL = 6, | ||
| 24 | }; | ||
| 25 | |||
| 26 | int32_t leonida_opus_decoder_create(uint32_t sample_rate, uint32_t channels, | ||
| 27 | LeonidaOpusDecoder **out_decoder); | ||
| 28 | uint32_t leonida_opus_decoder_channels(const LeonidaOpusDecoder *decoder); | ||
| 29 | int32_t leonida_opus_decode_packet(LeonidaOpusDecoder *decoder, | ||
| 30 | const uint8_t *input, size_t input_len, | ||
| 31 | float *out, size_t out_capacity_frames, | ||
| 32 | uint32_t *out_frames); | ||
| 33 | int32_t leonida_opus_decoder_reset(LeonidaOpusDecoder *decoder); | ||
| 34 | void leonida_opus_decoder_destroy(LeonidaOpusDecoder *decoder); | ||
| 35 | /* Test helper: encodes frame_count interleaved f32 frames to one packet at 48 kHz. */ | ||
| 36 | int32_t leonida_opus_encode_test(const float *input, uint32_t frame_count, | ||
| 37 | uint32_t channels, uint8_t *out, | ||
| 38 | size_t out_capacity, size_t *out_len); | ||
| 39 | |||
| 40 | #ifdef __cplusplus | ||
| 41 | } | ||
| 42 | #endif | ||
| 43 | |||
| 44 | #endif | ||
diff --git a/runtime/opus_decoder/src/lib.rs b/runtime/opus_decoder/src/lib.rs new file mode 100644 index 000000000..1e6c7dc83 --- /dev/null +++ b/runtime/opus_decoder/src/lib.rs | |||
| @@ -0,0 +1,244 @@ | |||
| 1 | #![deny(unsafe_op_in_unsafe_fn)] | ||
| 2 | |||
| 3 | //! C ABI around the pure-Rust `opus-pure` decoder, for the console audio decoder (`xapu.dll`). | ||
| 4 | //! | ||
| 5 | //! The command protocol lives in `runtime/shims/xapu_chad.cpp`; this crate only turns one Opus | ||
| 6 | //! packet into interleaved f32 PCM, resets the decoder, and (for tests) encodes a synthetic tone. | ||
| 7 | //! `opus-pure` is BSD-3-Clause; this wrapper is GPL-3.0-or-later, like the rest of the runtime. | ||
| 8 | |||
| 9 | use std::panic::{catch_unwind, AssertUnwindSafe}; | ||
| 10 | use std::ptr; | ||
| 11 | use std::sync::Mutex; | ||
| 12 | |||
| 13 | use opus_pure::{Application, OpusDecoder, OpusEncoder}; | ||
| 14 | |||
| 15 | pub const LEONIDA_OPUS_OK: i32 = 0; | ||
| 16 | pub const LEONIDA_OPUS_INVALID_ARGUMENT: i32 = 1; | ||
| 17 | pub const LEONIDA_OPUS_INVALID_FORMAT: i32 = 2; | ||
| 18 | pub const LEONIDA_OPUS_DECODER_FAILURE: i32 = 3; | ||
| 19 | pub const LEONIDA_OPUS_OUT_OF_MEMORY: i32 = 4; | ||
| 20 | pub const LEONIDA_OPUS_PANIC: i32 = 5; | ||
| 21 | pub const LEONIDA_OPUS_BUFFER_TOO_SMALL: i32 = 6; | ||
| 22 | |||
| 23 | /// 120 ms at 48 kHz, the longest Opus packet, in samples per channel. | ||
| 24 | pub const LEONIDA_OPUS_MAX_FRAMES: usize = 5760; | ||
| 25 | |||
| 26 | #[repr(C)] | ||
| 27 | pub struct LeonidaOpusDecoder { | ||
| 28 | decoder: Mutex<OpusDecoder>, | ||
| 29 | channels: usize, | ||
| 30 | } | ||
| 31 | |||
| 32 | #[no_mangle] | ||
| 33 | pub unsafe extern "C" fn leonida_opus_decoder_channels(decoder: *const LeonidaOpusDecoder) -> u32 { | ||
| 34 | if decoder.is_null() { | ||
| 35 | return 0; | ||
| 36 | } | ||
| 37 | unsafe { (*decoder).channels as u32 } | ||
| 38 | } | ||
| 39 | |||
| 40 | /// Creates a decoder for one mono or stereo Opus stream at `sample_rate` (the title uses 48000). | ||
| 41 | /// | ||
| 42 | /// # Safety | ||
| 43 | /// `out` must be writable for one pointer. The returned decoder must be destroyed once, after | ||
| 44 | /// every call that uses it has finished. | ||
| 45 | #[no_mangle] | ||
| 46 | pub unsafe extern "C" fn leonida_opus_decoder_create( | ||
| 47 | sample_rate: u32, | ||
| 48 | channels: u32, | ||
| 49 | out: *mut *mut LeonidaOpusDecoder, | ||
| 50 | ) -> i32 { | ||
| 51 | if out.is_null() { | ||
| 52 | return LEONIDA_OPUS_INVALID_ARGUMENT; | ||
| 53 | } | ||
| 54 | unsafe { *out = ptr::null_mut() }; | ||
| 55 | if sample_rate == 0 || sample_rate > i32::MAX as u32 || !(1..=2).contains(&channels) { | ||
| 56 | return LEONIDA_OPUS_INVALID_FORMAT; | ||
| 57 | } | ||
| 58 | match catch_unwind(AssertUnwindSafe(|| { | ||
| 59 | OpusDecoder::new(sample_rate as i32, channels as usize).map(|decoder| { | ||
| 60 | Box::new(LeonidaOpusDecoder { | ||
| 61 | decoder: Mutex::new(decoder), | ||
| 62 | channels: channels as usize, | ||
| 63 | }) | ||
| 64 | }) | ||
| 65 | })) { | ||
| 66 | Ok(Ok(decoder)) => { | ||
| 67 | unsafe { *out = Box::into_raw(decoder) }; | ||
| 68 | LEONIDA_OPUS_OK | ||
| 69 | } | ||
| 70 | Ok(Err(_)) => LEONIDA_OPUS_INVALID_FORMAT, | ||
| 71 | Err(_) => LEONIDA_OPUS_PANIC, | ||
| 72 | } | ||
| 73 | } | ||
| 74 | |||
| 75 | /// Decodes one Opus packet into `out` as interleaved f32 frames. | ||
| 76 | /// | ||
| 77 | /// # Safety | ||
| 78 | /// `decoder` must come from `leonida_opus_decoder_create`. `input` must reference `input_len` | ||
| 79 | /// readable bytes; `out` must hold `out_capacity_frames * channels` floats; `out_frames` must be | ||
| 80 | /// writable. Do not destroy the decoder concurrently with this call. | ||
| 81 | #[no_mangle] | ||
| 82 | pub unsafe extern "C" fn leonida_opus_decode_packet( | ||
| 83 | decoder: *mut LeonidaOpusDecoder, | ||
| 84 | input: *const u8, | ||
| 85 | input_len: usize, | ||
| 86 | out: *mut f32, | ||
| 87 | out_capacity_frames: usize, | ||
| 88 | out_frames: *mut u32, | ||
| 89 | ) -> i32 { | ||
| 90 | if decoder.is_null() | ||
| 91 | || input.is_null() | ||
| 92 | || input_len == 0 | ||
| 93 | || out.is_null() | ||
| 94 | || out_frames.is_null() | ||
| 95 | { | ||
| 96 | return LEONIDA_OPUS_INVALID_ARGUMENT; | ||
| 97 | } | ||
| 98 | let decoder = unsafe { &*decoder }; | ||
| 99 | let channels = decoder.channels; | ||
| 100 | let Ok(mut guard) = decoder.decoder.lock() else { | ||
| 101 | return LEONIDA_OPUS_DECODER_FAILURE; | ||
| 102 | }; | ||
| 103 | let packet = unsafe { std::slice::from_raw_parts(input, input_len) }; | ||
| 104 | let mut pcm = vec![0f32; LEONIDA_OPUS_MAX_FRAMES * channels]; | ||
| 105 | match guard.decode(packet, LEONIDA_OPUS_MAX_FRAMES, &mut pcm) { | ||
| 106 | Ok(frames) => { | ||
| 107 | if frames > out_capacity_frames { | ||
| 108 | return LEONIDA_OPUS_BUFFER_TOO_SMALL; | ||
| 109 | } | ||
| 110 | let samples = frames * channels; | ||
| 111 | unsafe { | ||
| 112 | ptr::copy_nonoverlapping(pcm.as_ptr(), out, samples); | ||
| 113 | *out_frames = frames as u32; | ||
| 114 | } | ||
| 115 | LEONIDA_OPUS_OK | ||
| 116 | } | ||
| 117 | Err(_) => LEONIDA_OPUS_DECODER_FAILURE, | ||
| 118 | } | ||
| 119 | } | ||
| 120 | |||
| 121 | /// # Safety | ||
| 122 | /// `decoder` must come from `leonida_opus_decoder_create` and not be used concurrently. | ||
| 123 | #[no_mangle] | ||
| 124 | pub unsafe extern "C" fn leonida_opus_decoder_reset(decoder: *mut LeonidaOpusDecoder) -> i32 { | ||
| 125 | if decoder.is_null() { | ||
| 126 | return LEONIDA_OPUS_INVALID_ARGUMENT; | ||
| 127 | } | ||
| 128 | let decoder = unsafe { &*decoder }; | ||
| 129 | let Ok(mut guard) = decoder.decoder.lock() else { | ||
| 130 | return LEONIDA_OPUS_DECODER_FAILURE; | ||
| 131 | }; | ||
| 132 | let _ = guard.reset_state(); | ||
| 133 | LEONIDA_OPUS_OK | ||
| 134 | } | ||
| 135 | |||
| 136 | /// # Safety | ||
| 137 | /// `decoder` must be a live handle and must not be used after this call. | ||
| 138 | #[no_mangle] | ||
| 139 | pub unsafe extern "C" fn leonida_opus_decoder_destroy(decoder: *mut LeonidaOpusDecoder) { | ||
| 140 | if !decoder.is_null() { | ||
| 141 | unsafe { drop(Box::from_raw(decoder)) }; | ||
| 142 | } | ||
| 143 | } | ||
| 144 | |||
| 145 | /// Test helper: encodes `frame_count` interleaved f32 frames to one Opus packet at 48 kHz. | ||
| 146 | /// | ||
| 147 | /// # Safety | ||
| 148 | /// `input` must hold `frame_count * channels` floats; `out` must hold `out_capacity` bytes; | ||
| 149 | /// `out_len` must be writable. | ||
| 150 | #[no_mangle] | ||
| 151 | pub unsafe extern "C" fn leonida_opus_encode_test( | ||
| 152 | input: *const f32, | ||
| 153 | frame_count: u32, | ||
| 154 | channels: u32, | ||
| 155 | out: *mut u8, | ||
| 156 | out_capacity: usize, | ||
| 157 | out_len: *mut usize, | ||
| 158 | ) -> i32 { | ||
| 159 | if input.is_null() | ||
| 160 | || out.is_null() | ||
| 161 | || out_len.is_null() | ||
| 162 | || frame_count == 0 | ||
| 163 | || !(1..=2).contains(&channels) | ||
| 164 | { | ||
| 165 | return LEONIDA_OPUS_INVALID_ARGUMENT; | ||
| 166 | } | ||
| 167 | let samples = frame_count as usize * channels as usize; | ||
| 168 | let input = unsafe { std::slice::from_raw_parts(input, samples) }; | ||
| 169 | let mut encoder = match OpusEncoder::new(48_000, channels as usize, Application::Audio) { | ||
| 170 | Ok(encoder) => encoder, | ||
| 171 | Err(_) => return LEONIDA_OPUS_INVALID_FORMAT, | ||
| 172 | }; | ||
| 173 | let mut packet = vec![0u8; out_capacity.max(4000)]; | ||
| 174 | match encoder.encode(input, frame_count as usize, &mut packet) { | ||
| 175 | Ok(bytes) if bytes <= out_capacity => { | ||
| 176 | unsafe { | ||
| 177 | ptr::copy_nonoverlapping(packet.as_ptr(), out, bytes); | ||
| 178 | *out_len = bytes; | ||
| 179 | } | ||
| 180 | LEONIDA_OPUS_OK | ||
| 181 | } | ||
| 182 | Ok(_) => LEONIDA_OPUS_BUFFER_TOO_SMALL, | ||
| 183 | Err(_) => LEONIDA_OPUS_DECODER_FAILURE, | ||
| 184 | } | ||
| 185 | } | ||
| 186 | |||
| 187 | #[cfg(test)] | ||
| 188 | mod tests { | ||
| 189 | use super::*; | ||
| 190 | |||
| 191 | #[test] | ||
| 192 | fn encodes_and_decodes_a_tone() { | ||
| 193 | const FRAMES: u32 = 960; | ||
| 194 | const CHANNELS: u32 = 2; | ||
| 195 | let mut tone = Vec::with_capacity((FRAMES * CHANNELS) as usize); | ||
| 196 | for i in 0..FRAMES { | ||
| 197 | let sample = ((i as f32) * 440.0 * std::f32::consts::TAU / 48_000.0).sin() * 0.5; | ||
| 198 | tone.push(sample); | ||
| 199 | tone.push(sample); | ||
| 200 | } | ||
| 201 | let mut packet = [0u8; 1500]; | ||
| 202 | let mut packet_len = 0usize; | ||
| 203 | // SAFETY: the buffers are owned by this test. | ||
| 204 | let encoded = unsafe { | ||
| 205 | leonida_opus_encode_test( | ||
| 206 | tone.as_ptr(), | ||
| 207 | FRAMES, | ||
| 208 | CHANNELS, | ||
| 209 | packet.as_mut_ptr(), | ||
| 210 | packet.len(), | ||
| 211 | &mut packet_len, | ||
| 212 | ) | ||
| 213 | }; | ||
| 214 | assert_eq!(encoded, LEONIDA_OPUS_OK); | ||
| 215 | assert!(packet_len > 0); | ||
| 216 | |||
| 217 | let mut decoder = ptr::null_mut(); | ||
| 218 | // SAFETY: `decoder` is writable for one pointer. | ||
| 219 | assert_eq!( | ||
| 220 | unsafe { leonida_opus_decoder_create(48_000, CHANNELS, &mut decoder) }, | ||
| 221 | LEONIDA_OPUS_OK | ||
| 222 | ); | ||
| 223 | let mut pcm = vec![0f32; LEONIDA_OPUS_MAX_FRAMES * CHANNELS as usize]; | ||
| 224 | let mut frames = 0u32; | ||
| 225 | // SAFETY: the packet and PCM buffers are owned by this test. | ||
| 226 | let decoded = unsafe { | ||
| 227 | leonida_opus_decode_packet( | ||
| 228 | decoder, | ||
| 229 | packet.as_ptr(), | ||
| 230 | packet_len, | ||
| 231 | pcm.as_mut_ptr(), | ||
| 232 | LEONIDA_OPUS_MAX_FRAMES, | ||
| 233 | &mut frames, | ||
| 234 | ) | ||
| 235 | }; | ||
| 236 | assert_eq!(decoded, LEONIDA_OPUS_OK); | ||
| 237 | assert_eq!(frames, FRAMES); | ||
| 238 | let energy: f32 = | ||
| 239 | pcm[..(frames * CHANNELS) as usize].iter().map(|s| s * s).sum::<f32>() / (frames * CHANNELS) as f32; | ||
| 240 | assert!(energy > 0.01, "decoded a tone, energy {energy}"); | ||
| 241 | // SAFETY: created above, destroyed once. | ||
| 242 | unsafe { leonida_opus_decoder_destroy(decoder) }; | ||
| 243 | } | ||
| 244 | } | ||
diff --git a/runtime/shims/xapu_chad.cpp b/runtime/shims/xapu_chad.cpp index 35bda2b72..e46a61c97 100644 --- a/runtime/shims/xapu_chad.cpp +++ b/runtime/shims/xapu_chad.cpp | |||
| @@ -1,24 +1,8 @@ | |||
| 1 | // xapu.dll and chad.dll: the console's audio processing unit (APU) and audio DSP command queues. No PC has either, | 1 | // chad.dll: the console's audio DSP command queue. No PC has one, so this gives the title a connection whose calls |
| 2 | // so these give the title connections whose calls succeed, a zeroed shared buffer, a result for each stream open and | 2 | // succeed and zeroed DSP status: nothing the title submits is processed. xapu.dll, the APU command queue, is in |
| 3 | // close, and zeroed DSP status: the audio the APU would render stays silent, and nothing the title submits is processed. | 3 | // xapu_queue.cpp. |
| 4 | // | 4 | // |
| 5 | // Read from the executable's call sites (counts in docs/runtime_imports.md), statically, never run: | 5 | // Read from the executable's call sites (counts in docs/runtime_imports.md), statically, never run: |
| 6 | // XApuConnect(block24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte | ||
| 7 | // output is read later as the base of a CPU-visible buffer: per-stream | ||
| 8 | // input at base + slot * 0x280 and output at base + 0x14000 + | ||
| 9 | // slot * 0x1E00. The first argument is a 24-byte global of the title | ||
| 10 | // that other title code also addresses; whether it is an input or an | ||
| 11 | // output is not known, so it is left untouched. | ||
| 12 | // XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type | ||
| 13 | // (1, 2 and 3 seen), the second a stream slot. | ||
| 14 | // XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues. | ||
| 15 | // XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative | ||
| 16 | // HRESULT skips that result. The loop reads a type at +0, a stream slot | ||
| 17 | // at +4 and a dword at +0x34. Its per-slot state machine takes a type 1 | ||
| 18 | // result as "opened" and returns the slot to the title's free list only | ||
| 19 | // on a type 2 result, after the title enqueued a type 2 command. | ||
| 20 | // XApuDisconnect(handle, 0x20) 1 site; the return value is never read. The constant second | ||
| 21 | // argument is not declared here: nothing reads it. | ||
| 22 | // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*) 1 site; success is a return of 0. The | 6 | // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*) 1 site; success is a return of 0. The |
| 23 | // buffer comes from the title's XMemAlloc and stays the title's. | 7 | // buffer comes from the title's XMemAlloc and stays the title's. |
| 24 | // XDspActivate(handle, desc*, out*, out*) 1 site; success is a return of 0, else the caller returns -1. The two | 8 | // XDspActivate(handle, desc*, out*, out*) 1 site; success is a return of 0, else the caller returns -1. The two |
| @@ -30,12 +14,6 @@ | |||
| 30 | // at +4 equals *id. | 14 | // at +4 equals *id. |
| 31 | // XDspDeactivate, XDspDisconnect 1 site each, tail calls: the caller returns what they return. | 15 | // XDspDeactivate, XDspDisconnect 1 site each, tail calls: the caller returns what they return. |
| 32 | // | 16 | // |
| 33 | // HYPOTHESIS: the shared buffer is 0x14000 + 128 * 0x1E00 bytes. 128 slots is what fits 0x14000 at the 0x280 input | ||
| 34 | // stride, and the DSP connect passes 0x80 as its stream limit; no call site shows a bound. The 16-byte output is | ||
| 35 | // written as {base, size}; only the base is measured. | ||
| 36 | // HYPOTHESIS: a type 1 (open) or type 2 (close) command produces one result of the same type for the same slot; the | ||
| 37 | // title's state machine fits that, the console is not measured. Without the close result the title's 256 stream ids | ||
| 38 | // run out. Only the two dwords are written; other command types are accepted with S_OK and produce no result. | ||
| 39 | // HYPOTHESIS: XDspActivate's outputs point at zeroed memory owned by the connection. XDspSubmitCommand leaves *id at | 17 | // HYPOTHESIS: XDspActivate's outputs point at zeroed memory owned by the connection. XDspSubmitCommand leaves *id at |
| 40 | // the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait. | 18 | // the title's 0, so the zeroed status reads as "command 0 done, no error" and the title does not wait. |
| 41 | #include <windows.h> | 19 | #include <windows.h> |
| @@ -43,7 +21,6 @@ | |||
| 43 | 21 | ||
| 44 | #include <cstdint> | 22 | #include <cstdint> |
| 45 | #include <cstring> | 23 | #include <cstring> |
| 46 | #include <deque> | ||
| 47 | #include <mutex> | 24 | #include <mutex> |
| 48 | #include <new> | 25 | #include <new> |
| 49 | #include <set> | 26 | #include <set> |
| @@ -54,30 +31,13 @@ | |||
| 54 | 31 | ||
| 55 | namespace { | 32 | namespace { |
| 56 | 33 | ||
| 57 | constexpr size_t kApuBufferSize = 0x14000 + 128 * 0x1E00; | ||
| 58 | |||
| 59 | // shortcut: results past this cap are dropped (each leaks one stream id); raise it if a title that never dequeues | ||
| 60 | // must still work. | ||
| 61 | constexpr size_t kMaxResults = 4096; | ||
| 62 | |||
| 63 | struct ApuResult { | ||
| 64 | uint32_t type; | ||
| 65 | uint32_t slot; | ||
| 66 | }; | ||
| 67 | |||
| 68 | struct ApuConnection { | ||
| 69 | void* buffer; | ||
| 70 | std::mutex mutex; | ||
| 71 | std::deque<ApuResult> results; | ||
| 72 | }; | ||
| 73 | |||
| 74 | struct DspConnection { | 34 | struct DspConnection { |
| 75 | uint8_t status[256]; | 35 | uint8_t status[256]; |
| 76 | uint8_t stream[256]; | 36 | uint8_t stream[256]; |
| 77 | }; | 37 | }; |
| 78 | 38 | ||
| 79 | // gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command type, with | 39 | // gta6rt --trace FILE: the first call of each function, with the caller, so the first boot shows what the title sends |
| 80 | // the caller, so the first boot shows what the title sends without a line per call. | 40 | // without a line per call. |
| 81 | void note(const char* api, uint64_t value, const void* caller) { | 41 | void note(const char* api, uint64_t value, const void* caller) { |
| 82 | if (!rt::startup_trace::enabled()) return; | 42 | if (!rt::startup_trace::enabled()) return; |
| 83 | static std::mutex mutex; | 43 | static std::mutex mutex; |
| @@ -92,71 +52,6 @@ void note(const char* api, uint64_t value, const void* caller) { | |||
| 92 | rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)))); | 52 | rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)))); |
| 93 | } | 53 | } |
| 94 | 54 | ||
| 95 | HRESULT __stdcall XApuConnect(void* block24, void* out16, void** handle) { | ||
| 96 | note("XApuConnect", 0, _ReturnAddress()); | ||
| 97 | if (!handle) return E_INVALIDARG; | ||
| 98 | *handle = nullptr; | ||
| 99 | void* buffer = VirtualAlloc(nullptr, kApuBufferSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed | ||
| 100 | if (!buffer) return E_OUTOFMEMORY; | ||
| 101 | auto* c = new (std::nothrow) ApuConnection; // a throwing new would unwind into the title | ||
| 102 | if (!c) { | ||
| 103 | VirtualFree(buffer, 0, MEM_RELEASE); | ||
| 104 | return E_OUTOFMEMORY; | ||
| 105 | } | ||
| 106 | c->buffer = buffer; | ||
| 107 | *handle = c; | ||
| 108 | (void)block24; | ||
| 109 | if (out16) { | ||
| 110 | const uint64_t info[2] = {reinterpret_cast<uint64_t>(buffer), kApuBufferSize}; | ||
| 111 | std::memcpy(out16, info, sizeof info); | ||
| 112 | } | ||
| 113 | return S_OK; | ||
| 114 | } | ||
| 115 | |||
| 116 | HRESULT __stdcall XApuDisconnect(void* handle) { | ||
| 117 | note("XApuDisconnect", 0, _ReturnAddress()); | ||
| 118 | auto* c = static_cast<ApuConnection*>(handle); | ||
| 119 | if (!c) return E_INVALIDARG; | ||
| 120 | VirtualFree(c->buffer, 0, MEM_RELEASE); | ||
| 121 | delete c; | ||
| 122 | return S_OK; | ||
| 123 | } | ||
| 124 | |||
| 125 | HRESULT __stdcall XApuEnqueueCommand(void* handle, const uint32_t* command, uint64_t flags) { | ||
| 126 | note("XApuEnqueueCommand", command ? command[0] : ~0ull, _ReturnAddress()); | ||
| 127 | (void)flags; | ||
| 128 | auto* c = static_cast<ApuConnection*>(handle); | ||
| 129 | if (!c || !command) return E_INVALIDARG; | ||
| 130 | if (command[0] == 1 || command[0] == 2) { | ||
| 131 | try { | ||
| 132 | const std::lock_guard lock(c->mutex); | ||
| 133 | if (c->results.size() < kMaxResults) c->results.push_back({command[0], command[1]}); | ||
| 134 | } catch (...) { // out of memory: the result is lost, nothing may unwind into the title | ||
| 135 | } | ||
| 136 | } | ||
| 137 | return S_OK; | ||
| 138 | } | ||
| 139 | |||
| 140 | uint32_t __stdcall XApuGetResultCount(void* handle, uint64_t flags) { | ||
| 141 | note("XApuGetResultCount", 0, _ReturnAddress()); | ||
| 142 | (void)flags; | ||
| 143 | auto* c = static_cast<ApuConnection*>(handle); | ||
| 144 | if (!c) return 0; | ||
| 145 | const std::lock_guard lock(c->mutex); | ||
| 146 | return static_cast<uint32_t>(c->results.size()); | ||
| 147 | } | ||
| 148 | |||
| 149 | HRESULT __stdcall XApuDequeueResult(void* handle, void* result) { | ||
| 150 | note("XApuDequeueResult", 0, _ReturnAddress()); | ||
| 151 | auto* c = static_cast<ApuConnection*>(handle); | ||
| 152 | if (!c || !result) return E_INVALIDARG; | ||
| 153 | const std::lock_guard lock(c->mutex); | ||
| 154 | if (c->results.empty()) return E_FAIL; | ||
| 155 | std::memcpy(result, &c->results.front(), sizeof(ApuResult)); // the rest stays as the caller zeroed it | ||
| 156 | c->results.pop_front(); | ||
| 157 | return S_OK; | ||
| 158 | } | ||
| 159 | |||
| 160 | HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams, | 55 | HRESULT __stdcall XDspConnectWithMaximumStreamLimit(void* buffer, uint32_t a, uint32_t b, uint32_t max_streams, |
| 161 | uint32_t flags, void** handle) { | 56 | uint32_t flags, void** handle) { |
| 162 | note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress()); | 57 | note("XDspConnectWithMaximumStreamLimit", max_streams, _ReturnAddress()); |
| @@ -199,14 +94,6 @@ HRESULT __stdcall XDspSubmitCommand(void*, void*, uint32_t*) { | |||
| 199 | 94 | ||
| 200 | } // namespace | 95 | } // namespace |
| 201 | 96 | ||
| 202 | SHIM_TABLE(xapu, | ||
| 203 | {"xapu.dll", "XApuConnect", reinterpret_cast<void*>(&XApuConnect)}, | ||
| 204 | {"xapu.dll", "XApuDequeueResult", reinterpret_cast<void*>(&XApuDequeueResult)}, | ||
| 205 | {"xapu.dll", "XApuDisconnect", reinterpret_cast<void*>(&XApuDisconnect)}, | ||
| 206 | {"xapu.dll", "XApuEnqueueCommand", reinterpret_cast<void*>(&XApuEnqueueCommand)}, | ||
| 207 | {"xapu.dll", "XApuGetResultCount", reinterpret_cast<void*>(&XApuGetResultCount)}, | ||
| 208 | ); | ||
| 209 | |||
| 210 | SHIM_TABLE(chad, | 97 | SHIM_TABLE(chad, |
| 211 | {"chad.dll", "XDspActivate", reinterpret_cast<void*>(&XDspActivate)}, | 98 | {"chad.dll", "XDspActivate", reinterpret_cast<void*>(&XDspActivate)}, |
| 212 | {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast<void*>(&XDspConnectWithMaximumStreamLimit)}, | 99 | {"chad.dll", "XDspConnectWithMaximumStreamLimit", reinterpret_cast<void*>(&XDspConnectWithMaximumStreamLimit)}, |
diff --git a/runtime/shims/xapu_queue.cpp b/runtime/shims/xapu_queue.cpp new file mode 100644 index 000000000..e754376ba --- /dev/null +++ b/runtime/shims/xapu_queue.cpp | |||
| @@ -0,0 +1,438 @@ | |||
| 1 | // xapu.dll: the console's audio processing unit (APU) command queue. No PC has one, so this keeps the queue the title | ||
| 2 | // talks to - one result per accepted command, in command order, with the console's error codes. With | ||
| 3 | // runtime/opus_decoder built (LEONIDA_HAVE_OPUS_DECODER) a process command decodes its Opus packet to PCM; without | ||
| 4 | // it the result carries the frame count its table-of-contents byte gives and silence in its output. | ||
| 5 | // | ||
| 6 | // Read from the executable's call sites (counts in docs/runtime_imports.md, shapes in docs/audio_hal_exe_calls.md), | ||
| 7 | // statically, never run: | ||
| 8 | // XApuConnect(input24*, out16*, handle*) 1 site; success is SUCCEEDED(hr). The first qword of the 16-byte | ||
| 9 | // output is read later as the base of a CPU-visible buffer: per-stream | ||
| 10 | // input at base + slot * 0x280 and output at base + 0x14000 + | ||
| 11 | // slot * 0x1E00. The first argument is a 24-byte global of the title | ||
| 12 | // that other title code also addresses. | ||
| 13 | // XApuEnqueueCommand(handle, cmd*, 0) 4 sites; the return value is never read. cmd's first dword is a type | ||
| 14 | // (1, 2 and 3 seen), the second a stream slot. | ||
| 15 | // XApuGetResultCount(handle, 0) 1 site; 0 skips the loop that dequeues. | ||
| 16 | // XApuDequeueResult(handle, out*) 1 site, called count times into a zeroed 0x50-byte local; a negative | ||
| 17 | // HRESULT skips that result. The loop reads a type at +0, a stream slot | ||
| 18 | // at +4 and a dword at +0x34. Its per-slot state machine takes a type 1 | ||
| 19 | // result as "opened" and returns the slot to the title's free list only | ||
| 20 | // on a type 2 result, after the title enqueued a type 2 command. | ||
| 21 | // XApuDisconnect(handle, 0x20) 1 site; the return value is never read. | ||
| 22 | // | ||
| 23 | // Where the layouts come from. The signatures, structure layouts, command kinds, option bits and error codes below | ||
| 24 | // are facts recorded by Marvisak/VIctory (GPL-3.0-or-later, crates/victory-hle/src/modules/apu.rs at commit ffe310e), | ||
| 25 | // whose runtime runs the retail executable through these calls; see docs/related_projects.md. Nothing of its code is | ||
| 26 | // copied; this file is written from those facts. They agree with every shape above: the first argument of | ||
| 27 | // XApuConnect is an input, the dword the title reads at +0x34 of a result is its output byte count, and a type 1 | ||
| 28 | // (activate) or type 2 (deactivate) command gives a result of the same kind for the same stream. | ||
| 29 | // HRESULT XApuConnect(const ConnectInput*, ConnectOutput*, Connection** out) | ||
| 30 | // HRESULT XApuDisconnect(Connection*, uint32_t) the second argument is not read | ||
| 31 | // HRESULT XApuEnqueueCommand(Connection*, const void* command, uint32_t* accepted_so_far) may be null | ||
| 32 | // HRESULT XApuDequeueResult(Connection*, Result* out) 0x8AC81001 while no result is ready | ||
| 33 | // uint32_t XApuGetResultCount(Connection*, uint32_t* dequeued_so_far) may be null; returns the results ready | ||
| 34 | // A connection is for one kind of processing; kind 1 is Opus decoding to 32-bit float PCM at 48 kHz, and any other | ||
| 35 | // kind is E_NOTIMPL. Every command starts with the 24-byte CommandId. A command refused at once (unknown kind, | ||
| 36 | // stream out of range, or the stream already holding `commands_per_stream` results not dequeued) gives no result; | ||
| 37 | // every other command gives one, with its error, if any, in the result. | ||
| 38 | // | ||
| 39 | // Without runtime/opus_decoder a process command's frame count comes from the Opus packet's table-of-contents byte | ||
| 40 | // (RFC 6716, section 3.1), clipped from first_frame, to frame_count and to what output_bytes holds, and that output | ||
| 41 | // range is written with zeros, so the title sees streams advance at the right rate and the audio stays silent. With | ||
| 42 | // the crate, fill() decodes the packet and writes its PCM instead. | ||
| 43 | #include <windows.h> | ||
| 44 | #include <intrin.h> | ||
| 45 | |||
| 46 | #include <cstddef> | ||
| 47 | #include <cstdint> | ||
| 48 | #include <cstdio> | ||
| 49 | #include <cstring> | ||
| 50 | #include <deque> | ||
| 51 | #include <mutex> | ||
| 52 | #include <new> | ||
| 53 | #include <set> | ||
| 54 | #include <string> | ||
| 55 | #include <vector> | ||
| 56 | |||
| 57 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 58 | #include "leonida_opus_decoder.h" | ||
| 59 | #endif | ||
| 60 | |||
| 61 | #include "shims.h" | ||
| 62 | #include "startup_trace.h" | ||
| 63 | |||
| 64 | namespace { | ||
| 65 | |||
| 66 | constexpr HRESULT kNotImpl = static_cast<HRESULT>(rt::shims::kENotImpl); | ||
| 67 | constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u); | ||
| 68 | constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u); | ||
| 69 | constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u); | ||
| 70 | constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u); | ||
| 71 | constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u); | ||
| 72 | constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u); | ||
| 73 | |||
| 74 | constexpr uint32_t kDecodeOpus = 1; // ConnectInput::processing | ||
| 75 | |||
| 76 | constexpr uint32_t kActivate = 1; // CommandId::kind | ||
| 77 | constexpr uint32_t kDeactivate = 2; | ||
| 78 | constexpr uint32_t kProcess = 3; | ||
| 79 | constexpr uint32_t kReset = 5; // 4 is notify; neither carries anything to do while nothing is decoded | ||
| 80 | |||
| 81 | constexpr uint32_t kSignalWhenDone = 0x1; // CommandId::options: set the result event when the result is ready | ||
| 82 | constexpr uint32_t kResultEvent = 0x8; // ConnectInput::options: create an auto-reset event and hand it out | ||
| 83 | constexpr uint32_t kDeinterleavedOutput = 0x4; // ConnectInput::options: split stereo into two planes | ||
| 84 | constexpr uint32_t kOpusSampleRate = 48000; | ||
| 85 | |||
| 86 | constexpr uint32_t kMaxStreams = 500; | ||
| 87 | constexpr uint32_t kMaxCommandsPerStream = 16; | ||
| 88 | constexpr uint32_t kMaxFrames = 5760; // 120 ms at 48 kHz, the longest Opus packet (RFC 6716, section 3.2.5) | ||
| 89 | |||
| 90 | #pragma pack(push, 1) | ||
| 91 | struct ConnectInput { | ||
| 92 | uint32_t processing; | ||
| 93 | uint32_t streams; | ||
| 94 | uint32_t commands_per_stream; | ||
| 95 | uint32_t memory_bytes; | ||
| 96 | uint32_t frames_per_output; // 0 for decoding | ||
| 97 | uint32_t options; | ||
| 98 | }; | ||
| 99 | struct ConnectOutput { | ||
| 100 | void* memory; // zeroed, for the title's packets and output | ||
| 101 | HANDLE result_event; | ||
| 102 | }; | ||
| 103 | struct CommandId { | ||
| 104 | uint32_t kind; | ||
| 105 | uint32_t stream; | ||
| 106 | uint32_t sequence; | ||
| 107 | uint32_t options; | ||
| 108 | uint64_t context; | ||
| 109 | }; | ||
| 110 | struct ActivateCommand { | ||
| 111 | CommandId id; | ||
| 112 | uint32_t channels; // 1 or 2 | ||
| 113 | uint32_t init_bytes; | ||
| 114 | const void* init; | ||
| 115 | float start_pitch; | ||
| 116 | uint32_t processing_bytes; | ||
| 117 | void* processing; | ||
| 118 | }; | ||
| 119 | struct ProcessCommand { | ||
| 120 | CommandId id; | ||
| 121 | float pitch_ramp; | ||
| 122 | float target_pitch; | ||
| 123 | uint32_t first_frame; | ||
| 124 | uint32_t frame_count; | ||
| 125 | uint32_t input_bytes; | ||
| 126 | const uint8_t* input; | ||
| 127 | uint32_t output_bytes; | ||
| 128 | uint8_t* output; | ||
| 129 | }; | ||
| 130 | struct Result { | ||
| 131 | CommandId id; | ||
| 132 | uint32_t state; | ||
| 133 | uint64_t state_data; | ||
| 134 | uint64_t usec; | ||
| 135 | HRESULT error; | ||
| 136 | uint32_t frames; | ||
| 137 | uint32_t output_bytes; | ||
| 138 | uint8_t* output; | ||
| 139 | float pitch; | ||
| 140 | uint32_t input_bytes; | ||
| 141 | const uint8_t* input; | ||
| 142 | }; | ||
| 143 | #pragma pack(pop) | ||
| 144 | static_assert(sizeof(ConnectInput) == 24, "six dwords"); | ||
| 145 | static_assert(sizeof(ConnectOutput) == 16, "memory and event"); | ||
| 146 | static_assert(sizeof(CommandId) == 24, "kind, stream, sequence, options, context"); | ||
| 147 | static_assert(sizeof(ActivateCommand) == 56, "CommandId and the activate fields"); | ||
| 148 | static_assert(sizeof(ProcessCommand) == 64, "CommandId and the process fields"); | ||
| 149 | static_assert(sizeof(Result) == 0x50, "the result the title dequeues"); | ||
| 150 | static_assert(offsetof(Result, state) == 0x18 && offsetof(Result, error) == 0x2C && | ||
| 151 | offsetof(Result, output_bytes) == 0x34 && offsetof(Result, pitch) == 0x40 && | ||
| 152 | offsetof(Result, input) == 0x48, | ||
| 153 | "the offsets the title and the layout agree on"); | ||
| 154 | |||
| 155 | struct Stream { | ||
| 156 | bool active = false; | ||
| 157 | uint32_t channels = 0; | ||
| 158 | uint32_t pending = 0; // results queued and not dequeued | ||
| 159 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 160 | LeonidaOpusDecoder* decoder = nullptr; | ||
| 161 | #endif | ||
| 162 | }; | ||
| 163 | |||
| 164 | struct Connection { | ||
| 165 | void* memory = nullptr; | ||
| 166 | HANDLE event = nullptr; | ||
| 167 | uint32_t commands_per_stream = 0; | ||
| 168 | bool deinterleaved = false; | ||
| 169 | std::mutex mutex; | ||
| 170 | std::vector<Stream> streams; | ||
| 171 | std::deque<Result> results; | ||
| 172 | uint32_t accepted = 0; | ||
| 173 | uint32_t dequeued = 0; | ||
| 174 | }; | ||
| 175 | |||
| 176 | // gta6rt --trace FILE: the first call of each function and the first XApuEnqueueCommand of each command kind, with | ||
| 177 | // the caller, so the first boot shows what the title sends without a line per call. | ||
| 178 | void note(const char* api, uint64_t value, const void* caller) { | ||
| 179 | if (!rt::startup_trace::enabled()) return; | ||
| 180 | static std::mutex mutex; | ||
| 181 | static std::set<std::pair<std::string, uint64_t>> seen; | ||
| 182 | { | ||
| 183 | const std::lock_guard lock(mutex); | ||
| 184 | if (!seen.insert({api, value}).second) return; | ||
| 185 | } | ||
| 186 | rt::startup_trace::event( | ||
| 187 | "audio_queue", std::string("\"api\":") + rt::startup_trace::quote(api) + | ||
| 188 | ",\"value\":" + rt::startup_trace::quote(rt::startup_trace::hex(value)) + ",\"caller\":" + | ||
| 189 | rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)))); | ||
| 190 | } | ||
| 191 | |||
| 192 | // Samples per channel at 48 kHz in one Opus packet, from its table-of-contents byte and frame count code (RFC 6716, | ||
| 193 | // section 3.1); 0 for a packet that is not valid. The no-decoder path counts frames this way. | ||
| 194 | uint32_t opus_packet_frames(const uint8_t* packet, uint32_t bytes) { | ||
| 195 | if (!packet || bytes == 0) return 0; | ||
| 196 | static constexpr uint32_t kSilk[4] = {480, 960, 1920, 2880}; // 10, 20, 40, 60 ms | ||
| 197 | static constexpr uint32_t kHybrid[2] = {480, 960}; // 10, 20 ms | ||
| 198 | static constexpr uint32_t kCelt[4] = {120, 240, 480, 960}; // 2.5, 5, 10, 20 ms | ||
| 199 | const uint32_t config = packet[0] >> 3; | ||
| 200 | const uint32_t per_frame = config < 12 ? kSilk[config & 3] : config < 16 ? kHybrid[config & 1] : kCelt[config & 3]; | ||
| 201 | uint32_t count = 0; | ||
| 202 | switch (packet[0] & 3) { | ||
| 203 | case 0: count = 1; break; | ||
| 204 | case 1: | ||
| 205 | case 2: count = 2; break; | ||
| 206 | default: | ||
| 207 | if (bytes < 2) return 0; | ||
| 208 | count = packet[1] & 0x3F; | ||
| 209 | break; | ||
| 210 | } | ||
| 211 | if (count == 0 || count * per_frame > kMaxFrames) return 0; | ||
| 212 | return count * per_frame; | ||
| 213 | } | ||
| 214 | |||
| 215 | // Fills a process command's result: the packet's PCM when runtime/opus_decoder is built, silence (with the frame | ||
| 216 | // count from the table-of-contents byte) otherwise. | ||
| 217 | void fill(Connection& connection, Stream& stream, const ProcessCommand& c, Result& r) { | ||
| 218 | r.input = c.input; | ||
| 219 | r.input_bytes = c.input_bytes; | ||
| 220 | r.output = c.output; | ||
| 221 | if (!c.input || !c.output || c.input_bytes == 0) { | ||
| 222 | r.error = E_INVALIDARG; | ||
| 223 | return; | ||
| 224 | } | ||
| 225 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 226 | if (stream.decoder) { | ||
| 227 | const uint32_t channels = leonida_opus_decoder_channels(stream.decoder); | ||
| 228 | if (channels == 0) { | ||
| 229 | r.error = kInvalidStream; | ||
| 230 | return; | ||
| 231 | } | ||
| 232 | std::vector<float> pcm; | ||
| 233 | try { | ||
| 234 | pcm.resize(size_t(kMaxFrames) * channels); | ||
| 235 | } catch (...) { | ||
| 236 | r.error = E_OUTOFMEMORY; | ||
| 237 | return; | ||
| 238 | } | ||
| 239 | uint32_t decoded = 0; | ||
| 240 | if (leonida_opus_decode_packet(stream.decoder, c.input, c.input_bytes, pcm.data(), kMaxFrames, &decoded) != | ||
| 241 | LEONIDA_OPUS_OK) { | ||
| 242 | r.error = kBadPacket; | ||
| 243 | return; | ||
| 244 | } | ||
| 245 | const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded; | ||
| 246 | uint32_t frames = decoded - first; | ||
| 247 | if (frames > c.frame_count) frames = c.frame_count; | ||
| 248 | const uint32_t room = c.output_bytes / (4 * channels); | ||
| 249 | if (frames > room) frames = room; | ||
| 250 | const uint32_t bytes = frames * channels * 4; | ||
| 251 | if (connection.deinterleaved && channels == 2) { | ||
| 252 | float* out = reinterpret_cast<float*>(c.output); | ||
| 253 | for (uint32_t i = 0; i < frames; ++i) { | ||
| 254 | out[i] = pcm[(first + i) * 2]; | ||
| 255 | out[frames + i] = pcm[(first + i) * 2 + 1]; | ||
| 256 | } | ||
| 257 | } else if (bytes != 0) { | ||
| 258 | std::memcpy(c.output, pcm.data() + first * channels, bytes); | ||
| 259 | } | ||
| 260 | r.frames = frames; | ||
| 261 | r.output_bytes = bytes; | ||
| 262 | return; | ||
| 263 | } | ||
| 264 | #endif | ||
| 265 | const uint32_t decoded = opus_packet_frames(c.input, c.input_bytes); | ||
| 266 | if (decoded == 0) { | ||
| 267 | r.error = kBadPacket; | ||
| 268 | return; | ||
| 269 | } | ||
| 270 | const uint32_t first = c.first_frame < decoded ? c.first_frame : decoded; | ||
| 271 | uint32_t frames = decoded - first; | ||
| 272 | if (frames > c.frame_count) frames = c.frame_count; | ||
| 273 | const uint32_t room = c.output_bytes / (4 * stream.channels); | ||
| 274 | if (frames > room) frames = room; | ||
| 275 | const uint32_t bytes = frames * stream.channels * 4; | ||
| 276 | std::memset(c.output, 0, bytes); // interleaved or not, silence is zeros | ||
| 277 | r.frames = frames; | ||
| 278 | r.output_bytes = bytes; | ||
| 279 | } | ||
| 280 | |||
| 281 | HRESULT __stdcall XApuConnect(const ConnectInput* input, ConnectOutput* output, Connection** out) { | ||
| 282 | note("XApuConnect", input ? input->processing : ~0ull, _ReturnAddress()); | ||
| 283 | if (!input || !output || !out) return E_INVALIDARG; | ||
| 284 | *out = nullptr; | ||
| 285 | ConnectInput in; | ||
| 286 | std::memcpy(&in, input, sizeof(in)); | ||
| 287 | if (in.streams == 0 || in.streams > kMaxStreams || in.commands_per_stream == 0 || | ||
| 288 | in.commands_per_stream > kMaxCommandsPerStream || in.memory_bytes == 0) | ||
| 289 | return E_INVALIDARG; | ||
| 290 | if (in.processing != kDecodeOpus) { | ||
| 291 | std::fprintf(stderr, "[rt] xapu: XApuConnect for processing kind %u: only Opus decoding (1); E_NOTIMPL\n", | ||
| 292 | in.processing); | ||
| 293 | return kNotImpl; | ||
| 294 | } | ||
| 295 | if (in.frames_per_output != 0) return E_INVALIDARG; | ||
| 296 | |||
| 297 | auto* c = new (std::nothrow) Connection; // a throwing new would unwind into the title | ||
| 298 | if (!c) return E_OUTOFMEMORY; | ||
| 299 | try { | ||
| 300 | c->streams.resize(in.streams); | ||
| 301 | } catch (...) { | ||
| 302 | delete c; | ||
| 303 | return E_OUTOFMEMORY; | ||
| 304 | } | ||
| 305 | c->memory = VirtualAlloc(nullptr, in.memory_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); // zeroed | ||
| 306 | if (!c->memory) { | ||
| 307 | delete c; | ||
| 308 | return E_OUTOFMEMORY; | ||
| 309 | } | ||
| 310 | if (in.options & kResultEvent) { | ||
| 311 | c->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); // auto-reset | ||
| 312 | if (!c->event) { | ||
| 313 | const HRESULT hr = HRESULT_FROM_WIN32(GetLastError()); | ||
| 314 | VirtualFree(c->memory, 0, MEM_RELEASE); | ||
| 315 | delete c; | ||
| 316 | return hr; | ||
| 317 | } | ||
| 318 | } | ||
| 319 | c->commands_per_stream = in.commands_per_stream; | ||
| 320 | c->deinterleaved = (in.options & kDeinterleavedOutput) != 0; | ||
| 321 | const ConnectOutput o{c->memory, c->event}; | ||
| 322 | std::memcpy(output, &o, sizeof(o)); | ||
| 323 | *out = c; | ||
| 324 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 325 | std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets decoded\n", in.streams); | ||
| 326 | #else | ||
| 327 | std::fprintf(stderr, "[rt] xapu: connected for Opus decoding, %u streams; packets counted, not decoded\n", | ||
| 328 | in.streams); | ||
| 329 | #endif | ||
| 330 | return S_OK; | ||
| 331 | } | ||
| 332 | |||
| 333 | HRESULT __stdcall XApuDisconnect(Connection* c, uint32_t /*0x20 at the measured site*/) { | ||
| 334 | note("XApuDisconnect", 0, _ReturnAddress()); | ||
| 335 | if (!c) return E_INVALIDARG; | ||
| 336 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 337 | for (Stream& s : c->streams) | ||
| 338 | if (s.decoder) leonida_opus_decoder_destroy(s.decoder); | ||
| 339 | #endif | ||
| 340 | if (c->event) CloseHandle(c->event); | ||
| 341 | VirtualFree(c->memory, 0, MEM_RELEASE); | ||
| 342 | delete c; | ||
| 343 | return S_OK; | ||
| 344 | } | ||
| 345 | |||
| 346 | HRESULT __stdcall XApuEnqueueCommand(Connection* c, const void* command, uint32_t* accepted_so_far) { | ||
| 347 | if (!c || !command) return E_INVALIDARG; | ||
| 348 | CommandId id; | ||
| 349 | std::memcpy(&id, command, sizeof(id)); | ||
| 350 | note("XApuEnqueueCommand", id.kind, _ReturnAddress()); | ||
| 351 | if (id.kind < kActivate || id.kind > kReset) return kInvalidCommand; | ||
| 352 | |||
| 353 | const std::lock_guard lock(c->mutex); | ||
| 354 | if (id.stream >= c->streams.size()) return kInvalidStream; | ||
| 355 | Stream& stream = c->streams[id.stream]; | ||
| 356 | if (stream.pending >= c->commands_per_stream) return kQueueFull; | ||
| 357 | |||
| 358 | Result r{}; | ||
| 359 | r.id = id; | ||
| 360 | r.pitch = 1.0f; | ||
| 361 | if (id.kind == kActivate) { | ||
| 362 | ActivateCommand a; | ||
| 363 | std::memcpy(&a, command, sizeof(a)); | ||
| 364 | if (stream.active) { | ||
| 365 | r.error = kAlreadyActive; | ||
| 366 | } else if (a.channels < 1 || a.channels > 2) { | ||
| 367 | r.error = E_INVALIDARG; | ||
| 368 | } else { | ||
| 369 | stream.active = true; | ||
| 370 | stream.channels = a.channels; | ||
| 371 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 372 | if (leonida_opus_decoder_create(kOpusSampleRate, a.channels, &stream.decoder) != LEONIDA_OPUS_OK) { | ||
| 373 | stream.active = false; | ||
| 374 | stream.channels = 0; | ||
| 375 | r.error = E_INVALIDARG; | ||
| 376 | } | ||
| 377 | #endif | ||
| 378 | } | ||
| 379 | } else if (id.kind == kDeactivate) { | ||
| 380 | stream.active = false; | ||
| 381 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 382 | if (stream.decoder) { | ||
| 383 | leonida_opus_decoder_destroy(stream.decoder); | ||
| 384 | stream.decoder = nullptr; | ||
| 385 | } | ||
| 386 | #endif | ||
| 387 | } else if (id.kind == kReset) { | ||
| 388 | #if defined(LEONIDA_HAVE_OPUS_DECODER) | ||
| 389 | if (stream.decoder) leonida_opus_decoder_reset(stream.decoder); | ||
| 390 | #endif | ||
| 391 | } else if (id.kind == kProcess) { | ||
| 392 | ProcessCommand p; | ||
| 393 | std::memcpy(&p, command, sizeof(p)); | ||
| 394 | if (!stream.active) r.error = kInvalidStream; | ||
| 395 | else fill(*c, stream, p, r); | ||
| 396 | } | ||
| 397 | try { | ||
| 398 | c->results.push_back(r); | ||
| 399 | } catch (...) { // out of memory: refuse the command, nothing may unwind into the title | ||
| 400 | return E_OUTOFMEMORY; | ||
| 401 | } | ||
| 402 | ++stream.pending; | ||
| 403 | ++c->accepted; | ||
| 404 | if (accepted_so_far) *accepted_so_far = c->accepted; | ||
| 405 | if ((id.options & kSignalWhenDone) && c->event) SetEvent(c->event); | ||
| 406 | return S_OK; | ||
| 407 | } | ||
| 408 | |||
| 409 | HRESULT __stdcall XApuDequeueResult(Connection* c, Result* out) { | ||
| 410 | note("XApuDequeueResult", 0, _ReturnAddress()); | ||
| 411 | if (!c || !out) return E_INVALIDARG; | ||
| 412 | const std::lock_guard lock(c->mutex); | ||
| 413 | if (c->results.empty()) return kNoResult; | ||
| 414 | const Result r = c->results.front(); | ||
| 415 | c->results.pop_front(); | ||
| 416 | --c->streams[r.id.stream].pending; | ||
| 417 | ++c->dequeued; | ||
| 418 | std::memcpy(out, &r, sizeof(r)); | ||
| 419 | return S_OK; | ||
| 420 | } | ||
| 421 | |||
| 422 | uint32_t __stdcall XApuGetResultCount(Connection* c, uint32_t* dequeued_so_far) { | ||
| 423 | note("XApuGetResultCount", 0, _ReturnAddress()); | ||
| 424 | if (!c) return 0; | ||
| 425 | const std::lock_guard lock(c->mutex); | ||
| 426 | if (dequeued_so_far) *dequeued_so_far = c->dequeued; | ||
| 427 | return static_cast<uint32_t>(c->results.size()); | ||
| 428 | } | ||
| 429 | |||
| 430 | } // namespace | ||
| 431 | |||
| 432 | SHIM_TABLE(xapu, | ||
| 433 | {"xapu.dll", "XApuConnect", reinterpret_cast<void*>(&XApuConnect)}, | ||
| 434 | {"xapu.dll", "XApuDequeueResult", reinterpret_cast<void*>(&XApuDequeueResult)}, | ||
| 435 | {"xapu.dll", "XApuDisconnect", reinterpret_cast<void*>(&XApuDisconnect)}, | ||
| 436 | {"xapu.dll", "XApuEnqueueCommand", reinterpret_cast<void*>(&XApuEnqueueCommand)}, | ||
| 437 | {"xapu.dll", "XApuGetResultCount", reinterpret_cast<void*>(&XApuGetResultCount)}, | ||
| 438 | ); | ||
diff --git a/runtime/test/xapu_chad_test.cpp b/runtime/test/xapu_chad_test.cpp index dffa74404..7e667492c 100644 --- a/runtime/test/xapu_chad_test.cpp +++ b/runtime/test/xapu_chad_test.cpp | |||
| @@ -1,7 +1,11 @@ | |||
| 1 | // Checks the registered xapu.dll and chad.dll shims in the call shapes the executable uses (runtime/shims/xapu_chad.cpp): | 1 | // Checks the registered xapu.dll and chad.dll shims (runtime/shims/xapu_queue.cpp and runtime/shims/xapu_chad.cpp) |
| 2 | // the connections succeed, the APU's shared buffer is zeroed and writable at the offsets the title reaches, commands | 2 | // in the call shapes the executable uses and against the layouts xapu_queue.cpp documents. |
| 3 | // are accepted, an open and a close each give one result and nothing else does, XDspActivate hands out zeroed status | 3 | // |
| 4 | // and stream memory, and both disconnect. | 4 | // xapu.dll: the connection's limits and its zeroed memory, writable at the offsets the title reaches; one result per |
| 5 | // accepted command, in command order, with its id echoed; the per-stream queue limit; the error codes, returned or in | ||
| 6 | // the result; a process command's frame count taken from the Opus packet's table-of-contents byte (RFC 6716, section | ||
| 7 | // 3.1) and clipped, with silence written; and the result event. The packets are hand-made TOC bytes, not audio. | ||
| 8 | // chad.dll: XDspActivate hands out zeroed status and stream memory, and both disconnect. | ||
| 5 | #include <windows.h> | 9 | #include <windows.h> |
| 6 | 10 | ||
| 7 | #include <cstdint> | 11 | #include <cstdint> |
| @@ -12,10 +16,10 @@ | |||
| 12 | 16 | ||
| 13 | namespace { | 17 | namespace { |
| 14 | 18 | ||
| 15 | using XApuConnectFn = HRESULT(__stdcall*)(void*, void*, void**); | 19 | using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**); |
| 16 | using XApuDisconnectFn = HRESULT(__stdcall*)(void*); | 20 | using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t); |
| 17 | using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const uint32_t*, uint64_t); | 21 | using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*); |
| 18 | using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint64_t); | 22 | using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*); |
| 19 | using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); | 23 | using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); |
| 20 | using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); | 24 | using XDspConnectFn = HRESULT(__stdcall*)(void*, uint32_t, uint32_t, uint32_t, uint32_t, void**); |
| 21 | using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**); | 25 | using XDspActivateFn = HRESULT(__stdcall*)(void*, const void*, void**, void**); |
| @@ -23,6 +27,55 @@ using XDspDeactivateFn = HRESULT(__stdcall*)(void*, uint64_t, uint64_t, uint64_t | |||
| 23 | using XDspDisconnectFn = HRESULT(__stdcall*)(void*); | 27 | using XDspDisconnectFn = HRESULT(__stdcall*)(void*); |
| 24 | using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*); | 28 | using XDspSubmitCommandFn = HRESULT(__stdcall*)(void*, void*, uint32_t*); |
| 25 | 29 | ||
| 30 | constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u); | ||
| 31 | constexpr HRESULT kNoResult = static_cast<HRESULT>(0x8AC81001u); | ||
| 32 | constexpr HRESULT kInvalidCommand = static_cast<HRESULT>(0x8AC81002u); | ||
| 33 | constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u); | ||
| 34 | constexpr HRESULT kAlreadyActive = static_cast<HRESULT>(0x8AC81005u); | ||
| 35 | constexpr HRESULT kBadPacket = static_cast<HRESULT>(0x8AC81008u); | ||
| 36 | |||
| 37 | #pragma pack(push, 1) | ||
| 38 | struct ConnectInput { | ||
| 39 | uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options; | ||
| 40 | }; | ||
| 41 | struct ConnectOutput { | ||
| 42 | void* memory; | ||
| 43 | HANDLE result_event; | ||
| 44 | }; | ||
| 45 | struct CommandId { | ||
| 46 | uint32_t kind, stream, sequence, options; | ||
| 47 | uint64_t context; | ||
| 48 | }; | ||
| 49 | struct ActivateCommand { | ||
| 50 | CommandId id; | ||
| 51 | uint32_t channels, init_bytes; | ||
| 52 | const void* init; | ||
| 53 | float start_pitch; | ||
| 54 | uint32_t processing_bytes; | ||
| 55 | void* processing; | ||
| 56 | }; | ||
| 57 | struct ProcessCommand { | ||
| 58 | CommandId id; | ||
| 59 | float pitch_ramp, target_pitch; | ||
| 60 | uint32_t first_frame, frame_count, input_bytes; | ||
| 61 | const uint8_t* input; | ||
| 62 | uint32_t output_bytes; | ||
| 63 | uint8_t* output; | ||
| 64 | }; | ||
| 65 | struct Result { | ||
| 66 | CommandId id; | ||
| 67 | uint32_t state; | ||
| 68 | uint64_t state_data, usec; | ||
| 69 | HRESULT error; | ||
| 70 | uint32_t frames, output_bytes; | ||
| 71 | uint8_t* output; | ||
| 72 | float pitch; | ||
| 73 | uint32_t input_bytes; | ||
| 74 | const uint8_t* input; | ||
| 75 | }; | ||
| 76 | #pragma pack(pop) | ||
| 77 | static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts"); | ||
| 78 | |||
| 26 | int g_checks = 0; | 79 | int g_checks = 0; |
| 27 | int g_failures = 0; | 80 | int g_failures = 0; |
| 28 | 81 | ||
| @@ -39,6 +92,8 @@ T get(const char* dll, const char* name) { | |||
| 39 | return reinterpret_cast<T>(fn); | 92 | return reinterpret_cast<T>(fn); |
| 40 | } | 93 | } |
| 41 | 94 | ||
| 95 | CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; } | ||
| 96 | |||
| 42 | } // namespace | 97 | } // namespace |
| 43 | 98 | ||
| 44 | int main() { | 99 | int main() { |
| @@ -56,39 +111,165 @@ int main() { | |||
| 56 | check(rt::shims::owns_dll("xapu.dll") && rt::shims::owns_dll("chad.dll"), "the shims own xapu.dll and chad.dll"); | 111 | check(rt::shims::owns_dll("xapu.dll") && rt::shims::owns_dll("chad.dll"), "the shims own xapu.dll and chad.dll"); |
| 57 | if (g_failures) return 1; | 112 | if (g_failures) return 1; |
| 58 | 113 | ||
| 59 | // XApuConnect(block24*, out16*, handle*), success read as SUCCEEDED. | 114 | // XApuConnect(const ConnectInput*, ConnectOutput*, handle*): the first argument is read, never written. |
| 60 | uint8_t out24[24]; | 115 | ConnectOutput out{}; |
| 61 | uint64_t out16[2] = {}; | ||
| 62 | std::memset(out24, 0xcc, sizeof out24); | ||
| 63 | void* apu = nullptr; | 116 | void* apu = nullptr; |
| 64 | check(SUCCEEDED(connect(out24, out16, &apu)) && apu, "XApuConnect succeeds with a handle"); | 117 | ConnectInput bad{1, 0, 2, 0x10000, 0, 0}; |
| 65 | check(out24[0] == 0xcc && out24[23] == 0xcc, "XApuConnect leaves the title's 24-byte block alone"); | 118 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "zero streams is E_INVALIDARG"); |
| 66 | auto* base = reinterpret_cast<uint8_t*>(out16[0]); | 119 | bad = {1, 501, 2, 0x10000, 0, 0}; |
| 67 | check(base != nullptr && out16[1] >= 0x14000 + 128 * 0x1E00, "XApuConnect returns the shared buffer and its size"); | 120 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 500 streams is E_INVALIDARG"); |
| 68 | if (base) { | 121 | bad = {1, 4, 17, 0x10000, 0, 0}; |
| 69 | const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output | 122 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "more than 16 commands per stream is E_INVALIDARG"); |
| 70 | check(base[0] == 0 && base[last_output] == 0, "the shared buffer is zeroed"); | 123 | bad = {1, 4, 2, 0, 0, 0}; |
| 71 | base[127 * 0x280] = 1; | 124 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "no memory is E_INVALIDARG"); |
| 72 | base[last_output] = 1; | 125 | bad = {1, 4, 2, 0x10000, 256, 0}; |
| 73 | check(base[127 * 0x280] == 1 && base[last_output] == 1, "the shared buffer is writable at slot 127"); | 126 | check(connect(&bad, &out, &apu) == E_INVALIDARG, "frames per output for decoding is E_INVALIDARG"); |
| 74 | } | 127 | bad = {2, 4, 2, 0x10000, 0, 0}; |
| 75 | check(connect(out24, out16, nullptr) == E_INVALIDARG, "XApuConnect without a handle pointer fails"); | 128 | check(connect(&bad, &out, &apu) == static_cast<HRESULT>(rt::shims::kENotImpl), |
| 129 | "a processing kind other than Opus decoding is E_NOTIMPL"); | ||
| 130 | check(apu == nullptr, "a failed XApuConnect hands out no handle"); | ||
| 131 | |||
| 132 | // The memory the title addresses: input at base + slot * 0x280, output at base + 0x14000 + slot * 0x1E00. | ||
| 133 | constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00; | ||
| 134 | const ConnectInput in{1, 128, 2, kMemory, 0, 8}; | ||
| 135 | const ConnectInput in_copy = in; | ||
| 136 | check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding, 128 streams, 2 commands each"); | ||
| 137 | check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone"); | ||
| 138 | check(out.memory != nullptr && out.result_event != nullptr, "it hands out memory and a result event"); | ||
| 139 | if (!apu || !out.memory) return 1; | ||
| 140 | auto* base = static_cast<uint8_t*>(out.memory); | ||
| 141 | const size_t last_output = 0x14000 + 127 * 0x1E00 + 0x1E00 - 1; // the end of slot 127's output | ||
| 142 | check(base[0] == 0 && base[last_output] == 0, "the memory is zeroed"); | ||
| 143 | base[127 * 0x280] = 1; | ||
| 144 | base[last_output] = 1; | ||
| 145 | check(base[127 * 0x280] == 1 && base[last_output] == 1, "the memory is writable at slot 127"); | ||
| 146 | base[127 * 0x280] = 0; | ||
| 147 | base[last_output] = 0; | ||
| 148 | |||
| 149 | Result r{}; | ||
| 150 | check(dequeue(apu, &r) == kNoResult, "XApuDequeueResult with nothing queued is 0x8AC81001"); | ||
| 151 | uint32_t dequeued = 99; | ||
| 152 | check(count(apu, &dequeued) == 0 && dequeued == 0, "XApuGetResultCount: nothing ready, none dequeued"); | ||
| 76 | 153 | ||
| 77 | // Command types 1, 2 and 3 as the title builds them; the third argument is 0 at every site. | 154 | // Activate stream 3 (stereo) and process one packet; the title's sites pass a null third argument. |
| 78 | for (uint32_t type = 1; type <= 3; ++type) { | 155 | const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr}; |
| 79 | uint32_t command[16] = {type, 5}; | 156 | check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 with a null count pointer"); |
| 80 | check(enqueue(apu, command, 0) == S_OK, "XApuEnqueueCommand accepts a command"); | 157 | check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "a command not asking for it leaves the event"); |
| 158 | uint8_t* const packet = base + 3 * 0x280; | ||
| 159 | uint8_t* const pcm = base + 0x14000 + 3 * 0x1E00; | ||
| 160 | packet[0] = (31 << 3) | 0; // one 20 ms CELT frame (config 31, code 0): 960 frames per channel | ||
| 161 | std::memset(pcm, 0x55, 0x1E00 + 16); // the slot and the start of the next, to see nothing past it is written | ||
| 162 | ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, 40, packet, 960 * 8, pcm}; | ||
| 163 | uint32_t total = 0; | ||
| 164 | check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted"); | ||
| 165 | check(WaitForSingleObject(out.result_event, 0) == WAIT_OBJECT_0, "a command asking for it signals the event"); | ||
| 166 | check(WaitForSingleObject(out.result_event, 0) == WAIT_TIMEOUT, "the event resets itself"); | ||
| 167 | check(enqueue(apu, &process, &total) == kQueueFull && total == 2, | ||
| 168 | "a third command on a stream of two is 0x8AC81000 and not counted"); | ||
| 169 | check(count(apu, nullptr) == 2, "two results ready, with a null dequeued pointer"); | ||
| 170 | |||
| 171 | check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.id.sequence == 7 && | ||
| 172 | r.id.context == 0x1234 && r.error == S_OK && r.pitch == 1.0f, | ||
| 173 | "results come in command order: the activate first, its id echoed"); | ||
| 174 | check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows"); | ||
| 175 | uint32_t dword34 = 0; | ||
| 176 | std::memcpy(&dword34, reinterpret_cast<const uint8_t*>(&r) + 0x34, 4); | ||
| 177 | check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == packet && r.input_bytes == 40, | ||
| 178 | "960 stereo float frames, the byte count at +0x34, the buffers echoed"); | ||
| 179 | bool silent = true; | ||
| 180 | for (int i = 0; i < 960 * 8; ++i) silent = silent && pcm[i] == 0; | ||
| 181 | check(silent && pcm[960 * 8] == 0x55, "the output range is silence, and nothing past it is written"); | ||
| 182 | check(count(apu, &dequeued) == 0 && dequeued == 2, "nothing ready, two dequeued"); | ||
| 183 | |||
| 184 | // The TOC byte's frame size and count (RFC 6716, section 3.1), one stereo packet each. | ||
| 185 | struct Toc { | ||
| 186 | uint8_t toc, count; | ||
| 187 | uint32_t frames; | ||
| 188 | const char* what; | ||
| 189 | } const tocs[] = { | ||
| 190 | {(0 << 3) | 0, 0, 480, "SILK 10 ms, code 0: 480 frames"}, | ||
| 191 | {(3 << 3) | 1, 0, 5760, "SILK 60 ms, code 1 (two frames): 5760 frames"}, | ||
| 192 | {(13 << 3) | 2, 0, 1920, "hybrid 20 ms, code 2 (two frames): 1920 frames"}, | ||
| 193 | {(16 << 3) | 3, 5, 600, "CELT 2.5 ms, code 3 with five frames: 600 frames"}, | ||
| 194 | }; | ||
| 195 | for (const Toc& t : tocs) { | ||
| 196 | packet[0] = t.toc; | ||
| 197 | packet[1] = t.count; | ||
| 198 | process = {id(3, 3), 0.0f, 1.0f, 0, 6000, 40, packet, 0x1E00 * 4, pcm}; | ||
| 199 | r = {}; | ||
| 200 | check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK && | ||
| 201 | r.frames == (t.frames < 0x1E00 * 4 / 8 ? t.frames : 0x1E00 * 4 / 8), | ||
| 202 | t.what); | ||
| 81 | } | 203 | } |
| 82 | check(count(apu, 0) == 2, "the open and the close each queued a result, the type 3 command none"); | 204 | |
| 83 | for (uint32_t type = 1; type <= 2; ++type) { | 205 | // first_frame and frame_count clip like a decode: three 20 ms frames (code 3, count 3) = 2880, from frame 2000. |
| 84 | uint32_t queued[0x50 / 4] = {}; | 206 | packet[0] = (31 << 3) | 3; |
| 85 | check(dequeue(apu, queued) == S_OK && queued[0] == type && queued[1] == 5 && queued[2] == 0 && queued[13] == 0, | 207 | packet[1] = 3; |
| 86 | "XApuDequeueResult returns the type and slot and leaves the rest zeroed"); | 208 | process = {id(3, 3), 0.0f, 1.0f, 2000, 4000, 40, packet, 0x1E00, pcm}; |
| 209 | enqueue(apu, &process, nullptr); | ||
| 210 | dequeue(apu, &r); | ||
| 211 | check(r.error == S_OK && r.frames == 880 && r.output_bytes == 880 * 8, "frames from first_frame to the packet's end"); | ||
| 212 | process.frame_count = 300; | ||
| 213 | enqueue(apu, &process, nullptr); | ||
| 214 | dequeue(apu, &r); | ||
| 215 | check(r.frames == 300, "no more than frame_count"); | ||
| 216 | process.frame_count = 4000; | ||
| 217 | process.output_bytes = 100 * 8 + 7; | ||
| 218 | enqueue(apu, &process, nullptr); | ||
| 219 | dequeue(apu, &r); | ||
| 220 | check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds"); | ||
| 221 | |||
| 222 | // Errors carried in the result: the command is accepted and its result says what went wrong. | ||
| 223 | packet[1] = 7; // seven 20 ms frames: 140 ms, longer than an Opus packet may be | ||
| 224 | enqueue(apu, &process, nullptr); | ||
| 225 | dequeue(apu, &r); | ||
| 226 | check(r.error == kBadPacket && r.frames == 0, "an impossible packet: 0x8AC81008 in the result"); | ||
| 227 | packet[0] = (31 << 3) | 3; | ||
| 228 | packet[1] = 0; | ||
| 229 | enqueue(apu, &process, nullptr); | ||
| 230 | dequeue(apu, &r); | ||
| 231 | check(r.error == kBadPacket, "a code 3 packet of zero frames: 0x8AC81008"); | ||
| 232 | ProcessCommand empty = process; | ||
| 233 | empty.input_bytes = 0; | ||
| 234 | check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 235 | "an empty input: E_INVALIDARG in the result"); | ||
| 236 | empty = process; | ||
| 237 | empty.output = nullptr; | ||
| 238 | check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 239 | "a null output: E_INVALIDARG in the result"); | ||
| 240 | ProcessCommand stray = process; | ||
| 241 | stray.id.stream = 4; | ||
| 242 | check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream, | ||
| 243 | "a process on a stream never activated: 0x8AC81003 in the result"); | ||
| 244 | check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kAlreadyActive, | ||
| 245 | "activating an active stream: 0x8AC81005 in the result"); | ||
| 246 | ActivateCommand surround = activate; | ||
| 247 | surround.id.stream = 5; | ||
| 248 | surround.channels = 6; | ||
| 249 | check(enqueue(apu, &surround, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 250 | "six channels: E_INVALIDARG in the result"); | ||
| 251 | |||
| 252 | // Errors returned at once, with no result. | ||
| 253 | stray.id.stream = 128; | ||
| 254 | check(enqueue(apu, &stray, nullptr) == kInvalidStream, "a stream past the connection's is 0x8AC81003"); | ||
| 255 | const CommandId unknown = id(9, 3); | ||
| 256 | check(enqueue(apu, &unknown, nullptr) == kInvalidCommand, "an unknown kind is 0x8AC81002"); | ||
| 257 | check(count(apu, nullptr) == 0, "neither left a result"); | ||
| 258 | |||
| 259 | // Notify and reset give a result; deactivate gives one and closes the stream. | ||
| 260 | for (uint32_t kind : {4u, 5u, 2u}) { | ||
| 261 | const CommandId command = id(kind, 3); | ||
| 262 | check(enqueue(apu, &command, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.id.kind == kind && | ||
| 263 | r.id.stream == 3 && r.error == S_OK, | ||
| 264 | "notify, reset and deactivate each give a result of their kind for their stream"); | ||
| 87 | } | 265 | } |
| 88 | check(count(apu, 0) == 0, "XApuGetResultCount is 0 again"); | 266 | process.id.stream = 3; |
| 89 | uint8_t result[0x50] = {}; | 267 | enqueue(apu, &process, nullptr); |
| 90 | check(FAILED(dequeue(apu, result)), "XApuDequeueResult on the empty queue fails"); | 268 | dequeue(apu, &r); |
| 91 | check(disconnect(apu) == S_OK, "XApuDisconnect succeeds"); | 269 | check(r.error == kInvalidStream, "after deactivate the stream takes no process command"); |
| 270 | check(enqueue(apu, &activate, &total) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK, | ||
| 271 | "and it can be activated again"); | ||
| 272 | check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)"); | ||
| 92 | 273 | ||
| 93 | // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*), success read as a return of 0. | 274 | // XDspConnectWithMaximumStreamLimit(buffer, u32, u32, 0x80, 1, handle*), success read as a return of 0. |
| 94 | alignas(64) static uint8_t dsp_buffer[4096]; | 275 | alignas(64) static uint8_t dsp_buffer[4096]; |
| @@ -99,10 +280,10 @@ int main() { | |||
| 99 | void* stream = nullptr; | 280 | void* stream = nullptr; |
| 100 | check(dsp_activate(dsp, description, reinterpret_cast<void**>(&status), &stream) == 0, "XDspActivate returns 0"); | 281 | check(dsp_activate(dsp, description, reinterpret_cast<void**>(&status), &stream) == 0, "XDspActivate returns 0"); |
| 101 | check(status && stream && static_cast<void*>(status) != stream, "XDspActivate writes both outputs"); | 282 | check(status && stream && static_cast<void*>(status) != stream, "XDspActivate writes both outputs"); |
| 102 | uint32_t id = 0; | 283 | uint32_t dsp_id = 0; |
| 103 | check(dsp_submit(stream, dsp_buffer, &id) == 0, "XDspSubmitCommand returns 0"); | 284 | check(dsp_submit(stream, dsp_buffer, &dsp_id) == 0, "XDspSubmitCommand returns 0"); |
| 104 | // What the title's wait reads: no error at +0xc and the submitted id at +4. | 285 | // What the title's wait reads: no error at +0xc and the submitted id at +4. |
| 105 | check(status && status[3] == 0 && status[1] == id, "the status block reports the submitted command as done"); | 286 | check(status && status[3] == 0 && status[1] == dsp_id, "the status block reports the submitted command as done"); |
| 106 | check(dsp_deactivate(dsp, 0, 0, 0) == 0, "XDspDeactivate returns 0"); | 287 | check(dsp_deactivate(dsp, 0, 0, 0) == 0, "XDspDeactivate returns 0"); |
| 107 | check(dsp_disconnect(dsp) == 0, "XDspDisconnect returns 0"); | 288 | check(dsp_disconnect(dsp) == 0, "XDspDisconnect returns 0"); |
| 108 | 289 | ||
diff --git a/runtime/test/xapu_opus_test.cpp b/runtime/test/xapu_opus_test.cpp new file mode 100644 index 000000000..30eb33cfe --- /dev/null +++ b/runtime/test/xapu_opus_test.cpp | |||
| @@ -0,0 +1,193 @@ | |||
| 1 | // Checks the decoded path of the registered xapu.dll shim (runtime/shims/xapu_queue.cpp) with | ||
| 2 | // runtime/opus_decoder built: the title's ConnectInput, activate/process/deactivate, one result per | ||
| 3 | // command in order, the 0x50-byte result layout, and a generated 440 Hz stereo packet decoded to | ||
| 4 | // 960 frames of f32 PCM, then clipped by first_frame / frame_count / output_bytes. The packet is | ||
| 5 | // encoded here; no game data. | ||
| 6 | #include <windows.h> | ||
| 7 | |||
| 8 | #include <cmath> | ||
| 9 | #include <cstdint> | ||
| 10 | #include <cstdio> | ||
| 11 | #include <cstring> | ||
| 12 | #include <vector> | ||
| 13 | |||
| 14 | #include "leonida_opus_decoder.h" | ||
| 15 | #include "shims.h" | ||
| 16 | |||
| 17 | namespace { | ||
| 18 | |||
| 19 | using XApuConnectFn = HRESULT(__stdcall*)(const void*, void*, void**); | ||
| 20 | using XApuDisconnectFn = HRESULT(__stdcall*)(void*, uint32_t); | ||
| 21 | using XApuEnqueueCommandFn = HRESULT(__stdcall*)(void*, const void*, uint32_t*); | ||
| 22 | using XApuGetResultCountFn = uint32_t(__stdcall*)(void*, uint32_t*); | ||
| 23 | using XApuDequeueResultFn = HRESULT(__stdcall*)(void*, void*); | ||
| 24 | |||
| 25 | constexpr HRESULT kQueueFull = static_cast<HRESULT>(0x8AC81000u); | ||
| 26 | constexpr HRESULT kInvalidStream = static_cast<HRESULT>(0x8AC81003u); | ||
| 27 | |||
| 28 | #pragma pack(push, 1) | ||
| 29 | struct ConnectInput { | ||
| 30 | uint32_t processing, streams, commands_per_stream, memory_bytes, frames_per_output, options; | ||
| 31 | }; | ||
| 32 | struct ConnectOutput { | ||
| 33 | void* memory; | ||
| 34 | HANDLE result_event; | ||
| 35 | }; | ||
| 36 | struct CommandId { | ||
| 37 | uint32_t kind, stream, sequence, options; | ||
| 38 | uint64_t context; | ||
| 39 | }; | ||
| 40 | struct ActivateCommand { | ||
| 41 | CommandId id; | ||
| 42 | uint32_t channels, init_bytes; | ||
| 43 | const void* init; | ||
| 44 | float start_pitch; | ||
| 45 | uint32_t processing_bytes; | ||
| 46 | void* processing; | ||
| 47 | }; | ||
| 48 | struct ProcessCommand { | ||
| 49 | CommandId id; | ||
| 50 | float pitch_ramp, target_pitch; | ||
| 51 | uint32_t first_frame, frame_count, input_bytes; | ||
| 52 | const uint8_t* input; | ||
| 53 | uint32_t output_bytes; | ||
| 54 | uint8_t* output; | ||
| 55 | }; | ||
| 56 | struct Result { | ||
| 57 | CommandId id; | ||
| 58 | uint32_t state; | ||
| 59 | uint64_t state_data, usec; | ||
| 60 | HRESULT error; | ||
| 61 | uint32_t frames, output_bytes; | ||
| 62 | uint8_t* output; | ||
| 63 | float pitch; | ||
| 64 | uint32_t input_bytes; | ||
| 65 | const uint8_t* input; | ||
| 66 | }; | ||
| 67 | #pragma pack(pop) | ||
| 68 | static_assert(sizeof(ActivateCommand) == 56 && sizeof(ProcessCommand) == 64 && sizeof(Result) == 0x50, "layouts"); | ||
| 69 | |||
| 70 | int g_checks = 0; | ||
| 71 | int g_failures = 0; | ||
| 72 | |||
| 73 | void check(bool condition, const char* what) { | ||
| 74 | ++g_checks; | ||
| 75 | std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); | ||
| 76 | if (!condition) ++g_failures; | ||
| 77 | } | ||
| 78 | |||
| 79 | template <typename T> | ||
| 80 | T get(const char* dll, const char* name) { | ||
| 81 | void* fn = rt::shims::find(dll, name); | ||
| 82 | check(fn != nullptr, name); | ||
| 83 | return reinterpret_cast<T>(fn); | ||
| 84 | } | ||
| 85 | |||
| 86 | CommandId id(uint32_t kind, uint32_t stream, uint32_t options = 0) { return {kind, stream, 7, options, 0x1234}; } | ||
| 87 | |||
| 88 | } // namespace | ||
| 89 | |||
| 90 | int main() { | ||
| 91 | std::printf("xapu_opus_test: decoded xapu.dll path\n"); | ||
| 92 | const auto connect = get<XApuConnectFn>("xapu.dll", "XApuConnect"); | ||
| 93 | const auto disconnect = get<XApuDisconnectFn>("xapu.dll", "XApuDisconnect"); | ||
| 94 | const auto enqueue = get<XApuEnqueueCommandFn>("xapu.dll", "XApuEnqueueCommand"); | ||
| 95 | const auto count = get<XApuGetResultCountFn>("xapu.dll", "XApuGetResultCount"); | ||
| 96 | const auto dequeue = get<XApuDequeueResultFn>("xapu.dll", "XApuDequeueResult"); | ||
| 97 | if (g_failures) return 1; | ||
| 98 | |||
| 99 | constexpr uint32_t kMemory = 0x14000 + 128 * 0x1E00; | ||
| 100 | const ConnectInput in{1, 128, 2, kMemory, 0, 0}; | ||
| 101 | const ConnectInput in_copy = in; | ||
| 102 | ConnectOutput out{}; | ||
| 103 | void* apu = nullptr; | ||
| 104 | check(SUCCEEDED(connect(&in, &out, &apu)) && apu, "XApuConnect for Opus decoding"); | ||
| 105 | check(std::memcmp(&in, &in_copy, sizeof in) == 0, "XApuConnect leaves its input alone"); | ||
| 106 | auto* base = static_cast<uint8_t*>(out.memory); | ||
| 107 | if (!apu || !base) return 1; | ||
| 108 | check(base[0] == 0 && base[kMemory - 1] == 0, "the shared memory is zeroed"); | ||
| 109 | |||
| 110 | const ActivateCommand activate{id(1, 3), 2, 0, nullptr, 1.0f, 0, nullptr}; | ||
| 111 | check(enqueue(apu, &activate, nullptr) == S_OK, "activate stream 3 (stereo)"); | ||
| 112 | |||
| 113 | std::vector<float> tone(960 * 2); | ||
| 114 | for (uint32_t i = 0; i < 960; ++i) { | ||
| 115 | const float sample = static_cast<float>(std::sin(double(i) * 440.0 * 6.283185307179586 / 48000.0)) * 0.5f; | ||
| 116 | tone[2 * i] = sample; | ||
| 117 | tone[2 * i + 1] = sample; | ||
| 118 | } | ||
| 119 | uint8_t encoded[1500]; | ||
| 120 | size_t encoded_len = 0; | ||
| 121 | check(leonida_opus_encode_test(tone.data(), 960, 2, encoded, sizeof encoded, &encoded_len) == LEONIDA_OPUS_OK && | ||
| 122 | encoded_len > 0, | ||
| 123 | "a synthetic 20 ms stereo Opus packet encodes"); | ||
| 124 | std::memcpy(base, encoded, encoded_len); | ||
| 125 | auto* const pcm = base + 0x14000 + 3 * 0x1E00; | ||
| 126 | std::memset(pcm, 0x55, 0x1E00 + 64); | ||
| 127 | ProcessCommand process{id(3, 3, 1), 0.0f, 1.0f, 0, 960, static_cast<uint32_t>(encoded_len), base, 0x1E00, pcm}; | ||
| 128 | uint32_t total = 0; | ||
| 129 | check(enqueue(apu, &process, &total) == S_OK && total == 2, "process on stream 3; two commands accepted"); | ||
| 130 | check(enqueue(apu, &process, &total) == kQueueFull && total == 2, | ||
| 131 | "a third command on a stream of two is 0x8AC81000"); | ||
| 132 | check(count(apu, nullptr) == 2, "two results ready"); | ||
| 133 | |||
| 134 | Result r{}; | ||
| 135 | check(dequeue(apu, &r) == S_OK && r.id.kind == 1 && r.id.stream == 3 && r.error == S_OK, | ||
| 136 | "results come in command order: the activate first"); | ||
| 137 | check(dequeue(apu, &r) == S_OK && r.id.kind == 3 && r.error == S_OK, "the process result follows"); | ||
| 138 | uint32_t dword34 = 0; | ||
| 139 | std::memcpy(&dword34, reinterpret_cast<const uint8_t*>(&r) + 0x34, 4); | ||
| 140 | check(r.frames == 960 && dword34 == 960 * 8 && r.output == pcm && r.input == base && | ||
| 141 | r.input_bytes == static_cast<uint32_t>(encoded_len), | ||
| 142 | "960 stereo float frames, the byte count at +0x34, the buffers echoed"); | ||
| 143 | float energy = 0.0f; | ||
| 144 | const auto* floats = reinterpret_cast<const float*>(pcm); | ||
| 145 | for (uint32_t i = 0; i < 960 * 2; ++i) energy += floats[i] * floats[i]; | ||
| 146 | energy /= 960 * 2; | ||
| 147 | check(energy > 0.01f, "the decoded tone has energy"); | ||
| 148 | check(pcm[960 * 8] == 0x55, "nothing past the decoded range is written"); | ||
| 149 | check(count(apu, nullptr) == 0, "the queue is empty after both results"); | ||
| 150 | |||
| 151 | // first_frame, frame_count and what output_bytes holds each clip the decoded frames. | ||
| 152 | process.first_frame = 500; | ||
| 153 | process.frame_count = 4000; | ||
| 154 | enqueue(apu, &process, nullptr); | ||
| 155 | dequeue(apu, &r); | ||
| 156 | check(r.error == S_OK && r.frames == 460 && r.output_bytes == 460 * 8, "frames from first_frame to the packet's end"); | ||
| 157 | process.frame_count = 300; | ||
| 158 | enqueue(apu, &process, nullptr); | ||
| 159 | dequeue(apu, &r); | ||
| 160 | check(r.frames == 300 && r.output_bytes == 300 * 8, "no more than frame_count"); | ||
| 161 | process.frame_count = 4000; | ||
| 162 | process.output_bytes = 100 * 8 + 7; | ||
| 163 | enqueue(apu, &process, nullptr); | ||
| 164 | dequeue(apu, &r); | ||
| 165 | check(r.frames == 100 && r.output_bytes == 800, "and no more than the output holds"); | ||
| 166 | |||
| 167 | // Errors carried in the result. | ||
| 168 | ProcessCommand empty = process; | ||
| 169 | empty.input_bytes = 0; | ||
| 170 | check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 171 | "an empty input: E_INVALIDARG in the result"); | ||
| 172 | empty = process; | ||
| 173 | empty.output = nullptr; | ||
| 174 | check(enqueue(apu, &empty, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == E_INVALIDARG, | ||
| 175 | "a null output: E_INVALIDARG in the result"); | ||
| 176 | ProcessCommand stray = process; | ||
| 177 | stray.id.stream = 4; | ||
| 178 | check(enqueue(apu, &stray, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream, | ||
| 179 | "a process on a stream never activated: 0x8AC81003 in the result"); | ||
| 180 | |||
| 181 | // Deactivate closes the stream; activating again creates a fresh decoder. | ||
| 182 | const CommandId deactivate = id(2, 3); | ||
| 183 | check(enqueue(apu, &deactivate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK, | ||
| 184 | "deactivate gives a result and closes the stream"); | ||
| 185 | check(enqueue(apu, &process, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == kInvalidStream, | ||
| 186 | "after deactivate the stream takes no process command"); | ||
| 187 | check(enqueue(apu, &activate, nullptr) == S_OK && dequeue(apu, &r) == S_OK && r.error == S_OK, | ||
| 188 | "the stream can be activated again"); | ||
| 189 | check(disconnect(apu, 0x20) == S_OK, "XApuDisconnect(handle, 0x20)"); | ||
| 190 | |||
| 191 | std::printf("%d checks, %d failures\n", g_checks, g_failures); | ||
| 192 | return g_failures ? 1 : 0; | ||
| 193 | } | ||