upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/xma_decoder/src/lib.rs
blob: 69fedf49e00e697cc45367f4f040e42ada4f0d10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#![deny(unsafe_op_in_unsafe_fn)]

use std::alloc::Layout;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::ptr;
use std::slice;
use std::sync::Mutex;

use xma::{Xma2Stream, XMA_FRAME_SAMPLES, XMA_PACKET_BYTES};

pub const LEONIDA_XMA2_OK: i32 = 0;
pub const LEONIDA_XMA2_INVALID_ARGUMENT: i32 = 1;
pub const LEONIDA_XMA2_INVALID_FORMAT: i32 = 2;
pub const LEONIDA_XMA2_BAD_PACKET_SIZE: i32 = 3;
pub const LEONIDA_XMA2_OUT_OF_MEMORY: i32 = 4;
pub const LEONIDA_XMA2_DECODER_FAILURE: i32 = 5;
pub const LEONIDA_XMA2_PANIC: i32 = 6;

const MAX_FRAMES_PER_PACKET: usize = 64;

#[repr(C)]
pub struct LeonidaXma2Decoder {
    stream: Mutex<Xma2Stream>,
    channels: usize,
}

#[repr(C)]
pub struct LeonidaXma2PcmBlock {
    samples: Vec<i16>,
}

#[cfg(not(test))]
use std::alloc::alloc as allocate_handle;
#[cfg(test)]
use tests::allocate_handle;

fn try_new_handle<T>(value: T) -> Result<Box<T>, i32> {
    const { assert!(std::mem::size_of::<T>() > 0) };
    // Both the allocation and Box's eventual deallocation use the global allocator
    // with T's exact layout. Initialize the storage before handing it to Box.
    let storage = unsafe { allocate_handle(Layout::new::<T>()) }.cast::<T>();
    if storage.is_null() {
        return Err(LEONIDA_XMA2_OUT_OF_MEMORY);
    }
    unsafe {
        storage.write(value);
        Ok(Box::from_raw(storage))
    }
}

/// Creates a decoder for one mono or stereo XMA2 stream.
///
/// # Safety
/// `out_decoder` must be writable for one pointer. The returned decoder must be destroyed once,
/// after all calls using it have finished.
#[no_mangle]
pub unsafe extern "C" fn leonida_xma2_decoder_create(
    sample_rate: u32,
    channels: u32,
    out_decoder: *mut *mut LeonidaXma2Decoder,
) -> i32 {
    unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new) }
}

/// Like `leonida_xma2_decoder_create`, but decodes like the console's XMA hardware: the first
/// frame is kept and there is no 64-sample start skip; the caller applies the context's skip.
/// # Safety
/// Same as `leonida_xma2_decoder_create`.
#[no_mangle]
pub unsafe extern "C" fn leonida_xma2_decoder_create_hardware(
    sample_rate: u32,
    channels: u32,
    out_decoder: *mut *mut LeonidaXma2Decoder,
) -> i32 {
    unsafe { create_with(sample_rate, channels, out_decoder, Xma2Stream::new_hardware) }
}

unsafe fn create_with<E>(
    sample_rate: u32,
    channels: u32,
    out_decoder: *mut *mut LeonidaXma2Decoder,
    make: impl FnOnce(u32, usize) -> Result<Xma2Stream, E>,
) -> i32 {
    if out_decoder.is_null() {
        return LEONIDA_XMA2_INVALID_ARGUMENT;
    }
    unsafe { *out_decoder = ptr::null_mut() };
    if sample_rate == 0 || !(channels == 1 || channels == 2) {
        return LEONIDA_XMA2_INVALID_FORMAT;
    }

    match catch_unwind(AssertUnwindSafe(|| {
        let stream =
            make(sample_rate, channels as usize).map_err(|_| LEONIDA_XMA2_INVALID_FORMAT)?;
        try_new_handle(LeonidaXma2Decoder {
            stream: Mutex::new(stream),
            channels: channels as usize,
        })
    })) {
        Ok(Ok(decoder)) => {
            unsafe { *out_decoder = Box::into_raw(decoder) };
            LEONIDA_XMA2_OK
        }
        Ok(Err(status)) => status,
        Err(_) => LEONIDA_XMA2_PANIC,
    }
}

/// Decodes a buffer containing one or more complete 2048-byte XMA2 packets.
///
/// # Safety
/// `decoder` must be a live handle returned by `leonida_xma2_decoder_create`
/// or `leonida_xma2_decoder_create_hardware`.
/// `input` must reference `input_len` readable bytes and `out_block` must be writable.
/// Do not destroy a decoder concurrently with this call. The returned PCM block remains valid
/// until `leonida_xma2_pcm_destroy` is called.
#[no_mangle]
pub unsafe extern "C" fn leonida_xma2_decode_buffer(
    decoder: *mut LeonidaXma2Decoder,
    input: *const u8,
    input_len: usize,
    out_block: *mut *mut LeonidaXma2PcmBlock,
) -> i32 {
    if out_block.is_null() {
        return LEONIDA_XMA2_INVALID_ARGUMENT;
    }
    unsafe { *out_block = ptr::null_mut() };

    if decoder.is_null() || input.is_null() || input_len > isize::MAX as usize {
        return LEONIDA_XMA2_INVALID_ARGUMENT;
    }
    if input_len == 0 || !input_len.is_multiple_of(XMA_PACKET_BYTES) {
        return LEONIDA_XMA2_BAD_PACKET_SIZE;
    }

    let decoded = catch_unwind(AssertUnwindSafe(|| {
        let handle = unsafe { &*decoder };
        let bytes = unsafe { slice::from_raw_parts(input, input_len) };
        let mut stream = handle
            .stream
            .lock()
            .map_err(|_| LEONIDA_XMA2_DECODER_FAILURE)?;
        let max_packet_samples = MAX_FRAMES_PER_PACKET
            .checked_mul(XMA_FRAME_SAMPLES)
            .and_then(|samples| samples.checked_mul(handle.channels))
            .ok_or(LEONIDA_XMA2_INVALID_ARGUMENT)?;
        let mut block = try_new_handle(LeonidaXma2PcmBlock {
            samples: Vec::new(),
        })?;
        let samples = &mut block.samples;

        let (packets, _) = bytes.as_chunks::<XMA_PACKET_BYTES>();
        for packet in packets {
            let requested = samples
                .len()
                .checked_add(max_packet_samples)
                .ok_or(LEONIDA_XMA2_INVALID_ARGUMENT)?;
            if requested > isize::MAX as usize / std::mem::size_of::<i16>() {
                return Err(LEONIDA_XMA2_INVALID_ARGUMENT);
            }
            samples
                .try_reserve(max_packet_samples)
                .map_err(|_| LEONIDA_XMA2_OUT_OF_MEMORY)?;
            stream.decode_packet(packet, samples);
        }

        if !samples.len().is_multiple_of(handle.channels) {
            return Err(LEONIDA_XMA2_DECODER_FAILURE);
        }
        Ok(block)
    }));

    match decoded {
        Ok(Ok(block)) => {
            unsafe { *out_block = Box::into_raw(block) };
            LEONIDA_XMA2_OK
        }
        Ok(Err(status)) => status,
        Err(_) => LEONIDA_XMA2_PANIC,
    }
}

/// Destroys a decoder. Passing null is a no-op.
///
/// # Safety
/// A non-null pointer must be a live handle returned by `leonida_xma2_decoder_create`
/// or `leonida_xma2_decoder_create_hardware`. No calls may be using it concurrently.
#[no_mangle]
pub unsafe extern "C" fn leonida_xma2_decoder_destroy(decoder: *mut LeonidaXma2Decoder) {
    if !decoder.is_null() {
        unsafe { drop(Box::from_raw(decoder)) };
    }
}

/// Returns the immutable interleaved signed-16 PCM pointer for a block.
///
/// # Safety
/// A non-null pointer must be a live block returned by `leonida_xma2_decode_buffer`.
/// The returned pointer is valid only until the block is destroyed.
#[no_mangle]
pub unsafe extern "C" fn leonida_xma2_pcm_data(block: *const LeonidaXma2PcmBlock) -> *const i16 {
    unsafe { block.as_ref() }.map_or(ptr::null(), |pcm| pcm.samples.as_ptr())
}

/// Returns the number of signed-16 samples in a block.
///
/// # Safety
/// A non-null pointer must be a live block returned by `leonida_xma2_decode_buffer`.
#[no_mangle]
pub unsafe extern "C" fn leonida_xma2_pcm_sample_count(block: *const LeonidaXma2PcmBlock) -> usize {
    unsafe { block.as_ref() }.map_or(0, |pcm| pcm.samples.len())
}

/// Destroys a PCM block. Passing null is a no-op.
///
/// # Safety
/// A non-null pointer must be a live block returned by `leonida_xma2_decode_buffer`.
#[no_mangle]
pub unsafe extern "C" fn leonida_xma2_pcm_destroy(block: *mut LeonidaXma2PcmBlock) {
    if !block.is_null() {
        unsafe { drop(Box::from_raw(block)) };
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;

    thread_local! {
        static FAIL_NEXT_HANDLE_ALLOCATION: Cell<bool> = const { Cell::new(false) };
    }

    pub(super) unsafe fn allocate_handle(layout: Layout) -> *mut u8 {
        if FAIL_NEXT_HANDLE_ALLOCATION.replace(false) {
            ptr::null_mut()
        } else {
            unsafe { std::alloc::alloc(layout) }
        }
    }

    #[test]
    fn decoder_handle_allocation_failure_clears_output() {
        let mut decoder = ptr::dangling_mut();
        FAIL_NEXT_HANDLE_ALLOCATION.set(true);
        let status = unsafe { leonida_xma2_decoder_create(48_000, 2, &mut decoder) };
        assert_eq!(status, LEONIDA_XMA2_OUT_OF_MEMORY);
        assert!(decoder.is_null());

        assert_eq!(
            unsafe { leonida_xma2_decoder_create(48_000, 2, &mut decoder) },
            LEONIDA_XMA2_OK
        );
        assert!(!decoder.is_null());
        unsafe { leonida_xma2_decoder_destroy(decoder) };
    }

    #[test]
    fn create_hardware_accepts_stereo_and_rejects_three_channels() {
        let mut decoder = ptr::null_mut();
        assert_eq!(
            unsafe { leonida_xma2_decoder_create_hardware(48_000, 2, &mut decoder) },
            LEONIDA_XMA2_OK
        );
        assert!(!decoder.is_null());
        unsafe { leonida_xma2_decoder_destroy(decoder) };

        let mut decoder = ptr::dangling_mut();
        assert_eq!(
            unsafe { leonida_xma2_decoder_create_hardware(48_000, 3, &mut decoder) },
            LEONIDA_XMA2_INVALID_FORMAT
        );
        assert!(decoder.is_null());
    }

    #[test]
    fn pcm_handle_allocation_failure_clears_output_and_allows_retry() {
        let mut decoder = ptr::null_mut();
        assert_eq!(
            unsafe { leonida_xma2_decoder_create(48_000, 2, &mut decoder) },
            LEONIDA_XMA2_OK
        );
        let packet = [0u8; XMA_PACKET_BYTES];
        let mut block = ptr::dangling_mut();
        FAIL_NEXT_HANDLE_ALLOCATION.set(true);
        let status = unsafe {
            leonida_xma2_decode_buffer(decoder, packet.as_ptr(), packet.len(), &mut block)
        };
        assert_eq!(status, LEONIDA_XMA2_OUT_OF_MEMORY);
        assert!(block.is_null());

        assert_eq!(
            unsafe {
                leonida_xma2_decode_buffer(decoder, packet.as_ptr(), packet.len(), &mut block)
            },
            LEONIDA_XMA2_OK
        );
        assert!(!block.is_null());
        unsafe {
            leonida_xma2_pcm_destroy(block);
            leonida_xma2_decoder_destroy(decoder);
        }
    }
}