upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/xma_decoder
diff options
context:
space:
mode:
authorRafael <rafaelalvesp2005@gmail.com>2026-11-23 15:36:26 -0300
committerRafael <rafaelalvesp2005@gmail.com>2026-11-23 15:36:26 -0300
commit63f0e0dea3a9d44201db408c4e2c3f2f5b2b94d6 (patch)
tree86f0dcad8070e2a3a693ef4897aa83950cfeb224 /runtime/xma_decoder
parentf78f7d6a2a9364cb128c03ac539fe540d5c70df1 (diff)
parent6dda0630bd6fc0514baadb94fb98e36bd7d64c0b (diff)
Merge main into fix/walk-bink_names
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/xma_decoder')
-rw-r--r--runtime/xma_decoder/.gitignore1
-rw-r--r--runtime/xma_decoder/Cargo.lock15
-rw-r--r--runtime/xma_decoder/Cargo.toml16
-rw-r--r--runtime/xma_decoder/README.md19
-rw-r--r--runtime/xma_decoder/leonida_xma2_decoder.h40
-rw-r--r--runtime/xma_decoder/src/lib.rs263
-rw-r--r--runtime/xma_decoder/tests/ffi_contract.rs227
-rw-r--r--runtime/xma_decoder/tests/ffi_cpp_smoke.cpp87
8 files changed, 668 insertions, 0 deletions
diff --git a/runtime/xma_decoder/.gitignore b/runtime/xma_decoder/.gitignore
new file mode 100644
index 000000000..b83d22266
--- /dev/null
+++ b/runtime/xma_decoder/.gitignore
@@ -0,0 +1 @@
/target/
diff --git a/runtime/xma_decoder/Cargo.lock b/runtime/xma_decoder/Cargo.lock
new file mode 100644
index 000000000..fcbc37f0d
--- /dev/null
+++ b/runtime/xma_decoder/Cargo.lock
@@ -0,0 +1,15 @@
1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "leonida-xma2-decoder"
7version = "0.1.0"
8dependencies = [
9 "xma",
10]
11
12[[package]]
13name = "xma"
14version = "0.1.0"
15source = "git+https://github.com/omonkeyz/xbox-emulator?rev=27122f7dfcceb9a899555362ee0dde2d530e033c#27122f7dfcceb9a899555362ee0dde2d530e033c"
diff --git a/runtime/xma_decoder/Cargo.toml b/runtime/xma_decoder/Cargo.toml
new file mode 100644
index 000000000..2f0fa7eaa
--- /dev/null
+++ b/runtime/xma_decoder/Cargo.toml
@@ -0,0 +1,16 @@
1[package]
2name = "leonida-xma2-decoder"
3version = "0.1.0"
4edition = "2021"
5license = "GPL-3.0-or-later"
6publish = false
7
8[lib]
9name = "leonida_xma2_decoder"
10crate-type = ["staticlib", "rlib"]
11
12[dependencies]
13xma = { git = "https://github.com/omonkeyz/xbox-emulator", package = "xma", rev = "27122f7dfcceb9a899555362ee0dde2d530e033c" }
14
15[profile.release]
16panic = "unwind"
diff --git a/runtime/xma_decoder/README.md b/runtime/xma_decoder/README.md
new file mode 100644
index 000000000..4a6d5fb10
--- /dev/null
+++ b/runtime/xma_decoder/README.md
@@ -0,0 +1,19 @@
1# XMA2 decoder C ABI
2
3This crate exposes a C ABI around the separately licensed xma Rust package pinned in Cargo.toml. It decodes one mono or stereo stream from a non-empty buffer of complete 2048-byte XMA2 packets into interleaved signed 16-bit PCM.
4
5Each decoder handle serializes decode calls. The returned PCM block owns its samples and stays valid until leonida_xma2_pcm_destroy, even after its decoder is destroyed. Do not destroy a decoder concurrently with a decode call or destroy a handle more than once.
6
7The tests build packets in memory; they do not open or contain audio fixtures. The synthetic C++ smoke test verifies the exported ABI and ownership boundary.
8
9This PR adds the decoder boundary only; the Windows XAudio2 engine/source-voice adapter is a follow-up stage.
10
11Run:
12
13```powershell
14cargo fmt --manifest-path runtime/xma_decoder/Cargo.toml -- --check
15cargo test --manifest-path runtime/xma_decoder/Cargo.toml --locked
16cargo build --manifest-path runtime/xma_decoder/Cargo.toml --locked
17```
18
19The C++ smoke test is run by the xma2-decoder workflow with MSVC. It links ws2_32, userenv, and ntdll for Rust's Windows standard library.
diff --git a/runtime/xma_decoder/leonida_xma2_decoder.h b/runtime/xma_decoder/leonida_xma2_decoder.h
new file mode 100644
index 000000000..98dd5c49c
--- /dev/null
+++ b/runtime/xma_decoder/leonida_xma2_decoder.h
@@ -0,0 +1,40 @@
1#ifndef LEONIDA_XMA2_DECODER_H
2#define LEONIDA_XMA2_DECODER_H
3
4#include <stddef.h>
5#include <stdint.h>
6
7#ifdef __cplusplus
8extern "C" {
9#endif
10
11#define LEONIDA_XMA2_PACKET_BYTES 2048u
12
13typedef struct LeonidaXma2Decoder LeonidaXma2Decoder;
14typedef struct LeonidaXma2PcmBlock LeonidaXma2PcmBlock;
15
16enum LeonidaXma2Status {
17 LEONIDA_XMA2_OK = 0,
18 LEONIDA_XMA2_INVALID_ARGUMENT = 1,
19 LEONIDA_XMA2_INVALID_FORMAT = 2,
20 LEONIDA_XMA2_BAD_PACKET_SIZE = 3,
21 LEONIDA_XMA2_OUT_OF_MEMORY = 4,
22 LEONIDA_XMA2_DECODER_FAILURE = 5,
23 LEONIDA_XMA2_PANIC = 6,
24};
25
26int32_t leonida_xma2_decoder_create(uint32_t sample_rate, uint32_t channels,
27 LeonidaXma2Decoder **out_decoder);
28int32_t leonida_xma2_decode_buffer(LeonidaXma2Decoder *decoder,
29 const uint8_t *input, size_t input_len,
30 LeonidaXma2PcmBlock **out_block);
31void leonida_xma2_decoder_destroy(LeonidaXma2Decoder *decoder);
32const int16_t *leonida_xma2_pcm_data(const LeonidaXma2PcmBlock *block);
33size_t leonida_xma2_pcm_sample_count(const LeonidaXma2PcmBlock *block);
34void leonida_xma2_pcm_destroy(LeonidaXma2PcmBlock *block);
35
36#ifdef __cplusplus
37}
38#endif
39
40#endif
diff --git a/runtime/xma_decoder/src/lib.rs b/runtime/xma_decoder/src/lib.rs
new file mode 100644
index 000000000..1b435a0ce
--- /dev/null
+++ b/runtime/xma_decoder/src/lib.rs
@@ -0,0 +1,263 @@
1#![deny(unsafe_op_in_unsafe_fn)]
2
3use std::alloc::Layout;
4use std::panic::{catch_unwind, AssertUnwindSafe};
5use std::ptr;
6use std::slice;
7use std::sync::Mutex;
8
9use xma::{Xma2Stream, XMA_FRAME_SAMPLES, XMA_PACKET_BYTES};
10
11pub const LEONIDA_XMA2_OK: i32 = 0;
12pub const LEONIDA_XMA2_INVALID_ARGUMENT: i32 = 1;
13pub const LEONIDA_XMA2_INVALID_FORMAT: i32 = 2;
14pub const LEONIDA_XMA2_BAD_PACKET_SIZE: i32 = 3;
15pub const LEONIDA_XMA2_OUT_OF_MEMORY: i32 = 4;
16pub const LEONIDA_XMA2_DECODER_FAILURE: i32 = 5;
17pub const LEONIDA_XMA2_PANIC: i32 = 6;
18
19const MAX_FRAMES_PER_PACKET: usize = 64;
20
21#[repr(C)]
22pub struct LeonidaXma2Decoder {
23 stream: Mutex<Xma2Stream>,
24 channels: usize,
25}
26
27#[repr(C)]
28pub struct LeonidaXma2PcmBlock {
29 samples: Vec<i16>,
30}
31
32#[cfg(not(test))]
33use std::alloc::alloc as allocate_handle;
34#[cfg(test)]
35use tests::allocate_handle;
36
37fn try_new_handle<T>(value: T) -> Result<Box<T>, i32> {
38 const { assert!(std::mem::size_of::<T>() > 0) };
39 // Both the allocation and Box's eventual deallocation use the global allocator
40 // with T's exact layout. Initialize the storage before handing it to Box.
41 let storage = unsafe { allocate_handle(Layout::new::<T>()) }.cast::<T>();
42 if storage.is_null() {
43 return Err(LEONIDA_XMA2_OUT_OF_MEMORY);
44 }
45 unsafe {
46 storage.write(value);
47 Ok(Box::from_raw(storage))
48 }
49}
50
51/// Creates a decoder for one mono or stereo XMA2 stream.
52///
53/// # Safety
54/// `out_decoder` must be writable for one pointer. The returned decoder must be destroyed once,
55/// after all calls using it have finished.
56#[no_mangle]
57pub unsafe extern "C" fn leonida_xma2_decoder_create(
58 sample_rate: u32,
59 channels: u32,
60 out_decoder: *mut *mut LeonidaXma2Decoder,
61) -> i32 {
62 if out_decoder.is_null() {
63 return LEONIDA_XMA2_INVALID_ARGUMENT;
64 }
65 unsafe { *out_decoder = ptr::null_mut() };
66 if sample_rate == 0 || !(channels == 1 || channels == 2) {
67 return LEONIDA_XMA2_INVALID_FORMAT;
68 }
69
70 match catch_unwind(AssertUnwindSafe(|| {
71 let stream = Xma2Stream::new(sample_rate, channels as usize)
72 .map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?;
73 try_new_handle(LeonidaXma2Decoder {
74 stream: Mutex::new(stream),
75 channels: channels as usize,
76 })
77 })) {
78 Ok(Ok(decoder)) => {
79 unsafe { *out_decoder = Box::into_raw(decoder) };
80 LEONIDA_XMA2_OK
81 }
82 Ok(Err(status)) => status,
83 Err(_) => LEONIDA_XMA2_PANIC,
84 }
85}
86
87/// Decodes a buffer containing one or more complete 2048-byte XMA2 packets.
88///
89/// # Safety
90/// `decoder` must be a live handle returned by `leonida_xma2_decoder_create`.
91/// `input` must reference `input_len` readable bytes and `out_block` must be writable.
92/// Do not destroy a decoder concurrently with this call. The returned PCM block remains valid
93/// until `leonida_xma2_pcm_destroy` is called.
94#[no_mangle]
95pub unsafe extern "C" fn leonida_xma2_decode_buffer(
96 decoder: *mut LeonidaXma2Decoder,
97 input: *const u8,
98 input_len: usize,
99 out_block: *mut *mut LeonidaXma2PcmBlock,
100) -> i32 {
101 if out_block.is_null() {
102 return LEONIDA_XMA2_INVALID_ARGUMENT;
103 }
104 unsafe { *out_block = ptr::null_mut() };
105
106 if decoder.is_null() || input.is_null() || input_len > isize::MAX as usize {
107 return LEONIDA_XMA2_INVALID_ARGUMENT;
108 }
109 if input_len == 0 || !input_len.is_multiple_of(XMA_PACKET_BYTES) {
110 return LEONIDA_XMA2_BAD_PACKET_SIZE;
111 }
112
113 let decoded = catch_unwind(AssertUnwindSafe(|| {
114 let handle = unsafe { &*decoder };
115 let bytes = unsafe { slice::from_raw_parts(input, input_len) };
116 let mut stream = handle
117 .stream
118 .lock()
119 .map_err(|_| LEONIDA_XMA2_DECODER_FAILURE)?;
120 let max_packet_samples = MAX_FRAMES_PER_PACKET
121 .checked_mul(XMA_FRAME_SAMPLES)
122 .and_then(|samples| samples.checked_mul(handle.channels))
123 .ok_or(LEONIDA_XMA2_INVALID_ARGUMENT)?;
124 let mut block = try_new_handle(LeonidaXma2PcmBlock {
125 samples: Vec::new(),
126 })?;
127 let samples = &mut block.samples;
128
129 let (packets, _) = bytes.as_chunks::<XMA_PACKET_BYTES>();
130 for packet in packets {
131 let requested = samples
132 .len()
133 .checked_add(max_packet_samples)
134 .ok_or(LEONIDA_XMA2_INVALID_ARGUMENT)?;
135 if requested > isize::MAX as usize / std::mem::size_of::<i16>() {
136 return Err(LEONIDA_XMA2_INVALID_ARGUMENT);
137 }
138 samples
139 .try_reserve(max_packet_samples)
140 .map_err(|_| LEONIDA_XMA2_OUT_OF_MEMORY)?;
141 stream.decode_packet(packet, samples);
142 }
143
144 if !samples.len().is_multiple_of(handle.channels) {
145 return Err(LEONIDA_XMA2_DECODER_FAILURE);
146 }
147 Ok(block)
148 }));
149
150 match decoded {
151 Ok(Ok(block)) => {
152 unsafe { *out_block = Box::into_raw(block) };
153 LEONIDA_XMA2_OK
154 }
155 Ok(Err(status)) => status,
156 Err(_) => LEONIDA_XMA2_PANIC,
157 }
158}
159
160/// Destroys a decoder. Passing null is a no-op.
161///
162/// # Safety
163/// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create`,
164/// and no calls may be using it concurrently.
165#[no_mangle]
166pub unsafe extern "C" fn leonida_xma2_decoder_destroy(decoder: *mut LeonidaXma2Decoder) {
167 if !decoder.is_null() {
168 unsafe { drop(Box::from_raw(decoder)) };
169 }
170}
171
172/// Returns the immutable interleaved signed-16 PCM pointer for a block.
173///
174/// # Safety
175/// A non-null pointer must be a live block returned by `leonida_xma2_decode_buffer`.
176/// The returned pointer is valid only until the block is destroyed.
177#[no_mangle]
178pub unsafe extern "C" fn leonida_xma2_pcm_data(block: *const LeonidaXma2PcmBlock) -> *const i16 {
179 unsafe { block.as_ref() }.map_or(ptr::null(), |pcm| pcm.samples.as_ptr())
180}
181
182/// Returns the number of signed-16 samples in a block.
183///
184/// # Safety
185/// A non-null pointer must be a live block returned by `leonida_xma2_decode_buffer`.
186#[no_mangle]
187pub unsafe extern "C" fn leonida_xma2_pcm_sample_count(block: *const LeonidaXma2PcmBlock) -> usize {
188 unsafe { block.as_ref() }.map_or(0, |pcm| pcm.samples.len())
189}
190
191/// Destroys a PCM block. Passing null is a no-op.
192///
193/// # Safety
194/// A non-null pointer must be a live block returned by `leonida_xma2_decode_buffer`.
195#[no_mangle]
196pub unsafe extern "C" fn leonida_xma2_pcm_destroy(block: *mut LeonidaXma2PcmBlock) {
197 if !block.is_null() {
198 unsafe { drop(Box::from_raw(block)) };
199 }
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205 use std::cell::Cell;
206
207 thread_local! {
208 static FAIL_NEXT_HANDLE_ALLOCATION: Cell<bool> = const { Cell::new(false) };
209 }
210
211 pub(super) unsafe fn allocate_handle(layout: Layout) -> *mut u8 {
212 if FAIL_NEXT_HANDLE_ALLOCATION.replace(false) {
213 ptr::null_mut()
214 } else {
215 unsafe { std::alloc::alloc(layout) }
216 }
217 }
218
219 #[test]
220 fn decoder_handle_allocation_failure_clears_output() {
221 let mut decoder = ptr::dangling_mut();
222 FAIL_NEXT_HANDLE_ALLOCATION.set(true);
223 let status = unsafe { leonida_xma2_decoder_create(48_000, 2, &mut decoder) };
224 assert_eq!(status, LEONIDA_XMA2_OUT_OF_MEMORY);
225 assert!(decoder.is_null());
226
227 assert_eq!(
228 unsafe { leonida_xma2_decoder_create(48_000, 2, &mut decoder) },
229 LEONIDA_XMA2_OK
230 );
231 assert!(!decoder.is_null());
232 unsafe { leonida_xma2_decoder_destroy(decoder) };
233 }
234
235 #[test]
236 fn pcm_handle_allocation_failure_clears_output_and_allows_retry() {
237 let mut decoder = ptr::null_mut();
238 assert_eq!(
239 unsafe { leonida_xma2_decoder_create(48_000, 2, &mut decoder) },
240 LEONIDA_XMA2_OK
241 );
242 let packet = [0u8; XMA_PACKET_BYTES];
243 let mut block = ptr::dangling_mut();
244 FAIL_NEXT_HANDLE_ALLOCATION.set(true);
245 let status = unsafe {
246 leonida_xma2_decode_buffer(decoder, packet.as_ptr(), packet.len(), &mut block)
247 };
248 assert_eq!(status, LEONIDA_XMA2_OUT_OF_MEMORY);
249 assert!(block.is_null());
250
251 assert_eq!(
252 unsafe {
253 leonida_xma2_decode_buffer(decoder, packet.as_ptr(), packet.len(), &mut block)
254 },
255 LEONIDA_XMA2_OK
256 );
257 assert!(!block.is_null());
258 unsafe {
259 leonida_xma2_pcm_destroy(block);
260 leonida_xma2_decoder_destroy(decoder);
261 }
262 }
263}
diff --git a/runtime/xma_decoder/tests/ffi_contract.rs b/runtime/xma_decoder/tests/ffi_contract.rs
new file mode 100644
index 000000000..0eb8e5cf4
--- /dev/null
+++ b/runtime/xma_decoder/tests/ffi_contract.rs
@@ -0,0 +1,227 @@
1use leonida_xma2_decoder::*;
2use std::ptr;
3use xma::bits::BitWriter;
4use xma::Xma2Stream;
5
6const PACKET_BYTES: usize = 2048;
7
8fn synthetic_silent_packet(channels: usize) -> [u8; PACKET_BYTES] {
9 assert!(channels == 1 || channels == 2);
10
11 let mut frame = BitWriter::default();
12 frame.put(1, 1); // Fixed-size tile header.
13 frame.put(1, 0); // One full-length subframe.
14 if channels == 2 {
15 frame.put(1, 0); // No optional stereo decorrelation matrix.
16 }
17 frame.put(8, 0); // No dynamic range adjustment.
18 frame.put(1, 0); // No trim metadata.
19 frame.put(1, 0); // No fill data.
20 frame.put(1, 0); // No corrupt-subframe marker.
21 if channels == 2 {
22 frame.put(1, 0); // No stereo transform error.
23 frame.put(1, 1); // Two-channel group without decorrelation.
24 frame.put(1, 0);
25 }
26 for _ in 0..channels {
27 frame.put(1, 0); // No transmitted coefficients: silence.
28 }
29 frame.put(1, 0); // Align to the next frame boundary.
30 frame.put(1, 0); // This packet contains one frame.
31
32 let frame_bits = 15 + frame.bits;
33 let mut packet_writer = BitWriter::default();
34 packet_writer.put(6, 1);
35 packet_writer.put(15, frame_bits as u32);
36 packet_writer.put(3, 1);
37 packet_writer.put(8, 0);
38 packet_writer.put(15, frame_bits as u32);
39 packet_writer.copy_from(&frame.buf, 0, frame.bits);
40
41 let mut packet = [0u8; PACKET_BYTES];
42 packet[..packet_writer.buf.len()].copy_from_slice(&packet_writer.buf);
43 packet
44}
45
46fn make_decoder(rate: u32, channels: u32) -> *mut LeonidaXma2Decoder {
47 let mut decoder = ptr::null_mut();
48 let result = unsafe { leonida_xma2_decoder_create(rate, channels, &mut decoder) };
49 assert_eq!(result, LEONIDA_XMA2_OK);
50 assert!(!decoder.is_null());
51 decoder
52}
53
54#[test]
55fn creation_rejects_invalid_outputs_and_formats() {
56 assert_eq!(
57 unsafe { leonida_xma2_decoder_create(48_000, 2, ptr::null_mut()) },
58 LEONIDA_XMA2_INVALID_ARGUMENT
59 );
60
61 let mut decoder = ptr::dangling_mut::<LeonidaXma2Decoder>();
62 assert_eq!(
63 unsafe { leonida_xma2_decoder_create(48_000, 3, &mut decoder) },
64 LEONIDA_XMA2_INVALID_FORMAT
65 );
66 assert!(decoder.is_null());
67
68 assert_eq!(
69 unsafe { leonida_xma2_decoder_create(0, 1, &mut decoder) },
70 LEONIDA_XMA2_INVALID_FORMAT
71 );
72 assert!(decoder.is_null());
73}
74
75#[test]
76fn synthetic_silent_packet_returns_owned_pcm_block_after_decoder_destruction() {
77 let decoder = make_decoder(48_000, 2);
78 let packet = synthetic_silent_packet(2);
79 let mut input = [0u8; PACKET_BYTES * 3];
80 input[PACKET_BYTES..PACKET_BYTES * 2].copy_from_slice(&packet);
81 input[PACKET_BYTES * 2..].copy_from_slice(&packet);
82 let mut block = ptr::null_mut();
83
84 assert_eq!(
85 unsafe { leonida_xma2_decode_buffer(decoder, input.as_ptr(), input.len(), &mut block,) },
86 LEONIDA_XMA2_OK
87 );
88 assert!(!block.is_null());
89
90 let samples = unsafe { leonida_xma2_pcm_sample_count(block) };
91 assert_eq!(samples % 2, 0);
92 assert!(samples > 0);
93 let pcm = unsafe { leonida_xma2_pcm_data(block) };
94 assert!(!pcm.is_null());
95 let decoded = unsafe { std::slice::from_raw_parts(pcm, samples) };
96 assert!(decoded.iter().all(|sample| *sample == 0));
97
98 unsafe { leonida_xma2_decoder_destroy(decoder) };
99 assert_eq!(unsafe { leonida_xma2_pcm_sample_count(block) }, samples);
100 assert_eq!(
101 unsafe { std::slice::from_raw_parts(leonida_xma2_pcm_data(block), samples) },
102 decoded
103 );
104 unsafe { leonida_xma2_pcm_destroy(block) };
105}
106
107#[test]
108fn synthetic_silent_mono_stream_decodes_to_silent_pcm() {
109 let decoder = make_decoder(44_100, 1);
110 let packet = synthetic_silent_packet(1);
111 let mut input = [0u8; PACKET_BYTES * 3];
112 input[PACKET_BYTES..PACKET_BYTES * 2].copy_from_slice(&packet);
113 input[PACKET_BYTES * 2..].copy_from_slice(&packet);
114 let mut block = ptr::null_mut();
115
116 assert_eq!(
117 unsafe { leonida_xma2_decode_buffer(decoder, input.as_ptr(), input.len(), &mut block) },
118 LEONIDA_XMA2_OK
119 );
120 assert!(!block.is_null());
121 let samples = unsafe { leonida_xma2_pcm_sample_count(block) };
122 assert!(samples > 0);
123 let pcm = unsafe { leonida_xma2_pcm_data(block) };
124 assert!(!pcm.is_null());
125 assert!(unsafe { std::slice::from_raw_parts(pcm, samples) }
126 .iter()
127 .all(|sample| *sample == 0));
128
129 unsafe {
130 leonida_xma2_pcm_destroy(block);
131 leonida_xma2_decoder_destroy(decoder);
132 }
133}
134
135#[test]
136fn decode_rejects_nulls_and_non_packet_aligned_buffers() {
137 let decoder = make_decoder(44_100, 1);
138 let packet = [0u8; PACKET_BYTES];
139 let mut block = ptr::dangling_mut::<LeonidaXma2PcmBlock>();
140
141 assert_eq!(
142 unsafe { leonida_xma2_decode_buffer(decoder, packet.as_ptr(), 0, &mut block) },
143 LEONIDA_XMA2_BAD_PACKET_SIZE
144 );
145 assert!(block.is_null());
146
147 assert_eq!(
148 unsafe {
149 leonida_xma2_decode_buffer(decoder, packet.as_ptr(), PACKET_BYTES - 1, &mut block)
150 },
151 LEONIDA_XMA2_BAD_PACKET_SIZE
152 );
153 assert!(block.is_null());
154
155 assert_eq!(
156 unsafe { leonida_xma2_decode_buffer(decoder, ptr::null(), PACKET_BYTES, &mut block) },
157 LEONIDA_XMA2_INVALID_ARGUMENT
158 );
159 assert!(block.is_null());
160
161 unsafe { leonida_xma2_decoder_destroy(decoder) };
162}
163
164#[test]
165fn deterministic_synthetic_packets_do_not_unwind_across_ffi() {
166 let decoder = make_decoder(48_000, 2);
167 for seed in 1..17u32 {
168 let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1);
169 let mut packet = [0u8; PACKET_BYTES];
170 for byte in &mut packet {
171 state ^= state << 13;
172 state ^= state >> 17;
173 state ^= state << 5;
174 *byte = state as u8;
175 }
176
177 let mut block = ptr::null_mut();
178 let result = unsafe {
179 leonida_xma2_decode_buffer(decoder, packet.as_ptr(), packet.len(), &mut block)
180 };
181 assert!(
182 result == LEONIDA_XMA2_OK
183 || result == LEONIDA_XMA2_DECODER_FAILURE
184 || result == LEONIDA_XMA2_PANIC,
185 "unexpected status {result}"
186 );
187 if !block.is_null() {
188 unsafe { leonida_xma2_pcm_destroy(block) };
189 }
190 }
191
192 unsafe { leonida_xma2_decoder_destroy(decoder) };
193}
194
195#[test]
196fn multiple_packet_buffer_matches_serial_decoder_calls() {
197 let decoder = make_decoder(48_000, 2);
198 let packet = synthetic_silent_packet(2);
199 let mut input = [0u8; PACKET_BYTES * 3];
200 input[PACKET_BYTES..PACKET_BYTES * 2].copy_from_slice(&packet);
201 input[PACKET_BYTES * 2..].copy_from_slice(&packet);
202
203 let mut reference = Xma2Stream::new(48_000, 2).unwrap();
204 let mut expected = Vec::new();
205 for packet in input.as_chunks::<PACKET_BYTES>().0 {
206 reference.decode_packet(packet, &mut expected);
207 }
208
209 let mut block = ptr::null_mut();
210 assert_eq!(
211 unsafe { leonida_xma2_decode_buffer(decoder, input.as_ptr(), input.len(), &mut block) },
212 LEONIDA_XMA2_OK
213 );
214 assert!(!block.is_null());
215 let samples = unsafe { leonida_xma2_pcm_sample_count(block) };
216 assert!(samples > 0);
217 assert_eq!(samples, expected.len());
218 assert_eq!(samples % 2, 0);
219 let pcm = unsafe { leonida_xma2_pcm_data(block) };
220 let actual = unsafe { std::slice::from_raw_parts(pcm, samples) };
221 assert_eq!(actual, expected.as_slice());
222
223 unsafe {
224 leonida_xma2_pcm_destroy(block);
225 leonida_xma2_decoder_destroy(decoder);
226 }
227}
diff --git a/runtime/xma_decoder/tests/ffi_cpp_smoke.cpp b/runtime/xma_decoder/tests/ffi_cpp_smoke.cpp
new file mode 100644
index 000000000..cb41c81f5
--- /dev/null
+++ b/runtime/xma_decoder/tests/ffi_cpp_smoke.cpp
@@ -0,0 +1,87 @@
1#include "../leonida_xma2_decoder.h"
2
3#include <algorithm>
4#include <array>
5#include <cstdint>
6#include <cstdio>
7#include <cstdlib>
8
9void check(bool condition, const char* expression, int line) {
10 if (!condition) {
11 std::fprintf(stderr, "ffi_cpp_smoke.cpp:%d: %s\n", line, expression);
12 std::exit(EXIT_FAILURE);
13 }
14}
15
16#define CHECK(condition) check((condition), #condition, __LINE__)
17
18template <size_t Size>
19void put_bits(std::array<uint8_t, Size>& bytes, size_t& position, uint32_t width,
20 uint32_t value) {
21 for (uint32_t bit = width; bit > 0; --bit, ++position) {
22 if (((value >> (bit - 1)) & 1u) != 0) {
23 bytes[position / 8] |= static_cast<uint8_t>(1u << (7 - (position % 8)));
24 }
25 }
26}
27
28std::array<uint8_t, LEONIDA_XMA2_PACKET_BYTES> make_silent_stereo_packet() {
29 std::array<uint8_t, LEONIDA_XMA2_PACKET_BYTES> packet{};
30 constexpr uint32_t frame_bits = 36;
31 size_t position = 0;
32 put_bits(packet, position, 6, 1);
33 put_bits(packet, position, 15, frame_bits);
34 put_bits(packet, position, 3, 1);
35 put_bits(packet, position, 8, 0);
36 put_bits(packet, position, 15, frame_bits);
37 put_bits(packet, position, 1, 1); // Fixed-size tile header.
38 put_bits(packet, position, 1, 0); // One full-length subframe.
39 put_bits(packet, position, 1, 0); // No optional stereo decorrelation matrix.
40 put_bits(packet, position, 8, 0); // No dynamic range adjustment.
41 put_bits(packet, position, 1, 0); // No trim metadata.
42 put_bits(packet, position, 1, 0); // No fill data.
43 put_bits(packet, position, 1, 0); // No corrupt-subframe marker.
44 put_bits(packet, position, 1, 0); // No stereo transform error.
45 put_bits(packet, position, 1, 1); // Two-channel group without decorrelation.
46 put_bits(packet, position, 1, 0);
47 put_bits(packet, position, 2, 0); // No transmitted coefficients: silence.
48 put_bits(packet, position, 1, 0); // Frame alignment bit.
49 put_bits(packet, position, 1, 0); // No additional frame in this packet.
50 CHECK(position == 32 + frame_bits);
51 return packet;
52}
53
54int main() {
55 LeonidaXma2Decoder* decoder = nullptr;
56 CHECK(leonida_xma2_decoder_create(48000, 2, &decoder) == LEONIDA_XMA2_OK);
57 CHECK(decoder != nullptr);
58
59 const auto packet = make_silent_stereo_packet();
60 std::array<uint8_t, LEONIDA_XMA2_PACKET_BYTES * 3> input{};
61 std::copy(packet.begin(), packet.end(), input.begin() + LEONIDA_XMA2_PACKET_BYTES);
62 std::copy(packet.begin(), packet.end(), input.begin() + LEONIDA_XMA2_PACKET_BYTES * 2);
63 LeonidaXma2PcmBlock* pcm = nullptr;
64 CHECK(leonida_xma2_decode_buffer(decoder, input.data(), input.size(), &pcm) ==
65 LEONIDA_XMA2_OK);
66 CHECK(pcm != nullptr);
67 const size_t samples = leonida_xma2_pcm_sample_count(pcm);
68 CHECK(samples > 0);
69 CHECK(samples % 2 == 0);
70 const int16_t* data = leonida_xma2_pcm_data(pcm);
71 CHECK(data != nullptr);
72
73 LeonidaXma2PcmBlock* invalid = reinterpret_cast<LeonidaXma2PcmBlock*>(1);
74 CHECK(leonida_xma2_decode_buffer(decoder, input.data(), input.size() - 1, &invalid) ==
75 LEONIDA_XMA2_BAD_PACKET_SIZE);
76 CHECK(invalid == nullptr);
77
78 leonida_xma2_decoder_destroy(decoder);
79 CHECK(leonida_xma2_pcm_sample_count(pcm) == samples);
80 CHECK(leonida_xma2_pcm_data(pcm) == data);
81 for (size_t i = 0; i < samples; ++i) {
82 CHECK(data[i] == 0);
83 }
84 leonida_xma2_pcm_destroy(pcm);
85 leonida_xma2_decoder_destroy(nullptr);
86 return 0;
87}