upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/opus_decoder
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 16:55:04 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-26 16:55:04 -0500
commitdf92abca8ee2a8f9093efea7fcaa4dadc3ddaebc (patch)
tree97ef8f95544fe263049d3f7360823f16100de209 /runtime/opus_decoder
parent49a0b69fcdb80db1f2a44ce7ca0ab8dfdec1e403 (diff)
parente5a7c8942678b323f655939c81f5d8855d20c248 (diff)
Merge main e5a7c8942 into shadow-aliased-guard (#1867)
One conflict, runtime/README.md: this branch rewrote the LEONIDA_SHADOW_ALIAS_MS row, main (#2163) added the LEONIDA_SHADOW_KEEP row after it. Both rows kept; the keep row's "aliased" now reads "aliased while they can't be guarded at every address", since aliased pages are no longer copied without a sign of a write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/opus_decoder')
-rw-r--r--runtime/opus_decoder/Cargo.lock16
-rw-r--r--runtime/opus_decoder/Cargo.toml16
-rw-r--r--runtime/opus_decoder/README.md33
-rw-r--r--runtime/opus_decoder/leonida_opus_decoder.h44
-rw-r--r--runtime/opus_decoder/src/lib.rs244
5 files changed, 353 insertions, 0 deletions
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.
3version = 4
4
5[[package]]
6name = "leonida-opus-decoder"
7version = "0.1.0"
8dependencies = [
9 "opus-pure",
10]
11
12[[package]]
13name = "opus-pure"
14version = "0.2.5"
15source = "registry+https://github.com/rust-lang/crates.io-index"
16checksum = "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]
2name = "leonida-opus-decoder"
3version = "0.1.0"
4edition = "2021"
5license = "GPL-3.0-or-later"
6publish = false
7
8[lib]
9name = "leonida_opus_decoder"
10crate-type = ["staticlib", "rlib"]
11
12[dependencies]
13opus-pure = "0.2.4"
14
15[profile.release]
16panic = "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
3This crate exposes a C ABI around the BSD-3-Clause `opus-pure` package for the console audio
4decoder (`xapu.dll`). The command protocol lives in `runtime/shims/xapu_chad.cpp`; this crate only
5decodes one Opus packet into interleaved f32 PCM, resets the decoder, and (for tests) encodes a
6synthetic tone.
7
8## Build
9
10```sh
11cargo fmt --manifest-path runtime/opus_decoder/Cargo.toml -- --check
12cargo test --manifest-path runtime/opus_decoder/Cargo.toml --locked
13cargo 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
21Without `cargo`, when the build fails, or with the `cl.exe` fallback of `scripts/build_runtime.ps1`,
22the XAPU path stays silent. Use `-DLEONIDA_REQUIRE_OPUS_DECODER=ON` to require the decoder in a
23CMake build.
24
25To link an already-built `leonida_opus_decoder.lib` without invoking `cargo` during CMake
26configure, pass `-DLEONIDA_OPUS_DECODER_LIB=<path>`.
27
28## Facts and credit
29
30The `xapu.dll` command protocol (connect input/output, per-stream command budget, activate /
31process / 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
33other 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
8extern "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
14typedef struct LeonidaOpusDecoder LeonidaOpusDecoder;
15
16enum 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
26int32_t leonida_opus_decoder_create(uint32_t sample_rate, uint32_t channels,
27 LeonidaOpusDecoder **out_decoder);
28uint32_t leonida_opus_decoder_channels(const LeonidaOpusDecoder *decoder);
29int32_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);
33int32_t leonida_opus_decoder_reset(LeonidaOpusDecoder *decoder);
34void leonida_opus_decoder_destroy(LeonidaOpusDecoder *decoder);
35/* Test helper: encodes frame_count interleaved f32 frames to one packet at 48 kHz. */
36int32_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
9use std::panic::{catch_unwind, AssertUnwindSafe};
10use std::ptr;
11use std::sync::Mutex;
12
13use opus_pure::{Application, OpusDecoder, OpusEncoder};
14
15pub const LEONIDA_OPUS_OK: i32 = 0;
16pub const LEONIDA_OPUS_INVALID_ARGUMENT: i32 = 1;
17pub const LEONIDA_OPUS_INVALID_FORMAT: i32 = 2;
18pub const LEONIDA_OPUS_DECODER_FAILURE: i32 = 3;
19pub const LEONIDA_OPUS_OUT_OF_MEMORY: i32 = 4;
20pub const LEONIDA_OPUS_PANIC: i32 = 5;
21pub const LEONIDA_OPUS_BUFFER_TOO_SMALL: i32 = 6;
22
23/// 120 ms at 48 kHz, the longest Opus packet, in samples per channel.
24pub const LEONIDA_OPUS_MAX_FRAMES: usize = 5760;
25
26#[repr(C)]
27pub struct LeonidaOpusDecoder {
28 decoder: Mutex<OpusDecoder>,
29 channels: usize,
30}
31
32#[no_mangle]
33pub 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]
46pub 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]
82pub 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]
124pub 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]
139pub 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]
151pub 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)]
188mod 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}