audio.rs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. //! The console's audio hardware (`AcpHal.dll`):
  2. //!
  3. //! * the APU heap: host memory with 32-bit device addresses;
  4. //! * SHAPE context arrays allocated from it;
  5. //! * the audio coprocessor's command and message queues, where every
  6. //! command completes at once and is acknowledged as the hardware would;
  7. //! * the XMA decoder: enabled XMA contexts are decoded on a thread of ours
  8. //! into their output rings, like the hardware does.
  9. //!
  10. //! SHAPE's other units (rate conversion, EQ, filters, mixing through
  11. //! flowgraphs) are not emulated, so voices that need them stay silent.
  12. //! Mixed audio leaves through the host's WASAPI, which titles and
  13. //! middleware reach through COM like on PC. fmod's console build sets up
  14. //! the coprocessor inside `System_Create` and waits there for its first
  15. //! command to be acknowledged; the title uses only XMA contexts.
  16. #![allow(non_snake_case)]
  17. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  18. use std::alloc::Layout;
  19. use std::collections::{BTreeMap, VecDeque};
  20. use std::ffi::c_void;
  21. use std::sync::{Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard};
  22. use std::time::Instant;
  23. use super::xasync::E_INVALIDARG;
  24. use super::xgameruntime::{HRESULT, S_OK};
  25. use crate::{HleModule, hle_export};
  26. #[cfg(all(windows, feature = "diagnostics"))]
  27. pub mod capture;
  28. const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
  29. const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
  30. fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
  31. m.lock().unwrap_or_else(|e| e.into_inner())
  32. }
  33. // The APU heap.
  34. struct Block {
  35. size: usize,
  36. apu: u32,
  37. layout: Layout,
  38. }
  39. struct Heap {
  40. /// By host address.
  41. blocks: BTreeMap<usize, Block>,
  42. /// Host address by device address.
  43. by_apu: BTreeMap<u32, usize>,
  44. /// Free device address ranges, start to end, merged with neighbours.
  45. free: BTreeMap<u32, u32>,
  46. /// Set by `ApuCreateHeap` or the first allocation: the heap exists.
  47. created: bool,
  48. }
  49. static HEAP: Mutex<Heap> = Mutex::new(Heap {
  50. blocks: BTreeMap::new(),
  51. by_apu: BTreeMap::new(),
  52. free: BTreeMap::new(),
  53. created: false,
  54. });
  55. /// Device addresses start above 0, which means "none" to titles.
  56. const APU_BASE: u32 = 0x0001_0000;
  57. impl Heap {
  58. /// First fit in the free ranges.
  59. fn take(&mut self, size: u32, align: u32) -> Option<u32> {
  60. if self.free.is_empty() && !self.created {
  61. self.free.insert(APU_BASE, u32::MAX);
  62. }
  63. self.created = true;
  64. let (start, end, apu) = self.free.iter().find_map(|(&start, &end)| {
  65. let apu = start.checked_next_multiple_of(align)?;
  66. (apu.checked_add(size)? <= end).then_some((start, end, apu))
  67. })?;
  68. self.free.remove(&start);
  69. if start < apu {
  70. self.free.insert(start, apu);
  71. }
  72. if apu + size < end {
  73. self.free.insert(apu + size, end);
  74. }
  75. Some(apu)
  76. }
  77. fn give_back(&mut self, mut start: u32, mut end: u32) {
  78. if let Some((&before, &before_end)) = self.free.range(..start).next_back()
  79. && before_end == start
  80. {
  81. self.free.remove(&before);
  82. start = before;
  83. }
  84. if let Some(after_end) = self.free.remove(&end) {
  85. end = after_end;
  86. }
  87. self.free.insert(start, end);
  88. }
  89. }
  90. /// Zeroed host memory and its device address.
  91. fn heap_alloc(size: usize, align: usize) -> Option<(*mut u8, u32)> {
  92. let layout = Layout::from_size_align(size.max(1), align.max(16)).ok()?;
  93. let mut heap = lock(&HEAP);
  94. let apu = heap.take(u32::try_from(layout.size()).ok()?, align as u32)?;
  95. // SAFETY: non-zero size.
  96. let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
  97. if ptr.is_null() {
  98. heap.give_back(apu, apu + layout.size() as u32);
  99. return None;
  100. }
  101. heap.blocks
  102. .insert(ptr as usize, Block { size, apu, layout });
  103. heap.by_apu.insert(apu, ptr as usize);
  104. // The big ones are named in the log: they are the title's audio memory
  105. // given out of our allocator, which the memory line counts as ours.
  106. if size >= 32 << 20 {
  107. tracing::info!(mb = size >> 20, at = ?ptr, "audio memory for the title from our allocator");
  108. }
  109. Some((ptr, apu))
  110. }
  111. fn heap_free(ptr: *mut u8) {
  112. let mut heap = lock(&HEAP);
  113. let Some(block) = heap.blocks.remove(&(ptr as usize)) else {
  114. return;
  115. };
  116. heap.by_apu.remove(&block.apu);
  117. heap.give_back(block.apu, block.apu + block.layout.size() as u32);
  118. drop(heap);
  119. // SAFETY: allocated by `heap_alloc` with this layout.
  120. unsafe { std::alloc::dealloc(ptr, block.layout) };
  121. }
  122. /// Sizes the heap once, before anything is allocated from it. The console
  123. /// reserves both parts up front; we allocate per block, so the sizes only
  124. /// decide whether the call is valid.
  125. // shortcut: the cached and non-cached sizes are not enforced as limits;
  126. // enforce them if a title relies on running out.
  127. pub extern "system" fn ApuCreateHeap(cached: u32, _non_cached: u32) -> HRESULT {
  128. const ALREADY_ALLOCATED: HRESULT = 0x8ACA_0001_u32 as i32;
  129. if cached == 0 {
  130. return E_INVALIDARG;
  131. }
  132. let mut heap = lock(&HEAP);
  133. if heap.created {
  134. return ALREADY_ALLOCATED;
  135. }
  136. heap.created = true;
  137. heap.free.insert(APU_BASE, u32::MAX);
  138. S_OK
  139. }
  140. /// The host address of a device address, null outside the heap.
  141. pub extern "system" fn ApuMapApuAddress(apu: u32) -> *mut c_void {
  142. heap_unmap(apu).map_or(std::ptr::null_mut(), |p| p.cast())
  143. }
  144. /// The device address of any byte of a heap block, 0 elsewhere.
  145. fn heap_map(ptr: usize) -> u32 {
  146. let heap = lock(&HEAP);
  147. match heap.blocks.range(..=ptr).next_back() {
  148. Some((&start, block)) if ptr < start + block.size.max(1) => {
  149. block.apu + (ptr - start) as u32
  150. }
  151. _ => 0,
  152. }
  153. }
  154. /// The host address of a device address, if a heap block holds it.
  155. fn heap_unmap(apu: u32) -> Option<*mut u8> {
  156. let heap = lock(&HEAP);
  157. let (&start, &host) = heap.by_apu.range(..=apu).next_back()?;
  158. let block = &heap.blocks[&host];
  159. (apu < start.saturating_add(block.size.max(1) as u32))
  160. .then(|| (host + (apu - start) as usize) as *mut u8)
  161. }
  162. /// `len` bytes of title memory at a device address, if one heap block holds
  163. /// them all.
  164. fn heap_bytes<'a>(apu: u32, len: usize) -> Option<&'a mut [u8]> {
  165. let heap = lock(&HEAP);
  166. let (&start, &host) = heap.by_apu.range(..=apu).next_back()?;
  167. let offset = (apu - start) as usize;
  168. (offset + len <= heap.blocks[&host].size)
  169. // SAFETY: inside a live heap block, which the title and the audio
  170. // hardware share like on the console.
  171. .then(|| unsafe { std::slice::from_raw_parts_mut((host + offset) as *mut u8, len) })
  172. }
  173. pub extern "system" fn ApuAlloc(
  174. out: *mut *mut c_void,
  175. apu: *mut u32,
  176. size: u32,
  177. align: u32,
  178. _flags: u32,
  179. ) -> HRESULT {
  180. if out.is_null() || size == 0 || align < 4 || !align.is_power_of_two() {
  181. return E_INVALIDARG;
  182. }
  183. let Some((ptr, address)) = heap_alloc(size as usize, align as usize) else {
  184. return E_OUTOFMEMORY;
  185. };
  186. // SAFETY: checked non-null; optional out parameter checked below.
  187. unsafe {
  188. out.write(ptr.cast());
  189. if !apu.is_null() {
  190. apu.write(address);
  191. }
  192. }
  193. S_OK
  194. }
  195. pub extern "system" fn ApuFree(ptr: *mut c_void) {
  196. heap_free(ptr.cast());
  197. }
  198. pub extern "system" fn ApuMapVirtualAddress(ptr: *const c_void) -> u32 {
  199. heap_map(ptr as usize)
  200. }
  201. pub extern "system" fn ApuIsVirtualAddressValid(ptr: *const c_void, align: u32) -> bool {
  202. let apu = heap_map(ptr as usize);
  203. apu != 0 && (align == 0 || apu.is_multiple_of(align))
  204. }
  205. // SHAPE context arrays.
  206. /// Six counts (rate conversion, EQ/compression, filter/volume, DMA, XMA,
  207. /// PCM), then the six arrays and their device addresses.
  208. #[repr(C, packed)]
  209. pub struct ShapeContexts {
  210. counts: [u32; 6],
  211. arrays: [*mut c_void; 6],
  212. apu: [u32; 6],
  213. }
  214. /// Bytes per context: rate conversion, DMA and XMA as fmod clears them;
  215. /// the others (not seen yet) get a generous upper bound.
  216. const CONTEXT_BYTES: [usize; 6] = [32, 256, 256, 16, 64, 256];
  217. static CONTEXTS: Mutex<Option<[usize; 6]>> = Mutex::new(None);
  218. pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts) -> HRESULT {
  219. if contexts.is_null() {
  220. return E_INVALIDARG;
  221. }
  222. let mut allocated = lock(&CONTEXTS);
  223. if allocated.is_some() {
  224. return E_FAIL;
  225. }
  226. // SAFETY: the title passes its request; packed fields are copied out.
  227. let counts = unsafe { std::ptr::addr_of!((*contexts).counts).read_unaligned() };
  228. let mut arrays: [*mut c_void; 6] = [std::ptr::null_mut(); 6];
  229. let mut addresses = [0u32; 6];
  230. for i in 0..6 {
  231. if counts[i] == 0 {
  232. continue;
  233. }
  234. let Some((ptr, apu)) = heap_alloc(counts[i] as usize * CONTEXT_BYTES[i], 256) else {
  235. arrays.iter().for_each(|&p| heap_free(p.cast()));
  236. return E_OUTOFMEMORY;
  237. };
  238. (arrays[i], addresses[i]) = (ptr.cast(), apu);
  239. }
  240. // SAFETY: as above.
  241. unsafe {
  242. std::ptr::addr_of_mut!((*contexts).arrays).write_unaligned(arrays);
  243. std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses);
  244. }
  245. *allocated = Some(arrays.map(|p| p as usize));
  246. let mut xma = XMA.write().unwrap_or_else(|e| e.into_inner());
  247. xma.array = arrays[4] as usize;
  248. xma.voices = (0..counts[4]).map(|_| Mutex::new(None)).collect();
  249. S_OK
  250. }
  251. pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT {
  252. match lock(&CONTEXTS).take() {
  253. Some(arrays) => {
  254. *XMA.write().unwrap_or_else(|e| e.into_inner()) = Xma::EMPTY;
  255. arrays.iter().for_each(|&p| heap_free(p as *mut u8));
  256. S_OK
  257. }
  258. None => E_FAIL,
  259. }
  260. }
  261. // The XMA decoder.
  262. //
  263. // An XMA context (16 words in the shared context array) names up to two
  264. // input buffers of 2 KiB packets, a ring of 256-byte output blocks the
  265. // hardware fills with 16-bit PCM, and the read offset the title advances
  266. // by command. Words and bit fields, as titles write them:
  267. // 0: input 0 size in packets (0-11), loop count (12-19, 255 forever),
  268. // valid inputs (20-21), output size in blocks (22-26), write block
  269. // (27-31, hardware);
  270. // 1: input 1 size (0-11), loop end subframe (12-13), loop start subframes
  271. // to skip (17-19), subframes to skip at the start (24-26), sample rate
  272. // (27-28: 24, 32, 44.1, 48 kHz), stereo (29), output writable (31);
  273. // 2: read position in bits (0-25), error status (26-30), error (31);
  274. // 3: loop start in bits (0-25); 4: loop end in bits (0-25), current input
  275. // (31); 5, 6: input addresses; 7: output address; 8: overlap buffer;
  276. // 9: read block (0-4).
  277. // Titles read back only the write block, "writable" and the read block,
  278. // and take whatever lies between read and write.
  279. // shortcut: each enabled context decodes from a cold state and the overlap
  280. // buffer is ignored (titles copy it between consecutive contexts of one
  281. // voice); keep decoder state there if a title's seams turn out audible.
  282. use victory_formats::xma;
  283. const ENABLE_XMA: u32 = 5;
  284. const ENABLE_XMAS: u32 = 6;
  285. const DISABLE_XMA: u32 = 7;
  286. const DISABLE_XMAS: u32 = 8;
  287. const ADVANCE_XMA_READ: u32 = 18;
  288. const BLOCK_BYTES: usize = 256;
  289. const SAMPLES_PER_BLOCK: usize = BLOCK_BYTES / 2;
  290. /// Error status: the input ran out.
  291. const INPUT_INVALID: u32 = 4;
  292. struct Voice {
  293. decoder: Option<xma::Decoder>,
  294. pcm: VecDeque<i16>,
  295. /// Samples per channel still to drop (start or loop subframe skips).
  296. skip: usize,
  297. ended: bool,
  298. trace: Trace,
  299. }
  300. /// What a voice did, for the debug log when it is disabled.
  301. struct Trace {
  302. since: Instant,
  303. /// Samples per channel written to the ring.
  304. produced: usize,
  305. /// Blocks the title took (command 18), how often, and how often it
  306. /// found the ring less than full.
  307. taken: usize,
  308. takes: u32,
  309. partial_takes: u32,
  310. frames: u32,
  311. bad_frames: u32,
  312. /// The loudest sample written.
  313. peak: i16,
  314. /// Milliseconds after enabling when the input ran out.
  315. ended_ms: Option<u128>,
  316. }
  317. struct Xma {
  318. /// Host address of the context array.
  319. array: usize,
  320. /// One entry per context, `Some` while enabled. Each has its own lock,
  321. /// so a command for one voice never waits for others to decode (the
  322. /// title sends them from its time-critical mixer thread).
  323. voices: Vec<Mutex<Option<Voice>>>,
  324. }
  325. impl Xma {
  326. const EMPTY: Xma = Xma {
  327. array: 0,
  328. voices: Vec::new(),
  329. };
  330. }
  331. /// Written only when the context arrays are allocated or released.
  332. static XMA: RwLock<Xma> = RwLock::new(Xma::EMPTY);
  333. fn xma() -> RwLockReadGuard<'static, Xma> {
  334. XMA.read().unwrap_or_else(|e| e.into_inner())
  335. }
  336. /// A context's words in title memory.
  337. #[derive(Clone, Copy)]
  338. struct Context(*mut u32);
  339. impl Context {
  340. fn get(self, word: usize) -> u32 {
  341. // SAFETY: inside the context array; the title reads and writes it
  342. // concurrently, like the hardware's.
  343. unsafe { self.0.add(word).read_volatile() }
  344. }
  345. fn set(self, word: usize, value: u32) {
  346. // SAFETY: as above.
  347. unsafe { self.0.add(word).write_volatile(value) }
  348. }
  349. fn field(self, word: usize, shift: u32, bits: u32) -> u32 {
  350. (self.get(word) >> shift) & ((1 << bits) - 1)
  351. }
  352. fn set_field(self, word: usize, shift: u32, bits: u32, value: u32) {
  353. let mask = ((1u32 << bits) - 1) << shift;
  354. self.set(word, (self.get(word) & !mask) | ((value << shift) & mask));
  355. }
  356. fn channels(self) -> usize {
  357. 1 + self.field(1, 29, 1) as usize
  358. }
  359. }
  360. impl Xma {
  361. fn context(&self, index: u32) -> Option<Context> {
  362. ((index as usize) < self.voices.len() && self.array != 0)
  363. .then(|| Context((self.array + index as usize * 64) as *mut u32))
  364. }
  365. fn enable(&self, index: u32) {
  366. let Some(context) = self.context(index) else {
  367. return;
  368. };
  369. let mut slot = lock(&self.voices[index as usize]);
  370. context.set_field(2, 26, 6, 0);
  371. tracing::debug!(
  372. index,
  373. words = ?(0..10).map(|w| format!("{:08x}", context.get(w))).collect::<Vec<_>>(),
  374. "XMA voice enabled"
  375. );
  376. #[cfg(feature = "diagnostics")]
  377. dump_input(index, context);
  378. *slot = Some(Voice {
  379. decoder: None,
  380. pcm: VecDeque::new(),
  381. skip: context.field(1, 24, 3) as usize * xma::SUBFRAME_SAMPLES,
  382. ended: false,
  383. trace: Trace {
  384. since: Instant::now(),
  385. produced: 0,
  386. taken: 0,
  387. takes: 0,
  388. partial_takes: 0,
  389. frames: 0,
  390. bad_frames: 0,
  391. peak: 0,
  392. ended_ms: None,
  393. },
  394. });
  395. drop(slot);
  396. wake_decoder();
  397. }
  398. fn disable(&self, index: u32) {
  399. let Some(context) = self.context(index) else {
  400. return;
  401. };
  402. let Some(voice) = lock(&self.voices[index as usize]).take() else {
  403. return;
  404. };
  405. let t = &voice.trace;
  406. tracing::debug!(
  407. index,
  408. ms = t.since.elapsed().as_millis(),
  409. produced = t.produced,
  410. taken = t.taken * SAMPLES_PER_BLOCK / context.channels(),
  411. takes = t.takes,
  412. partial_takes = t.partial_takes,
  413. frames = t.frames,
  414. bad_frames = t.bad_frames,
  415. peak = t.peak,
  416. input_ended_ms = ?t.ended_ms,
  417. read_bit = context.field(2, 0, 26),
  418. input_bits = context.field(0, 0, 12) * xma::PACKET_BYTES as u32 * 8,
  419. "XMA voice disabled"
  420. );
  421. }
  422. /// Moves the title's read block on, which frees output space.
  423. fn advance_read(&self, index: u32, blocks: u32) {
  424. let Some(context) = self.context(index) else {
  425. return;
  426. };
  427. // The decoder writes the same words.
  428. let mut slot = lock(&self.voices[index as usize]);
  429. let size = context.field(0, 22, 5).max(1);
  430. // The count is the title's: reduced first, so the sum stays small.
  431. let read = (context.field(9, 0, 5) + blocks % size) % size;
  432. context.set_field(9, 0, 5, read);
  433. if blocks > 0 {
  434. context.set_field(1, 31, 1, 1);
  435. }
  436. if let Some(voice) = &mut *slot {
  437. let t = &mut voice.trace;
  438. t.taken += blocks as usize;
  439. t.takes += 1;
  440. t.partial_takes += u32::from(blocks < size);
  441. }
  442. drop(slot);
  443. wake_decoder();
  444. }
  445. /// Fills every enabled context's output as far as it has room.
  446. fn pump(&self) {
  447. let start = Instant::now();
  448. let mut active = 0;
  449. for index in 0..self.voices.len() as u32 {
  450. if let (Some(context), Some(voice)) =
  451. (self.context(index), &mut *lock(&self.voices[index as usize]))
  452. {
  453. pump(context, voice);
  454. active += 1;
  455. }
  456. }
  457. let took = start.elapsed();
  458. if took.as_millis() >= 4 {
  459. tracing::debug!(active, ms = took.as_millis(), "slow XMA decoding pass");
  460. }
  461. }
  462. }
  463. fn pump(context: Context, voice: &mut Voice) {
  464. let size = context.field(0, 22, 5);
  465. if size == 0 {
  466. return;
  467. }
  468. while context.field(1, 31, 1) == 1 {
  469. if voice.pcm.len() < SAMPLES_PER_BLOCK && !decode(context, voice) {
  470. return;
  471. }
  472. let write = context.field(0, 27, 5);
  473. let address = context.get(7) as usize + write as usize * BLOCK_BYTES;
  474. let Some(out) = heap_bytes(address as u32, BLOCK_BYTES) else {
  475. return;
  476. };
  477. for pair in out.as_chunks_mut::<2>().0 {
  478. let sample = voice.pcm.pop_front().unwrap_or(0);
  479. voice.trace.peak = voice.trace.peak.max(sample.saturating_abs());
  480. pair.copy_from_slice(&sample.to_le_bytes());
  481. }
  482. voice.trace.produced += SAMPLES_PER_BLOCK / context.channels();
  483. let write = (write + 1) % size;
  484. context.set_field(0, 27, 5, write);
  485. if write == context.field(9, 0, 5) {
  486. // Full: nothing more until the title advances its read block.
  487. context.set_field(1, 31, 1, 0);
  488. }
  489. }
  490. }
  491. /// Decodes the next frame of the current input into `voice.pcm`; false
  492. /// when there is nothing left to decode.
  493. fn decode(context: Context, voice: &mut Voice) -> bool {
  494. if voice.ended {
  495. return false;
  496. }
  497. let channels = context.channels();
  498. let mut current = context.field(4, 31, 1);
  499. let valid = context.field(0, 20, 2);
  500. if valid & (1 << current) == 0 {
  501. if valid & (1 << (1 - current)) == 0 {
  502. // Out of input: the overlap tail, then nothing.
  503. if let Some(decoder) = &mut voice.decoder {
  504. let mut tail = Vec::new();
  505. decoder.flush(&mut tail);
  506. voice.pcm.extend(tail);
  507. }
  508. voice.ended = true;
  509. voice.trace.ended_ms = Some(voice.trace.since.elapsed().as_millis());
  510. context.set_field(2, 26, 5, INPUT_INVALID);
  511. context.set_field(2, 31, 1, 1);
  512. return !voice.pcm.is_empty();
  513. }
  514. current = 1 - current;
  515. context.set_field(4, 31, 1, current);
  516. context.set_field(2, 0, 26, 0);
  517. }
  518. let (address, packets) = match current {
  519. 0 => (context.get(5), context.field(0, 0, 12)),
  520. _ => (context.get(6), context.field(1, 0, 12)),
  521. };
  522. let Some(data) = heap_bytes(address & !0x7ff, packets as usize * xma::PACKET_BYTES) else {
  523. context.set_field(0, 20 + current, 1, 0);
  524. return true;
  525. };
  526. let mut at = context.field(2, 0, 26) as usize;
  527. if at < 32 {
  528. at = 32 + xma::packet(data, 0).map_or(0, |p| p.first_frame_bit as usize);
  529. }
  530. let Some(frame) = xma::read_frame(data, at) else {
  531. // This input is used up.
  532. context.set_field(0, 20 + current, 1, 0);
  533. return true;
  534. };
  535. let decoder = voice.decoder.get_or_insert_with(|| {
  536. const RATES: [u32; 4] = [24_000, 32_000, 44_100, 48_000];
  537. xma::Decoder::new(channels, RATES[context.field(1, 27, 2) as usize])
  538. });
  539. let mut pcm = Vec::with_capacity(xma::FRAME_SAMPLES * channels);
  540. voice.trace.frames += 1;
  541. if let Err(e) = decoder.decode(&frame.data, frame.bits, &mut pcm) {
  542. voice.trace.bad_frames += 1;
  543. if voice.trace.bad_frames <= 2 {
  544. tracing::debug!(
  545. at,
  546. bits = frame.bits,
  547. head = ?&frame.data[..frame.data.len().min(8)],
  548. %e,
  549. "XMA frame did not decode"
  550. );
  551. }
  552. }
  553. let mut next = frame.next.unwrap_or(0);
  554. let loops = context.field(0, 12, 8);
  555. let loop_end = context.field(4, 0, 26) as usize;
  556. let ends_loop = loop_end != 0
  557. && (frame.start == loop_end
  558. || (frame.start < loop_end && frame.next.is_none_or(|n| loop_end < n)));
  559. if loops > 0 && ends_loop {
  560. let keep = (context.field(1, 12, 2) as usize + 1) * xma::SUBFRAME_SAMPLES * channels;
  561. pcm.truncate(keep);
  562. next = context.field(3, 0, 26) as usize;
  563. voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES;
  564. if loops != 255 {
  565. context.set_field(0, 12, 8, loops - 1);
  566. }
  567. }
  568. let skip = (voice.skip * channels).min(pcm.len());
  569. voice.skip -= skip / channels;
  570. voice.pcm.extend(&pcm[skip..]);
  571. if next == 0 {
  572. context.set_field(0, 20 + current, 1, 0);
  573. }
  574. context.set_field(2, 0, 26, next as u32);
  575. true
  576. }
  577. /// `VICTORY_XMA_DUMP=<dir>`: saves the context words (`<n>-<index>.ctx`)
  578. /// and input buffer 0 (`.xma`) of the first 32 voices enabled, to test
  579. /// the decoder on a title's streams outside the title.
  580. #[cfg(feature = "diagnostics")]
  581. fn dump_input(index: u32, context: Context) {
  582. static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  583. let Some(dir) = std::env::var_os("VICTORY_XMA_DUMP") else {
  584. return;
  585. };
  586. let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  587. if n >= 32 {
  588. return;
  589. }
  590. let dir = std::path::PathBuf::from(dir);
  591. let words: Vec<u8> = (0..16).flat_map(|w| context.get(w).to_le_bytes()).collect();
  592. let input = heap_bytes(
  593. context.get(5) & !0x7ff,
  594. context.field(0, 0, 12) as usize * xma::PACKET_BYTES,
  595. );
  596. let _ = std::fs::create_dir_all(&dir);
  597. let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words);
  598. let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default());
  599. }
  600. /// Starts the decoding thread on the first enabled voice, and has it fill
  601. /// rings now: a voice just enabled or read from.
  602. fn wake_decoder() {
  603. static DECODER: OnceLock<std::thread::Thread> = OnceLock::new();
  604. DECODER
  605. .get_or_init(|| {
  606. std::thread::Builder::new()
  607. .name("victory XMA decoder".into())
  608. .spawn(|| {
  609. loop {
  610. xma().pump();
  611. // A 256-byte output block lasts 2.7 ms at 48 kHz mono.
  612. std::thread::park_timeout(std::time::Duration::from_millis(2));
  613. }
  614. })
  615. .map_or_else(|_| std::thread::current(), |h| h.thread().clone())
  616. })
  617. .unpark();
  618. }
  619. /// Runs an XMA command; false for one this does not know.
  620. fn xma_command(command: u32, word: impl Fn(usize) -> Option<u32>) -> bool {
  621. let xma = xma();
  622. match command {
  623. ENABLE_XMA => xma.enable(word(0).unwrap_or(u32::MAX)),
  624. DISABLE_XMA => xma.disable(word(0).unwrap_or(u32::MAX)),
  625. ENABLE_XMAS | DISABLE_XMAS => {
  626. for i in 0..xma.voices.len() as u32 {
  627. if word(i as usize / 32).unwrap_or(0) & (1 << (i % 32)) != 0 {
  628. match command {
  629. ENABLE_XMAS => xma.enable(i),
  630. _ => xma.disable(i),
  631. }
  632. }
  633. }
  634. }
  635. ADVANCE_XMA_READ => xma.advance_read(word(0).unwrap_or(u32::MAX), word(1).unwrap_or(0)),
  636. _ => return false,
  637. }
  638. true
  639. }
  640. // The audio coprocessor.
  641. const LOAD_FLOWGRAPH: u32 = 1;
  642. const REGISTER_MESSAGES: u32 = 2;
  643. const UNREGISTER_MESSAGES: u32 = 3;
  644. const FLOWGRAPH_COMPLETED: u32 = 0x02;
  645. const COMMAND_COMPLETED: u32 = 0x10;
  646. const DISCONNECTED: u32 = 0x80;
  647. /// Audio frames of 128 samples at 48 kHz.
  648. const FRAMES_PER_SECOND: u64 = 375;
  649. #[repr(C, packed)]
  650. #[derive(Clone, Copy)]
  651. struct Message {
  652. kind: u32,
  653. dropped: u32,
  654. usec: u32,
  655. data: [u8; 16],
  656. }
  657. struct State {
  658. connected: bool,
  659. /// Message kinds the title registered for.
  660. mask: u32,
  661. messages: VecDeque<Message>,
  662. /// Queue size given to `connect`.
  663. capacity: usize,
  664. /// Messages lost to a full queue since the last one queued.
  665. dropped: u32,
  666. since: Instant,
  667. }
  668. impl State {
  669. fn usec(&self) -> u64 {
  670. self.since.elapsed().as_micros() as u64
  671. }
  672. fn frame(&self) -> u32 {
  673. (self.usec() * FRAMES_PER_SECOND / 1_000_000) as u32
  674. }
  675. /// Queues a registered message; a full queue drops it and counts it in
  676. /// the next one that fits.
  677. fn post(&mut self, kind: u32, data: &[u8]) {
  678. if self.mask & kind == 0 {
  679. return;
  680. }
  681. if self.messages.len() >= self.capacity {
  682. self.dropped = self.dropped.saturating_add(1);
  683. tracing::debug!(kind, dropped = self.dropped, "coprocessor message dropped");
  684. return;
  685. }
  686. let mut message = Message {
  687. kind,
  688. dropped: std::mem::take(&mut self.dropped),
  689. usec: self.usec() as u32,
  690. data: [0; 16],
  691. };
  692. message.data[..data.len()].copy_from_slice(data);
  693. self.messages.push_back(message);
  694. }
  695. }
  696. /// The interface object: its method table, then our state.
  697. #[repr(C)]
  698. pub struct Acp {
  699. vtable: &'static AcpMethods,
  700. state: Mutex<State>,
  701. }
  702. #[repr(C)]
  703. struct AcpMethods {
  704. connect: extern "system" fn(*mut Acp, u32, u32) -> HRESULT,
  705. disconnect: extern "system" fn(*mut Acp) -> HRESULT,
  706. submit: extern "system" fn(*mut Acp, u32, u64, u32, *const c_void, u32) -> HRESULT,
  707. pop_message: extern "system" fn(*mut Acp, *mut Message) -> bool,
  708. message_count: extern "system" fn(*mut Acp) -> u32,
  709. release: extern "system" fn(*mut Acp),
  710. }
  711. static ACP_METHODS: AcpMethods = AcpMethods {
  712. connect,
  713. disconnect,
  714. submit,
  715. pop_message,
  716. message_count,
  717. release,
  718. };
  719. fn state(this: *mut Acp) -> MutexGuard<'static, State> {
  720. // SAFETY: title code calls methods on the object `AcpHalCreate` made,
  721. // which lives until `release`.
  722. lock(unsafe { &(*this).state })
  723. }
  724. extern "system" fn connect(this: *mut Acp, commands: u32, messages: u32) -> HRESULT {
  725. if commands == 0 {
  726. return E_INVALIDARG;
  727. }
  728. let mut state = state(this);
  729. state.connected = true;
  730. state.capacity = messages as usize;
  731. S_OK
  732. }
  733. extern "system" fn disconnect(this: *mut Acp) -> HRESULT {
  734. let mut state = state(this);
  735. if !state.connected {
  736. return E_FAIL;
  737. }
  738. state.post(DISCONNECTED, &[]);
  739. state.connected = false;
  740. S_OK
  741. }
  742. /// Done at once: message registrations take effect, a flowgraph completes
  743. /// unprocessed, a command with an id is acknowledged, and its notification
  744. /// word is set.
  745. extern "system" fn submit(
  746. this: *mut Acp,
  747. command: u32,
  748. id: u64,
  749. _frame: u32,
  750. data: *const c_void,
  751. notification: u32,
  752. ) -> HRESULT {
  753. static SEEN: Mutex<u64> = Mutex::new(0);
  754. if command < 64 && *lock(&SEEN) & 1 << command == 0 {
  755. *lock(&SEEN) |= 1 << command;
  756. tracing::info!(command, "first coprocessor command of this kind");
  757. }
  758. let mut state = state(this);
  759. let word = |at: usize| -> Option<u32> {
  760. // SAFETY: the command's data starts with these u32 fields.
  761. (!data.is_null()).then(|| unsafe { data.cast::<u32>().add(at).read_unaligned() })
  762. };
  763. match command {
  764. REGISTER_MESSAGES => state.mask |= word(0).unwrap_or(0),
  765. UNREGISTER_MESSAGES => state.mask &= !word(0).unwrap_or(0),
  766. LOAD_FLOWGRAPH => {
  767. let flowgraph = word(1).unwrap_or(0);
  768. state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes());
  769. }
  770. _ if xma_command(command, word) => {}
  771. // shortcut: context updates and the other SHAPE units' commands are
  772. // acknowledged but not carried out; add them when a title sends
  773. // them (each kind is logged once above).
  774. _ => {}
  775. }
  776. if id != 0 {
  777. let mut done = [0u8; 16];
  778. done[..4].copy_from_slice(&command.to_le_bytes());
  779. done[4..12].copy_from_slice(&id.to_le_bytes());
  780. done[12..].copy_from_slice(&state.frame().to_le_bytes());
  781. state.post(COMMAND_COMPLETED, &done);
  782. }
  783. if notification != 0
  784. && let Some(word) = heap_unmap(notification)
  785. {
  786. // SAFETY: a u32 in a heap block, which the title reads as volatile.
  787. unsafe { word.cast::<u32>().write_volatile(1) };
  788. }
  789. S_OK
  790. }
  791. extern "system" fn pop_message(this: *mut Acp, out: *mut Message) -> bool {
  792. let Some(message) = state(this).messages.pop_front() else {
  793. return false;
  794. };
  795. if !out.is_null() {
  796. // SAFETY: the title passes room for one message.
  797. unsafe { out.write_unaligned(message) };
  798. }
  799. true
  800. }
  801. extern "system" fn message_count(this: *mut Acp) -> u32 {
  802. state(this).messages.len() as u32
  803. }
  804. extern "system" fn release(this: *mut Acp) {
  805. // SAFETY: made by `AcpHalCreate` with `Box::into_raw`; released once.
  806. drop(unsafe { Box::from_raw(this) });
  807. }
  808. pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT {
  809. if out.is_null() {
  810. return E_INVALIDARG;
  811. }
  812. let acp = Box::new(Acp {
  813. vtable: &ACP_METHODS,
  814. state: Mutex::new(State {
  815. connected: false,
  816. mask: 0,
  817. messages: VecDeque::new(),
  818. capacity: 0,
  819. dropped: 0,
  820. since: Instant::now(),
  821. }),
  822. });
  823. // SAFETY: checked non-null.
  824. unsafe { out.write(Box::into_raw(acp)) };
  825. S_OK
  826. }
  827. pub(crate) fn module() -> HleModule {
  828. HleModule {
  829. name: "audio",
  830. dlls: &["acphal.dll"],
  831. exports: vec![
  832. hle_export!(AcpHalAllocateShapeContexts),
  833. hle_export!(AcpHalReleaseShapeContexts),
  834. hle_export!(AcpHalCreate),
  835. hle_export!(ApuAlloc),
  836. hle_export!(ApuCreateHeap),
  837. hle_export!(ApuFree),
  838. hle_export!(ApuIsVirtualAddressValid),
  839. hle_export!(ApuMapApuAddress),
  840. hle_export!(ApuMapVirtualAddress),
  841. ],
  842. }
  843. }
  844. #[cfg(test)]
  845. mod tests {
  846. use super::*;
  847. #[test]
  848. fn heap_maps_every_byte_of_a_block() {
  849. let _serial = lock(&CONTEXT_TESTS);
  850. let (mut ptr, mut apu) = (std::ptr::null_mut(), 0);
  851. assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 128, 1), S_OK);
  852. assert!(apu != 0 && apu.is_multiple_of(128));
  853. let inner = ptr.cast::<u8>().wrapping_add(0x40).cast_const().cast();
  854. assert_eq!(ApuMapVirtualAddress(inner), apu + 0x40);
  855. assert!(ApuIsVirtualAddressValid(ptr, 128));
  856. assert_eq!(heap_unmap(apu + 4), Some(ptr.cast::<u8>().wrapping_add(4)));
  857. ApuFree(ptr);
  858. assert_eq!(ApuMapVirtualAddress(ptr), 0);
  859. assert_eq!(ApuAlloc(&mut ptr, &mut apu, 0x100, 6, 1), E_INVALIDARG);
  860. }
  861. /// The context arrays and the heap exist once per process: tests that
  862. /// allocate from them run one at a time (a concurrent allocation could
  863. /// take a freed range a test expects back).
  864. static CONTEXT_TESTS: Mutex<()> = Mutex::new(());
  865. #[test]
  866. fn heap_reuses_freed_addresses() {
  867. let _serial = lock(&CONTEXT_TESTS);
  868. let (mut a, mut b, mut c) = (
  869. std::ptr::null_mut(),
  870. std::ptr::null_mut(),
  871. std::ptr::null_mut(),
  872. );
  873. let (mut apu_a, mut apu_b, mut apu_c) = (0, 0, 0);
  874. assert_eq!(ApuAlloc(&mut a, &mut apu_a, 0x1000, 0x1000, 1), S_OK);
  875. assert_eq!(ApuAlloc(&mut b, &mut apu_b, 0x1000, 0x1000, 1), S_OK);
  876. ApuFree(a);
  877. assert_eq!(ApuAlloc(&mut c, &mut apu_c, 0x800, 0x800, 1), S_OK);
  878. // The freed range is free again, whichever part `c` took.
  879. assert!(
  880. lock(&HEAP)
  881. .free
  882. .iter()
  883. .any(|(&s, &e)| s <= apu_a + 0x800 && apu_a + 0x1000 <= e)
  884. || apu_c == apu_a
  885. );
  886. assert_eq!(
  887. ApuMapApuAddress(apu_b + 8),
  888. b.cast::<u8>().wrapping_add(8).cast()
  889. );
  890. assert!(ApuMapApuAddress(0).is_null());
  891. assert_eq!(
  892. ApuCreateHeap(64 << 20, 0),
  893. 0x8ACA_0001_u32 as i32,
  894. "too late"
  895. );
  896. ApuFree(b);
  897. ApuFree(c);
  898. }
  899. /// Two packets of three silent mono frames each: a fixed one-subframe
  900. /// layout, no transmitted coefficients.
  901. fn silent_stream() -> Vec<u8> {
  902. let mut data = vec![0xffu8; 2 * xma::PACKET_BYTES];
  903. let mut put = |at: usize, value: u32, width: usize| {
  904. for i in 0..width {
  905. let (p, bit) = (at + i, (value >> (width - 1 - i)) & 1);
  906. data[p / 8] = (data[p / 8] & !(0x80 >> (p % 8))) | ((bit as u8) << (7 - p % 8));
  907. }
  908. };
  909. for packet in 0..2 {
  910. let base = packet * xma::PACKET_BYTES * 8;
  911. put(base, 3 << 26, 32);
  912. for frame in 0..3 {
  913. let at = base + 32 + frame * 31;
  914. put(at, 31, 15); // length
  915. put(at + 15, 0b10, 2); // fixed layout, one 512-sample subframe
  916. put(at + 17, 0, 8 + 1 + 3 + 2); // gain, no trim, empty subframe
  917. }
  918. }
  919. data
  920. }
  921. #[test]
  922. fn xma_contexts_decode_into_their_output_rings() {
  923. let _serial = lock(&CONTEXT_TESTS);
  924. let mut request = ShapeContexts {
  925. counts: [0, 0, 0, 0, 4, 0],
  926. arrays: [std::ptr::null_mut(); 6],
  927. apu: [0; 6],
  928. };
  929. assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK);
  930. let context = Context(request.arrays[4].cast::<u32>().wrapping_add(16));
  931. let (mut input, mut input_apu) = (std::ptr::null_mut(), 0);
  932. assert_eq!(ApuAlloc(&mut input, &mut input_apu, 0x1000, 0x800, 1), S_OK);
  933. let stream = silent_stream();
  934. // SAFETY: two packets were allocated.
  935. unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), input.cast(), stream.len()) };
  936. let (mut output, mut output_apu) = (std::ptr::null_mut(), 0);
  937. assert_eq!(
  938. ApuAlloc(&mut output, &mut output_apu, 0x400, 0x100, 2),
  939. S_OK
  940. );
  941. // SAFETY: the ring was just allocated.
  942. unsafe { output.cast::<u8>().write_bytes(0x55, 0x400) };
  943. // As the title sets one up: two packets, input 0 valid, a ring of
  944. // four blocks, writable, 48 kHz mono, reading from the first frame.
  945. context.set(0, 2 | 1 << 20 | 4 << 22);
  946. context.set(1, 1 << 31 | 3 << 27);
  947. context.set(2, 32);
  948. context.set(5, input_apu);
  949. context.set(7, output_apu);
  950. let mut acp = std::ptr::null_mut();
  951. assert_eq!(AcpHalCreate(&mut acp), S_OK);
  952. // SAFETY: just created.
  953. let m = unsafe { (*acp).vtable };
  954. assert_eq!((m.connect)(acp, 0x1000, 0x1000), S_OK);
  955. let submit = |command: u32, words: &[u32]| {
  956. assert_eq!(
  957. (m.submit)(acp, command, 0xf1, u32::MAX, words.as_ptr().cast(), 0),
  958. S_OK
  959. );
  960. };
  961. submit(ENABLE_XMA, &[1]);
  962. xma().pump();
  963. // Full: all four blocks written (silence), the write block wrapped
  964. // onto the read block, and the ring no longer writable.
  965. assert_eq!(context.field(0, 27, 5), 0);
  966. assert_eq!(context.field(1, 31, 1), 0);
  967. // SAFETY: the ring.
  968. let ring = unsafe { std::slice::from_raw_parts(output.cast::<u8>(), 0x400) };
  969. assert!(ring.iter().all(|&b| b == 0));
  970. // Read four blocks at a time until the input has run out and the
  971. // ring keeps room (the decoding thread may fill it too).
  972. for _ in 0..20 {
  973. submit(ADVANCE_XMA_READ, &[1, 4]);
  974. xma().pump();
  975. if context.field(2, 31, 1) == 1 && context.field(1, 31, 1) == 1 {
  976. break;
  977. }
  978. }
  979. // Six frames and the flushed tail: 3,328 samples, 26 blocks.
  980. let produced = |x: &Xma| lock(&x.voices[1]).as_ref().map(|v| v.trace.produced);
  981. assert_eq!(produced(&xma()), Some(26 * SAMPLES_PER_BLOCK));
  982. assert_eq!(context.field(0, 20, 2), 0, "input used up");
  983. assert_eq!(context.field(2, 26, 5), INPUT_INVALID);
  984. // A count near `u32::MAX` wraps the read block like any other
  985. // (3 + 0xffff_ffff blocks on a ring of four is block 2); the sum
  986. // used to overflow.
  987. context.set_field(9, 0, 5, 3);
  988. submit(ADVANCE_XMA_READ, &[1, u32::MAX]);
  989. assert_eq!(context.field(9, 0, 5), 2);
  990. submit(DISABLE_XMA, &[1]);
  991. assert_eq!(produced(&xma()), None);
  992. (m.release)(acp);
  993. ApuFree(input);
  994. ApuFree(output);
  995. assert_eq!(AcpHalReleaseShapeContexts(), S_OK);
  996. }
  997. #[test]
  998. fn full_message_queues_count_drops() {
  999. let mut acp = std::ptr::null_mut();
  1000. assert_eq!(AcpHalCreate(&mut acp), S_OK);
  1001. // SAFETY: just created.
  1002. let m = unsafe { (*acp).vtable };
  1003. assert_eq!((m.connect)(acp, 16, 2), S_OK);
  1004. let mask = COMMAND_COMPLETED;
  1005. assert_eq!(
  1006. (m.submit)(
  1007. acp,
  1008. REGISTER_MESSAGES,
  1009. 0,
  1010. u32::MAX,
  1011. (&raw const mask).cast(),
  1012. 0
  1013. ),
  1014. S_OK
  1015. );
  1016. for id in 1..=4 {
  1017. assert_eq!((m.submit)(acp, 12, id, u32::MAX, std::ptr::null(), 0), S_OK);
  1018. }
  1019. assert_eq!((m.message_count)(acp), 2);
  1020. let mut message = Message {
  1021. kind: 0,
  1022. dropped: 0,
  1023. usec: 0,
  1024. data: [0; 16],
  1025. };
  1026. assert!((m.pop_message)(acp, &mut message) && (m.pop_message)(acp, &mut message));
  1027. assert_eq!((m.submit)(acp, 12, 5, u32::MAX, std::ptr::null(), 0), S_OK);
  1028. assert!((m.pop_message)(acp, &mut message));
  1029. let dropped = message.dropped;
  1030. assert_eq!(dropped, 2);
  1031. (m.release)(acp);
  1032. }
  1033. #[test]
  1034. fn startup_as_fmod_does_it() {
  1035. let _serial = lock(&CONTEXT_TESTS);
  1036. // Context arrays: rate conversion, DMA and XMA.
  1037. let mut request = ShapeContexts {
  1038. counts: [0x200, 0, 0, 0x400, 0x200, 0],
  1039. arrays: [std::ptr::null_mut(); 6],
  1040. apu: [0; 6],
  1041. };
  1042. assert_eq!(size_of::<ShapeContexts>(), 0x60);
  1043. assert_eq!(AcpHalAllocateShapeContexts(&mut request), S_OK);
  1044. let arrays = request.arrays;
  1045. assert!(!arrays[0].is_null() && !arrays[3].is_null() && !arrays[4].is_null());
  1046. assert!(arrays[1].is_null());
  1047. // SAFETY: 0x200 rate-conversion contexts of 32 bytes were allocated.
  1048. unsafe { arrays[0].cast::<u8>().write_bytes(0, 0x200 << 5) };
  1049. // Connect, register every message but frame starts, then wait for
  1050. // the registration to be acknowledged.
  1051. let mut acp = std::ptr::null_mut();
  1052. assert_eq!(AcpHalCreate(&mut acp), S_OK);
  1053. // SAFETY: just created.
  1054. let m = unsafe { (*acp).vtable };
  1055. assert_eq!((m.connect)(acp, 0x804, 0x804), S_OK);
  1056. let mask = 0xfe_u32;
  1057. let data = (&raw const mask).cast();
  1058. assert_eq!(
  1059. (m.submit)(acp, REGISTER_MESSAGES, 1, u32::MAX, data, 0),
  1060. S_OK
  1061. );
  1062. let mut message = Message {
  1063. kind: 0,
  1064. dropped: 0,
  1065. usec: 0,
  1066. data: [0; 16],
  1067. };
  1068. assert!((m.pop_message)(acp, &mut message));
  1069. let (kind, dropped) = (message.kind, message.dropped);
  1070. assert_eq!((kind, dropped), (COMMAND_COMPLETED, 0));
  1071. assert_eq!(
  1072. u64::from_le_bytes(message.data[4..12].try_into().unwrap()),
  1073. 1
  1074. );
  1075. assert!(!(m.pop_message)(acp, &mut message));
  1076. assert_eq!((m.disconnect)(acp), S_OK);
  1077. assert_eq!((m.message_count)(acp), 1, "disconnected");
  1078. (m.release)(acp);
  1079. assert_eq!(AcpHalReleaseShapeContexts(), S_OK);
  1080. }
  1081. }