upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/xma_decoder/src
diff options
context:
space:
mode:
authoredupode <30982306+edupode@users.noreply.github.com>2026-11-23 15:54:45 +0000
committerGitHub <noreply@github.com>2026-11-23 09:54:45 -0600
commit8714c3503bc49b72f79909338684c41cb1282e84 (patch)
tree89fb5655a682e28518b4a02cb33e7d20ec6f38bf /runtime/xma_decoder/src
parentabb7f4401c91a2dcdfb4f570f9dbad139302eafb (diff)
[RT-197] Add the XMA2 decoder C ABI boundary (#3441)
Squash-merged after diff review of PR #3441
Diffstat (limited to 'runtime/xma_decoder/src')
-rw-r--r--runtime/xma_decoder/src/lib.rs263
1 files changed, 263 insertions, 0 deletions
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}