#![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::ffi::c_void; use std::sync::Mutex; use std::sync::atomic::{AtomicI32, AtomicU32, Ordering}; use super::xasync::E_INVALIDARG; use super::xgameruntime::{HRESULT, S_OK}; use crate::hle::{HleModule}; use crate::hle_export; mod convolve; fn convolve_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var_os("EONACAT_XS_DSP_CONVOLVE").is_none_or(|v| v != "0")) } const GAIN: f32 = 2.0; fn gain() -> f32 { static GAIN_SET: std::sync::OnceLock = std::sync::OnceLock::new(); *GAIN_SET.get_or_init(|| { std::env::var("EONACAT_XS_DSP_GAIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(GAIN) }) } const E_POINTER: HRESULT = 0x8000_4003_u32 as i32; const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; const CONVOLUTION: u32 = 1; const STEREO_OPTIONS: u32 = 2 | 8; const NOT_FOR_CONVOLUTION: u32 = 4; pub struct Dsp { max_streams: u32, active: Mutex, } #[repr(C, packed)] pub struct StreamDesc { kind: u32, options: u32, frames: u32, channels: u32, ir_floats: u32, ir: *const f32, } #[repr(C)] pub struct Status { submitted: AtomicU32, completed: AtomicU32, reserved: AtomicU32, result: AtomicI32, } const _: () = { assert!(size_of::() == 16); assert!(align_of::() == 4); assert!(std::mem::offset_of!(Status, submitted) == 0); assert!(std::mem::offset_of!(Status, completed) == 4); assert!(std::mem::offset_of!(Status, reserved) == 8); assert!(std::mem::offset_of!(Status, result) == 12); }; struct SubmitState { last: u32, convolver: Option, } pub struct Stream { dsp: *mut Dsp, frames: u32, channels: u32, submit: Mutex, status: Box, } #[repr(C)] pub struct Command { gains: [f32; 2], input: *const f32, output: *mut f32, reserved: u64, } pub extern "system" fn XDspConnectWithMaximumStreamLimit( base: *mut c_void, base_length: u32, ir_seconds: u32, max_streams: u32, max_channels: u32, out: *mut *mut Dsp, ) -> HRESULT { if base.is_null() || !(0x1_0000..=0x1F40_0000).contains(&base_length) || ir_seconds > 0x80 || max_streams > 0x100 || max_channels > 2 { return E_INVALIDARG; } if out.is_null() { return E_POINTER; } tracing::info!( base_length, ir_seconds, max_streams, max_channels, "audio DSP connected" ); let dsp = Box::new(Dsp { max_streams, active: Mutex::new(0), }); unsafe { out.write(Box::into_raw(dsp)) }; S_OK } pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT { if dsp.is_null() { return E_INVALIDARG; } drop(unsafe { Box::from_raw(dsp) }); S_OK } fn valid(desc: &StreamDesc) -> bool { let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels); let shape = if kind == CONVOLUTION { (1..=2).contains(&channels) && matches!(frames, 0x200 | 0x400) && options & NOT_FOR_CONVOLUTION == 0 } else { channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800) }; shape && (options & STEREO_OPTIONS == 0 || channels == 2) } pub extern "system" fn XDspActivate( dsp: *mut Dsp, desc: *const StreamDesc, status: *mut *const Status, stream: *mut *mut Stream, ) -> HRESULT { if status.is_null() || stream.is_null() { return E_POINTER; } if dsp.is_null() || desc.is_null() { return E_INVALIDARG; } let desc = unsafe { &*desc }; if !valid(desc) { return E_INVALIDARG; } let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels); let (ir, ir_floats) = (desc.ir, desc.ir_floats); let convolver = if convolve_on() && kind == CONVOLUTION && channels == 1 && frames == 0x400 && !ir.is_null() { convolve::Convolver::new(unsafe { std::slice::from_raw_parts(ir, ir_floats as usize) }) } else { None }; tracing::debug!( kind, options, frames, channels, ir_floats, computed = convolver.is_some(), "audio DSP stream activated" ); { let dsp = unsafe { &*dsp }; let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner()); if *active >= dsp.max_streams { return E_OUTOFMEMORY; } *active += 1; } let new = Box::new(Stream { dsp, frames: desc.frames, channels: desc.channels, submit: Mutex::new(SubmitState { last: 0, convolver }), status: Box::new(Status { submitted: AtomicU32::new(0), completed: AtomicU32::new(0), reserved: AtomicU32::new(0), result: AtomicI32::new(S_OK), }), }); let raw = Box::into_raw(new); unsafe { status.write(std::ptr::from_ref(&*(*raw).status)); stream.write(raw); } S_OK } pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT { if stream.is_null() { return E_INVALIDARG; } let stream = unsafe { Box::from_raw(stream) }; let dsp = unsafe { &*stream.dsp }; *dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1; S_OK } fn ramp(output: &mut [f32], frames: u32, channels: u32, [begin, end]: [f32; 2]) { if (begin, end) == (1.0, 1.0) || frames == 0 { return; } let step = (end - begin) / frames as f32; let channels = channels.max(1) as usize; for (i, frame) in output.chunks_mut(channels).enumerate() { let scale = begin + i as f32 * step; frame.iter_mut().for_each(|s| *s *= scale); } } pub extern "system" fn XDspSubmitCommand( stream: *mut Stream, command: *const Command, ticket: *mut u32, ) -> HRESULT { if stream.is_null() || command.is_null() { return E_INVALIDARG; } let (stream, command) = unsafe { (&*stream, &*command) }; let mut submit = stream.submit.lock().unwrap_or_else(|e| e.into_inner()); let next = submit.last.wrapping_add(1); submit.last = next; stream.status.submitted.store(next, Ordering::Release); let samples = (stream.frames * stream.channels) as usize; if !command.output.is_null() && !command.input.is_null() && let Some(convolver) = submit.convolver.as_mut() { let (input, output) = unsafe { (std::slice::from_raw_parts(command.input, samples), std::slice::from_raw_parts_mut(command.output, samples)) }; convolver.process(input, output, gain()); ramp(output, stream.frames, stream.channels, command.gains); } else if !command.output.is_null() { unsafe { std::ptr::write_bytes(command.output, 0, samples) }; } stream.status.result.store(S_OK, Ordering::Relaxed); stream.status.completed.store(next, Ordering::Release); drop(submit); if !ticket.is_null() { unsafe { ticket.write(next) }; } S_OK } pub(crate) fn module() -> HleModule { HleModule { name: "dsp", dlls: &["chad.dll"], exports: vec![ hle_export!(XDspConnectWithMaximumStreamLimit), hle_export!(XDspDisconnect), hle_export!(XDspActivate), hle_export!(XDspDeactivate), hle_export!(XDspSubmitCommand), ], } }