Files
EonaCat.XSBox/crates/engine/src/hle/modules/apu.rs
T
EonaCat 49e10bb398
Rust validation / Formatting (push) Failing after 26s
EonaCat/ci-workflows: SonarQube / sonar (push) Successful in 49s
Rust validation / Windows x64 build and tests (push) Canceled after 0s
Initial
2026-12-04 20:15:38 +01:00

615 lines
18 KiB
Rust

#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::alloc::Layout;
use std::collections::VecDeque;
use std::ffi::c_void;
use std::sync::Mutex;
use opus_pure::OpusDecoder;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::Threading::{CreateEventW, SetEvent};
use super::xasync::E_INVALIDARG;
use super::xgameruntime::{HRESULT, S_OK};
use crate::hle::{HleModule};
use crate::hle_export;
const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
const QUEUE_FULL: HRESULT = 0x8AC8_1000_u32 as i32;
pub(crate) const PENDING_RESULTS: HRESULT = 0x8AC8_1001_u32 as i32;
const INVALID_COMMAND: HRESULT = 0x8AC8_1002_u32 as i32;
const INVALID_STREAM: HRESULT = 0x8AC8_1003_u32 as i32;
const ALREADY_ACTIVE: HRESULT = 0x8AC8_1005_u32 as i32;
const BAD_PACKET: HRESULT = 0x8AC8_1008_u32 as i32;
const DECODE_OPUS: u32 = 1;
const DECODE_CONVERT_OPUS: u32 = 2;
const CONVERT_PCM: u32 = 3;
const ACTIVATE: u32 = 1;
const DEACTIVATE: u32 = 2;
const PROCESS: u32 = 3;
const NOTIFY: u32 = 4;
const RESET: u32 = 5;
const SIGNAL: u32 = 1;
const FLUSH: u32 = 2;
const RESET_DECODER: u32 = 4;
const DEINTERLEAVED_INPUT: u32 = 2;
const DEINTERLEAVED_OUTPUT: u32 = 4;
const RESULT_EVENT: u32 = 8;
const MAX_FRAMES: usize = 5760;
#[repr(C)]
pub struct ConnectInput {
process: u32,
streams: u32,
commands_per_stream: u32,
memory: u32,
frames_per_output: u32,
options: u32,
}
#[repr(C)]
pub struct ConnectOutput {
memory: *mut c_void,
result_event: HANDLE,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct CommandId {
kind: u32,
stream: u32,
sequence: u32,
options: u32,
context: u64,
}
#[repr(C, packed)]
struct Activate {
id: CommandId,
channels: u32,
init_length: u32,
init: *const c_void,
start_pitch: f32,
processing_length: u32,
processing: *mut c_void,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
struct Process {
id: CommandId,
pitch_ramp: f32,
target_pitch: f32,
first_frame: u32,
frame_count: u32,
input_length: u32,
input: *const u8,
output_length: u32,
output: *mut u8,
}
#[repr(C, packed)]
#[derive(Clone, Copy)]
pub struct ApuResult {
id: CommandId,
state: u32,
state_data: u64,
usec: u64,
error: HRESULT,
frames: u32,
output_length: u32,
output: *mut u8,
pitch: f32,
input_length: u32,
input: *const u8,
}
unsafe impl Send for ApuResult {}
pub struct Connection {
memory: *mut u8,
layout: Layout,
event: HANDLE,
options: u32,
per_stream: u32,
process: u32,
chunk: usize,
state: Mutex<State>,
}
struct State {
streams: Vec<Option<Stream>>,
queued: Vec<u32>,
results: VecDeque<ApuResult>,
commands: u32,
dequeued: u32,
}
fn lock(c: &Connection) -> std::sync::MutexGuard<'_, State> {
c.state.lock().unwrap_or_else(|e| e.into_inner())
}
pub extern "system" fn XApuConnect(
input: *const ConnectInput,
output: *mut ConnectOutput,
handle: *mut *mut Connection,
) -> HRESULT {
if input.is_null() || output.is_null() || handle.is_null() {
return E_INVALIDARG;
}
let input = unsafe { &*input };
if !(1..=500).contains(&input.streams)
|| !(1..=16).contains(&input.commands_per_stream)
|| input.memory == 0
{
return E_INVALIDARG;
}
match (input.process, input.frames_per_output) {
(DECODE_OPUS, 0) => {}
(DECODE_CONVERT_OPUS | CONVERT_PCM, 256 | 480 | 512 | 960 | 1024) => {}
(DECODE_OPUS | DECODE_CONVERT_OPUS | CONVERT_PCM, _) => return E_INVALIDARG,
(process, _) => {
tracing::warn!(process, "audio decoder: unknown processing kind");
return E_NOTIMPL;
}
}
let Ok(layout) = Layout::from_size_align(input.memory as usize, 16) else {
return E_INVALIDARG;
};
let memory = unsafe { std::alloc::alloc_zeroed(layout) };
if memory.is_null() {
return E_OUTOFMEMORY;
}
let event = if input.options & RESULT_EVENT != 0 {
let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) };
if event.is_null() {
unsafe { std::alloc::dealloc(memory, layout) };
return E_OUTOFMEMORY;
}
event
} else {
std::ptr::null_mut()
};
let streams = input.streams as usize;
tracing::info!(
streams,
memory = input.memory,
options = input.options,
"audio decoder connected"
);
let connection = Box::new(Connection {
memory,
layout,
event,
options: input.options,
per_stream: input.commands_per_stream,
process: input.process,
chunk: input.frames_per_output as usize,
state: Mutex::new(State {
streams: (0..streams).map(|_| None).collect(),
queued: vec![0; streams],
results: VecDeque::new(),
commands: 0,
dequeued: 0,
}),
});
unsafe {
output.write(ConnectOutput {
memory: memory.cast(),
result_event: event,
});
handle.write(Box::into_raw(connection));
}
S_OK
}
pub extern "system" fn XApuDisconnect(handle: *mut Connection) -> HRESULT {
if handle.is_null() {
return E_INVALIDARG;
}
let connection = unsafe { Box::from_raw(handle) };
if !connection.event.is_null() {
unsafe { CloseHandle(connection.event) };
}
unsafe { std::alloc::dealloc(connection.memory, connection.layout) };
S_OK
}
pub extern "system" fn XApuEnqueueCommand(
handle: *mut Connection,
command: *const CommandId,
total: *mut u32,
) -> HRESULT {
if handle.is_null() || command.is_null() {
return E_INVALIDARG;
}
let (connection, id) = unsafe { (&*handle, command.read_unaligned()) };
let mut state = lock(connection);
let stream = id.stream as usize;
if stream >= state.streams.len() {
return INVALID_STREAM;
}
if state.queued[stream] >= connection.per_stream {
return QUEUE_FULL;
}
let mut result = ApuResult {
id,
state: 0,
state_data: 0,
usec: 0,
error: S_OK,
frames: 0,
output_length: 0,
output: std::ptr::null_mut(),
pitch: 1.0,
input_length: 0,
input: std::ptr::null(),
};
let slot = &mut state.streams[stream];
match id.kind {
ACTIVATE => {
let activate = unsafe { command.cast::<Activate>().read_unaligned() };
let (channels, start_pitch) = (activate.channels, activate.start_pitch);
tracing::debug!(stream, channels, process = connection.process, "audio stream activated");
result.error = if slot.is_some() {
ALREADY_ACTIVE
} else {
match Stream::new(connection.process, channels, start_pitch) {
Some(s) => {
*slot = Some(s);
S_OK
}
None => E_INVALIDARG,
}
};
}
DEACTIVATE => {
*slot = None;
#[cfg(feature = "diagnostics")]
opus_log(handle, stream, None);
}
RESET => {
if let Some(s) = slot {
s.reset(id.options & RESET_DECODER != 0);
}
}
NOTIFY => {}
PROCESS => {
let command = unsafe { command.cast::<Process>().read_unaligned() };
match slot {
Some(Stream { decoder: Some(d), converter: None, .. }) => {
process(d, connection.options, &command, &mut result);
}
Some(s) => s.convert(connection, &command, &mut result),
None => result.error = INVALID_STREAM,
}
#[cfg(feature = "diagnostics")]
opus_log(handle, stream, Some(result.frames));
}
_ => return INVALID_COMMAND,
}
state.queued[stream] += 1;
state.commands = state.commands.wrapping_add(1);
state.results.push_back(result);
if !total.is_null() {
unsafe { total.write(state.commands) };
}
if id.options & SIGNAL != 0 && !connection.event.is_null() {
unsafe { SetEvent(connection.event) };
}
S_OK
}
struct Stream {
decoder: Option<OpusDecoder>,
converter: Option<Converter>,
}
impl Stream {
fn new(process: u32, channels: u32, start_pitch: f32) -> Option<Stream> {
if !(1..=2).contains(&channels) {
return None;
}
let channels = channels as usize;
let decoder = match process {
CONVERT_PCM => None,
_ => Some(OpusDecoder::new(48_000, channels).ok()?),
};
let converter = (process != DECODE_OPUS).then(|| Converter::new(channels, start_pitch));
Some(Stream { decoder, converter })
}
fn reset(&mut self, decoder_only: bool) {
if let Some(d) = &mut self.decoder {
let _ = d.reset_state();
}
if let Some(c) = &mut self.converter
&& !decoder_only
{
c.reset();
}
}
fn convert(&mut self, connection: &Connection, command: &Process, result: &mut ApuResult) {
let Some(converter) = &mut self.converter else {
result.error = INVALID_STREAM;
return;
};
let channels = converter.channels;
let (input, input_length) = (command.input, command.input_length);
let (output, output_length) = (command.output, command.output_length);
(result.input, result.input_length, result.output) = (input, input_length, output);
if input.is_null() || output.is_null() {
result.error = E_INVALIDARG;
return;
}
let bytes = unsafe { std::slice::from_raw_parts(input, input_length as usize) };
let frames: Vec<f32> = match &mut self.decoder {
Some(decoder) => {
let mut pcm = vec![0f32; MAX_FRAMES * channels];
let Ok(decoded) = decoder.decode(bytes, MAX_FRAMES, &mut pcm) else {
result.error = BAD_PACKET;
return;
};
let first = (command.first_frame as usize).min(decoded);
let count = (decoded - first).min(command.frame_count as usize);
pcm[first * channels..(first + count) * channels].to_vec()
}
None => {
let samples: Vec<f32> = bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect();
let count = samples.len() / channels;
if connection.options & DEINTERLEAVED_INPUT != 0 && channels == 2 {
(0..count).flat_map(|i| [samples[i], samples[count + i]]).collect()
} else {
samples[..count * channels].to_vec()
}
}
};
let unconverted_before = converter.input.len() / channels;
converter.input.extend_from_slice(&frames);
let used = converter.run(command.target_pitch, command.pitch_ramp);
let used_here = used.min(unconverted_before + frames.len() / channels);
let chunk = connection.chunk;
let deinterleaved = connection.options & DEINTERLEAVED_OUTPUT != 0 && channels == 2;
let ready = converter.output.len() / channels;
let flush = command.id.options & FLUSH != 0;
let mut give = if ready >= chunk { chunk } else if flush { ready } else { 0 };
let room = output_length as usize / 4;
give = give.min(if deinterleaved { room.saturating_sub(chunk).min(chunk) } else { room / channels });
let out: Vec<f32> = converter.output.drain(..give * channels).collect();
let write = |at: usize, v: f32| unsafe { output.add(at * 4).cast::<[u8; 4]>().write_unaligned(v.to_le_bytes()) };
for i in 0..give {
if deinterleaved {
write(i, out[2 * i]);
write(chunk + i, out[2 * i + 1]);
} else {
for c in 0..channels {
write(i * channels + c, out[i * channels + c]);
}
}
}
let left = converter.output.len() / channels;
result.frames = give as u32;
result.output_length = match (give, deinterleaved) {
(0, _) => 0,
(_, true) => ((chunk + give) * 4) as u32,
_ => (give * channels * 4) as u32,
};
result.pitch = converter.pitch;
result.state = (u32::from(give > 0) * OUTPUT_READY)
| if left >= chunk { MORE_OUTPUT_AVAILABLE } else { NEED_MORE_INPUT };
let kept = (converter.input.len() / channels) as u64;
result.state_data = (left as u64).min(0xffff) | (used_here as u64).min(0xffff) << 16 | kept.min(0xffff) << 48;
}
}
const OUTPUT_READY: u32 = 1;
const NEED_MORE_INPUT: u32 = 2;
const MORE_OUTPUT_AVAILABLE: u32 = 4;
const PITCHES: std::ops::RangeInclusive<f32> = 0.125..=8.0;
struct Converter {
channels: usize,
start_pitch: f32,
pitch: f32,
input: Vec<f32>,
pos: f64,
output: VecDeque<f32>,
}
impl Converter {
fn new(channels: usize, start_pitch: f32) -> Converter {
let start_pitch = if start_pitch.is_finite() { start_pitch.clamp(*PITCHES.start(), *PITCHES.end()) } else { 1.0 };
Converter { channels, start_pitch, pitch: start_pitch, input: Vec::new(), pos: 0.0, output: VecDeque::new() }
}
fn reset(&mut self) {
*self = Converter::new(self.channels, self.start_pitch);
}
fn run(&mut self, target: f32, ramp: f32) -> usize {
let channels = self.channels;
let frames = self.input.len() / channels;
let target = if target.is_finite() { target.clamp(*PITCHES.start(), *PITCHES.end()) } else { self.pitch };
let ramp = ramp.abs();
while (self.pos as usize) + 1 < frames {
let i = self.pos as usize;
let t = (self.pos - i as f64) as f32;
for c in 0..channels {
let (a, b) = (self.input[i * channels + c], self.input[(i + 1) * channels + c]);
self.output.push_back(a + (b - a) * t);
}
self.pos += f64::from(self.pitch);
self.pitch = if ramp == 0.0 {
target
} else if self.pitch < target {
(self.pitch + ramp).min(target)
} else {
(self.pitch - ramp).max(target)
};
}
let used = (self.pos as usize).min(frames);
self.input.drain(..used * channels);
self.pos -= used as f64;
used
}
}
#[cfg(feature = "diagnostics")]
fn opus_log(connection: *const Connection, stream: usize, frames: Option<u32>) {
use std::collections::BTreeMap;
use std::time::Instant;
type Log = (Option<Instant>, BTreeMap<(usize, usize), u64>);
static LOG: Mutex<Log> = Mutex::new((None, BTreeMap::new()));
let Some(ms) = super::audio::voice_log_ms() else {
return;
};
let mut log = LOG.lock().unwrap_or_else(|e| e.into_inner());
let key = (connection as usize, stream);
let Some(frames) = frames else {
log.1.remove(&key);
return;
};
*log.1.entry(key).or_default() += u64::from(frames);
if log.0.is_some_and(|t| t.elapsed().as_millis() < ms) {
return;
}
log.0 = Some(Instant::now());
for (&(connection, stream), &frames) in &log.1 {
tracing::info!(
connection = format_args!("{connection:#x}"),
stream,
frames,
"Opus stream position"
);
}
}
fn process(decoder: &mut OpusDecoder, options: u32, command: &Process, result: &mut ApuResult) {
let channels = decoder.channels();
let (input, input_length) = (command.input, command.input_length);
let (output, output_length) = (command.output, command.output_length);
result.input = input;
result.input_length = input_length;
result.output = output;
if input.is_null() || output.is_null() || input_length == 0 {
result.error = E_INVALIDARG;
return;
}
let packet = unsafe { std::slice::from_raw_parts(input, input_length as usize) };
let mut pcm = vec![0f32; MAX_FRAMES * channels];
let decoded = match decoder.decode(packet, MAX_FRAMES, &mut pcm) {
Ok(n) => n,
Err(_) => {
result.error = BAD_PACKET;
return;
}
};
let first = (command.first_frame as usize).min(decoded);
let frames = (decoded - first)
.min(command.frame_count as usize)
.min(output_length as usize / (4 * channels));
let kept = &pcm[first * channels..(first + frames) * channels];
let bytes = frames * channels * 4;
if bytes > 0 {
let out = unsafe { std::slice::from_raw_parts_mut(output, bytes) };
if options & DEINTERLEAVED_OUTPUT != 0 && channels == 2 {
let (left, right) = out.split_at_mut(frames * 4);
let (left, _) = left.as_chunks_mut::<4>();
let (right, _) = right.as_chunks_mut::<4>();
for (i, frame) in kept.as_chunks::<2>().0.iter().enumerate() {
left[i] = frame[0].to_le_bytes();
right[i] = frame[1].to_le_bytes();
}
} else {
for (dst, &sample) in out.as_chunks_mut::<4>().0.iter_mut().zip(kept) {
*dst = sample.to_le_bytes();
}
}
}
result.frames = frames as u32;
result.output_length = bytes as u32;
}
pub extern "system" fn XApuDequeueResult(handle: *mut Connection, out: *mut ApuResult) -> HRESULT {
if handle.is_null() || out.is_null() {
return E_INVALIDARG;
}
let mut state = lock(unsafe { &*handle });
let Some(result) = state.results.pop_front() else {
return PENDING_RESULTS;
};
let stream = result.id.stream as usize;
state.queued[stream] -= 1;
state.dequeued = state.dequeued.wrapping_add(1);
unsafe { out.write_unaligned(result) };
S_OK
}
pub extern "system" fn XApuGetResultCount(handle: *mut Connection, total: *mut u32) -> u32 {
if handle.is_null() {
return 0;
}
let state = lock(unsafe { &*handle });
if !total.is_null() {
unsafe { total.write(state.dequeued) };
}
state.results.len() as u32
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "apu",
dlls: &["xapu.dll"],
exports: vec![
hle_export!(XApuConnect),
hle_export!(XApuDisconnect),
hle_export!(XApuEnqueueCommand),
hle_export!(XApuDequeueResult),
hle_export!(XApuGetResultCount),
],
}
}