dsp.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. //! The console's audio DSP (`chad.dll`): streams that convolve blocks of
  2. //! float samples with an impulse response (reverb), or run other block
  3. //! transforms, on a coprocessor.
  4. //!
  5. //! A title connects once with a memory block for the DSP, activates
  6. //! streams, and submits one command per block (gains, an input and an
  7. //! output buffer). Activation hands back a status block whose second word is
  8. //! the ticket of the last completed command and whose fourth is its result;
  9. //! the title checks it one block later and treats a late command as an
  10. //! overrun. Commands complete when submitted here.
  11. //!
  12. //! The transforms themselves are not computed: the hardware takes impulse
  13. //! responses already in its own partitioned frequency-domain layout, which
  14. //! is not known. Outputs are silence, so reverb returns are dry.
  15. // shortcut: no convolution or block transform; outputs are zeros. Needs the
  16. // coprocessor's impulse response and spectrum layouts to do better.
  17. #![allow(non_snake_case)]
  18. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  19. use std::ffi::c_void;
  20. use std::sync::Mutex;
  21. use super::xasync::E_INVALIDARG;
  22. use super::xgameruntime::{HRESULT, S_OK};
  23. use crate::{HleModule, hle_export};
  24. const E_POINTER: HRESULT = 0x8000_4003_u32 as i32;
  25. const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
  26. const CONVOLUTION: u32 = 1;
  27. /// Option bits that need a stereo stream, and one convolution refuses.
  28. const STEREO_OPTIONS: u32 = 2 | 8;
  29. const NOT_FOR_CONVOLUTION: u32 = 4;
  30. pub struct Dsp {
  31. max_streams: u32,
  32. active: Mutex<u32>,
  33. }
  34. /// What activation describes.
  35. #[repr(C, packed)]
  36. pub struct StreamDesc {
  37. kind: u32,
  38. options: u32,
  39. frames: u32,
  40. channels: u32,
  41. ir_floats: u32,
  42. ir: *const f32,
  43. }
  44. /// The status block a stream's owner polls.
  45. #[repr(C)]
  46. pub struct Status {
  47. submitted: u32,
  48. completed: u32,
  49. reserved: u32,
  50. result: HRESULT,
  51. }
  52. pub struct Stream {
  53. dsp: *mut Dsp,
  54. frames: u32,
  55. channels: u32,
  56. status: Box<Status>,
  57. }
  58. /// One block of work.
  59. #[repr(C)]
  60. pub struct Command {
  61. gains: [f32; 2],
  62. input: *const f32,
  63. output: *mut f32,
  64. reserved: u64,
  65. }
  66. pub extern "system" fn XDspConnectWithMaximumStreamLimit(
  67. base: *mut c_void,
  68. base_length: u32,
  69. ir_seconds: u32,
  70. max_streams: u32,
  71. max_channels: u32,
  72. out: *mut *mut Dsp,
  73. ) -> HRESULT {
  74. if base.is_null()
  75. || !(0x1_0000..=0x1F40_0000).contains(&base_length)
  76. || ir_seconds > 0x80
  77. || max_streams > 0x100
  78. || max_channels > 2
  79. {
  80. return E_INVALIDARG;
  81. }
  82. if out.is_null() {
  83. return E_POINTER;
  84. }
  85. tracing::info!(
  86. base_length,
  87. ir_seconds,
  88. max_streams,
  89. max_channels,
  90. "audio DSP connected"
  91. );
  92. let dsp = Box::new(Dsp {
  93. max_streams,
  94. active: Mutex::new(0),
  95. });
  96. // SAFETY: checked non-null.
  97. unsafe { out.write(Box::into_raw(dsp)) };
  98. S_OK
  99. }
  100. pub extern "system" fn XDspDisconnect(dsp: *mut Dsp) -> HRESULT {
  101. if dsp.is_null() {
  102. return E_INVALIDARG;
  103. }
  104. // SAFETY: made by `XDspConnectWithMaximumStreamLimit`; disconnected
  105. // once, after its streams.
  106. drop(unsafe { Box::from_raw(dsp) });
  107. S_OK
  108. }
  109. fn valid(desc: &StreamDesc) -> bool {
  110. let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
  111. let shape = if kind == CONVOLUTION {
  112. (1..=2).contains(&channels)
  113. && matches!(frames, 0x200 | 0x400)
  114. && options & NOT_FOR_CONVOLUTION == 0
  115. } else {
  116. channels == 1 && matches!(frames, 0x200 | 0x400 | 0x800)
  117. };
  118. shape && (options & STEREO_OPTIONS == 0 || channels == 2)
  119. }
  120. pub extern "system" fn XDspActivate(
  121. dsp: *mut Dsp,
  122. desc: *const StreamDesc,
  123. status: *mut *const Status,
  124. stream: *mut *mut Stream,
  125. ) -> HRESULT {
  126. if status.is_null() || stream.is_null() {
  127. return E_POINTER;
  128. }
  129. if dsp.is_null() || desc.is_null() {
  130. return E_INVALIDARG;
  131. }
  132. // SAFETY: checked non-null; the title passes its description.
  133. let desc = unsafe { &*desc };
  134. if !valid(desc) {
  135. return E_INVALIDARG;
  136. }
  137. let (kind, options, frames, channels) = (desc.kind, desc.options, desc.frames, desc.channels);
  138. tracing::debug!(
  139. kind,
  140. options,
  141. frames,
  142. channels,
  143. "audio DSP stream activated"
  144. );
  145. {
  146. // SAFETY: a connection from `XDspConnectWithMaximumStreamLimit`.
  147. let dsp = unsafe { &*dsp };
  148. let mut active = dsp.active.lock().unwrap_or_else(|e| e.into_inner());
  149. if *active >= dsp.max_streams {
  150. return E_OUTOFMEMORY;
  151. }
  152. *active += 1;
  153. }
  154. let new = Box::new(Stream {
  155. dsp,
  156. frames: desc.frames,
  157. channels: desc.channels,
  158. status: Box::new(Status {
  159. submitted: 0,
  160. completed: 0,
  161. reserved: 0,
  162. result: S_OK,
  163. }),
  164. });
  165. // SAFETY: checked non-null.
  166. unsafe {
  167. status.write(&*new.status);
  168. stream.write(Box::into_raw(new));
  169. }
  170. S_OK
  171. }
  172. pub extern "system" fn XDspDeactivate(stream: *mut Stream) -> HRESULT {
  173. if stream.is_null() {
  174. return E_INVALIDARG;
  175. }
  176. // SAFETY: made by `XDspActivate`; deactivated once.
  177. let stream = unsafe { Box::from_raw(stream) };
  178. // SAFETY: the connection outlives its streams.
  179. let dsp = unsafe { &*stream.dsp };
  180. *dsp.active.lock().unwrap_or_else(|e| e.into_inner()) -= 1;
  181. S_OK
  182. }
  183. /// Completes the command at once: its output block is silence.
  184. pub extern "system" fn XDspSubmitCommand(
  185. stream: *mut Stream,
  186. command: *const Command,
  187. ticket: *mut u32,
  188. ) -> HRESULT {
  189. if stream.is_null() || command.is_null() {
  190. return E_INVALIDARG;
  191. }
  192. // SAFETY: a stream from `XDspActivate`, the title's command.
  193. let (stream, command) = unsafe { (&mut *stream, &*command) };
  194. if !command.output.is_null() {
  195. let samples = (stream.frames * stream.channels) as usize;
  196. // SAFETY: the title's output buffer holds one block of the stream.
  197. unsafe { std::ptr::write_bytes(command.output, 0, samples) };
  198. }
  199. let status = &mut *stream.status;
  200. let next = status.submitted.wrapping_add(1);
  201. // SAFETY: the status block is read by title code on other threads.
  202. unsafe {
  203. std::ptr::write_volatile(&mut status.submitted, next);
  204. std::ptr::write_volatile(&mut status.result, S_OK);
  205. std::ptr::write_volatile(&mut status.completed, next);
  206. }
  207. if !ticket.is_null() {
  208. // SAFETY: optional out parameter.
  209. unsafe { ticket.write(next) };
  210. }
  211. S_OK
  212. }
  213. pub(crate) fn module() -> HleModule {
  214. HleModule {
  215. name: "dsp",
  216. dlls: &["chad.dll"],
  217. exports: vec![
  218. hle_export!(XDspConnectWithMaximumStreamLimit),
  219. hle_export!(XDspDisconnect),
  220. hle_export!(XDspActivate),
  221. hle_export!(XDspDeactivate),
  222. hle_export!(XDspSubmitCommand),
  223. ],
  224. }
  225. }
  226. #[cfg(test)]
  227. mod tests {
  228. use super::*;
  229. #[test]
  230. fn convolution_stream_as_the_title_drives_it() {
  231. let mut base = vec![0u8; 0x10_0000];
  232. let mut dsp = std::ptr::null_mut();
  233. assert_eq!(
  234. XDspConnectWithMaximumStreamLimit(
  235. base.as_mut_ptr().cast(),
  236. 0x10_0000,
  237. 24,
  238. 0x80,
  239. 1,
  240. &mut dsp
  241. ),
  242. S_OK
  243. );
  244. let ir = vec![0f32; 0x800];
  245. // Stereo convolution with option 2, as the title asks for.
  246. let desc = StreamDesc {
  247. kind: CONVOLUTION,
  248. options: 2,
  249. frames: 0x400,
  250. channels: 2,
  251. ir_floats: 0x800,
  252. ir: ir.as_ptr(),
  253. };
  254. let (mut status, mut stream) = (std::ptr::null(), std::ptr::null_mut());
  255. assert_eq!(XDspActivate(dsp, &desc, &mut status, &mut stream), S_OK);
  256. let mut output = vec![1f32; 0x800];
  257. let input = vec![0.5f32; 0x800];
  258. let command = Command {
  259. gains: [1.0, 1.0],
  260. input: input.as_ptr(),
  261. output: output.as_mut_ptr(),
  262. reserved: 0,
  263. };
  264. let mut ticket = 0;
  265. assert_eq!(XDspSubmitCommand(stream, &command, &mut ticket), S_OK);
  266. // SAFETY: the stream's status block.
  267. let (completed, result) = unsafe { ((*status).completed, (*status).result) };
  268. assert_eq!((completed, result), (ticket, S_OK));
  269. assert!(output.iter().all(|&s| s == 0.0));
  270. assert_eq!(XDspDeactivate(stream), S_OK);
  271. // Mono streams refuse stereo options; transforms are mono only.
  272. let bad = StreamDesc {
  273. channels: 1,
  274. ..desc
  275. };
  276. assert_eq!(
  277. XDspActivate(dsp, &bad, &mut status, &mut stream),
  278. E_INVALIDARG
  279. );
  280. let transform = StreamDesc {
  281. kind: 2,
  282. options: 0,
  283. channels: 1,
  284. ir_floats: 0,
  285. ir: std::ptr::null(),
  286. ..desc
  287. };
  288. assert_eq!(
  289. XDspActivate(dsp, &transform, &mut status, &mut stream),
  290. S_OK
  291. );
  292. assert_eq!(XDspDeactivate(stream), S_OK);
  293. assert_eq!(XDspDisconnect(dsp), S_OK);
  294. }
  295. }