#![allow(non_snake_case)] #![allow(clippy::not_unsafe_ptr_arg_deref)] use std::alloc::Layout; use std::collections::{BTreeMap, VecDeque}; use std::ffi::c_void; use std::sync::{Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard}; use std::time::Instant; use super::xasync::{E_INVALIDARG, E_NOTIMPL}; use super::xgameruntime::{HRESULT, S_OK}; use crate::hle::{HleModule}; use crate::hle_export; #[cfg(all(windows, feature = "diagnostics"))] pub mod capture; #[cfg(windows)] pub mod output; const E_FAIL: HRESULT = 0x8000_4005_u32 as i32; const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32; fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } struct Block { size: usize, apu: u32, layout: Layout, non_cached: bool, } struct Heap { blocks: BTreeMap, by_apu: BTreeMap, free: BTreeMap, created: bool, sizes: [u32; 2], } static HEAP: Mutex = Mutex::new(Heap { blocks: BTreeMap::new(), by_apu: BTreeMap::new(), free: BTreeMap::new(), created: false, sizes: [0; 2], }); const APU_BASE: u32 = 0x0001_0000; impl Heap { fn take(&mut self, size: u32, align: u32) -> Option { if self.free.is_empty() && !self.created { self.free.insert(APU_BASE, u32::MAX); } self.created = true; let (start, end, apu) = self.free.iter().find_map(|(&start, &end)| { let apu = start.checked_next_multiple_of(align)?; (apu.checked_add(size)? <= end).then_some((start, end, apu)) })?; self.free.remove(&start); if start < apu { self.free.insert(start, apu); } if apu + size < end { self.free.insert(apu + size, end); } Some(apu) } fn give_back(&mut self, mut start: u32, mut end: u32) { if let Some((&before, &before_end)) = self.free.range(..start).next_back() && before_end == start { self.free.remove(&before); start = before; } if let Some(after_end) = self.free.remove(&end) { end = after_end; } self.free.insert(start, end); } } #[derive(Debug)] enum HeapRefusal { NoDeviceRange { size: usize, align: usize }, HostAllocator { len_bytes: usize }, } impl HeapRefusal { fn report(&self) { match *self { Self::NoDeviceRange { size, align } => tracing::warn!( size, align, "no free APU device-address range fits the request" ), Self::HostAllocator { len_bytes } => super::xmem::report_allocator_refusal(len_bytes), } } } fn heap_alloc(size: usize, align: usize, non_cached: bool) -> Result<(*mut u8, u32), HeapRefusal> { let mut heap = lock(&HEAP); let fit = Layout::from_size_align(size.max(1), align.max(16)) .ok() .and_then(|layout| { let apu = heap.take(u32::try_from(layout.size()).ok()?, align as u32)?; Some((layout, apu)) }); let Some((layout, apu)) = fit else { return Err(HeapRefusal::NoDeviceRange { size, align }); }; let ptr = unsafe { std::alloc::alloc_zeroed(layout) }; if ptr.is_null() { heap.give_back(apu, apu + layout.size() as u32); return Err(HeapRefusal::HostAllocator { len_bytes: layout.size(), }); } heap.blocks .insert(ptr as usize, Block { size, apu, layout, non_cached }); heap.by_apu.insert(apu, ptr as usize); if size >= 32 << 20 { tracing::info!(mb = size >> 20, at = ?ptr, "audio memory for the title from our allocator"); } Ok((ptr, apu)) } fn heap_free(ptr: *mut u8) { let mut heap = lock(&HEAP); let Some(block) = heap.blocks.remove(&(ptr as usize)) else { return; }; heap.by_apu.remove(&block.apu); heap.give_back(block.apu, block.apu + block.layout.size() as u32); drop(heap); unsafe { std::alloc::dealloc(ptr, block.layout) }; } pub extern "system" fn ApuCreateHeap(cached: u32, non_cached: u32) -> HRESULT { const ALREADY_ALLOCATED: HRESULT = 0x8ACA_0001_u32 as i32; if cached == 0 { return E_INVALIDARG; } let mut heap = lock(&HEAP); if heap.created { return ALREADY_ALLOCATED; } heap.created = true; heap.sizes = [cached, non_cached]; heap.free.insert(APU_BASE, u32::MAX); S_OK } pub extern "system" fn ApuMapApuAddress(apu: u32) -> *mut c_void { heap_unmap(apu).map_or(std::ptr::null_mut(), |p| p.cast()) } fn heap_map(ptr: usize) -> u32 { let heap = lock(&HEAP); match heap.blocks.range(..=ptr).next_back() { Some((&start, block)) if ptr < start + block.size.max(1) => { block.apu + (ptr - start) as u32 } _ => 0, } } fn heap_unmap(apu: u32) -> Option<*mut u8> { let heap = lock(&HEAP); let (&start, &host) = heap.by_apu.range(..=apu).next_back()?; let block = &heap.blocks[&host]; (apu < start.saturating_add(block.size.max(1) as u32)) .then(|| (host + (apu - start) as usize) as *mut u8) } fn heap_bytes<'a>(apu: u32, len: usize) -> Option<&'a mut [u8]> { let heap = lock(&HEAP); let (&start, &host) = heap.by_apu.range(..=apu).next_back()?; let offset = (apu - start) as usize; (offset + len <= heap.blocks[&host].size) .then(|| unsafe { std::slice::from_raw_parts_mut((host + offset) as *mut u8, len) }) } pub extern "system" fn ApuAlloc( out: *mut *mut c_void, apu: *mut u32, size: u32, align: u32, flags: u32, ) -> HRESULT { if out.is_null() || size == 0 || align < 4 || !align.is_power_of_two() { return E_INVALIDARG; } const NON_CACHED: u32 = 2; let (ptr, address) = match heap_alloc(size as usize, align as usize, flags & NON_CACHED != 0) { Ok(block) => block, Err(refusal) => { refusal.report(); return E_OUTOFMEMORY; } }; unsafe { out.write(ptr.cast()); if !apu.is_null() { apu.write(address); } } S_OK } #[repr(C)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct ApuHeapState { pub bytes_free: u32, pub bytes_allocated: u32, pub bytes_lost: u32, pub largest_free_block: u32, pub allocations: u32, } pub extern "system" fn ApuHeapGetState(state: *mut ApuHeapState, flags: u32) -> HRESULT { const NOT_ALLOCATED: HRESULT = 0x8ACA_0002_u32 as i32; let non_cached = match flags { 1 => false, 2 => true, _ => return E_INVALIDARG, }; if state.is_null() { return E_INVALIDARG; } let heap = lock(&HEAP); if !heap.created { return NOT_ALLOCATED; } let mut s = ApuHeapState::default(); let mut used = 0u64; for block in heap.blocks.values().filter(|b| b.non_cached == non_cached) { s.allocations += 1; s.bytes_allocated = s.bytes_allocated.saturating_add(block.size as u32); s.bytes_lost = s.bytes_lost.saturating_add((block.layout.size() - block.size) as u32); used += block.layout.size() as u64; } s.bytes_free = u64::from(heap.sizes[usize::from(non_cached)]).saturating_sub(used) as u32; s.largest_free_block = s.bytes_free; unsafe { state.write(s) }; S_OK } pub extern "system" fn ApuFree(ptr: *mut c_void) { heap_free(ptr.cast()); } pub extern "system" fn ApuMapVirtualAddress(ptr: *const c_void) -> u32 { heap_map(ptr as usize) } pub extern "system" fn ApuIsVirtualAddressValid(ptr: *const c_void, align: u32) -> bool { let apu = heap_map(ptr as usize); apu != 0 && (align == 0 || apu.is_multiple_of(align)) } #[repr(C, packed)] pub struct ShapeContexts { counts: [u32; 6], arrays: [*mut c_void; 6], apu: [u32; 6], } const CONTEXT_BYTES: [usize; 6] = [32, 256, 256, 16, 64, 256]; static CONTEXTS: Mutex> = Mutex::new(None); pub extern "system" fn AcpHalAllocateShapeContexts(contexts: *mut ShapeContexts) -> HRESULT { if contexts.is_null() { return E_INVALIDARG; } let mut allocated = lock(&CONTEXTS); if allocated.is_some() { return E_FAIL; } let counts = unsafe { std::ptr::addr_of!((*contexts).counts).read_unaligned() }; let mut arrays: [*mut c_void; 6] = [std::ptr::null_mut(); 6]; let mut addresses = [0u32; 6]; for i in 0..6 { if counts[i] == 0 { continue; } let (ptr, apu) = match heap_alloc(counts[i] as usize * CONTEXT_BYTES[i], 256, false) { Ok(block) => block, Err(refusal) => { arrays.iter().for_each(|&p| heap_free(p.cast())); drop(allocated); refusal.report(); return E_OUTOFMEMORY; } }; (arrays[i], addresses[i]) = (ptr.cast(), apu); } unsafe { std::ptr::addr_of_mut!((*contexts).arrays).write_unaligned(arrays); std::ptr::addr_of_mut!((*contexts).apu).write_unaligned(addresses); } *allocated = Some(arrays.map(|p| p as usize)); let mut xma = XMA.write().unwrap_or_else(|e| e.into_inner()); xma.array = arrays[4] as usize; xma.voices = (0..counts[4]).map(|_| Mutex::new(None)).collect(); S_OK } pub extern "system" fn AcpHalReleaseShapeContexts() -> HRESULT { match lock(&CONTEXTS).take() { Some(arrays) => { *XMA.write().unwrap_or_else(|e| e.into_inner()) = Xma::EMPTY; arrays.iter().for_each(|&p| heap_free(p as *mut u8)); S_OK } None => E_FAIL, } } use eonacat_xsbox_gpu::formats::xma; const ENABLE_XMA: u32 = 5; const ENABLE_XMAS: u32 = 6; const DISABLE_XMA: u32 = 7; const DISABLE_XMAS: u32 = 8; const ADVANCE_XMA_READ: u32 = 18; const BLOCK_BYTES: usize = 256; const SAMPLES_PER_BLOCK: usize = BLOCK_BYTES / 2; const INPUT_INVALID: u32 = 4; const CARRY_TAG: [u8; 4] = *b"VXO1"; const CARRY_HEADER: usize = 10; fn carry_bytes(channels: usize) -> usize { CARRY_HEADER + xma::FRAME_SAMPLES / 2 * channels * 2 } fn save_carry(context: Context, decoder: &xma::Decoder) -> bool { let address = context.get(8); let channels = decoder.channels(); if address == 0 { return false; } let Some(out) = heap_bytes(address, carry_bytes(channels)) else { return false; }; let carry = decoder.carry(); out[..4].copy_from_slice(&CARRY_TAG); out[4] = channels as u8; out[5] = 0; out[6..8].copy_from_slice(&carry.block_len[0].to_le_bytes()); out[8..10].copy_from_slice(&carry.block_len[1].to_le_bytes()); for (pair, s) in out[CARRY_HEADER..].as_chunks_mut::<2>().0.iter_mut().zip(&carry.samples) { pair.copy_from_slice(&s.to_le_bytes()); } true } fn resume_carry(context: Context, channels: usize, rate: u32) -> Option { let address = context.get(8); if address == 0 { return None; } let bytes = heap_bytes(address, carry_bytes(channels))?; if bytes[..4] != CARRY_TAG || usize::from(bytes[4]) != channels { return None; } let carry = xma::Carry { block_len: [u16::from_le_bytes([bytes[6], bytes[7]]), u16::from_le_bytes([bytes[8], bytes[9]])], samples: bytes[CARRY_HEADER..].as_chunks::<2>().0.iter().map(|p| i16::from_le_bytes(*p)).collect(), }; bytes[..4].fill(0); let mut decoder = xma::Decoder::new(channels, rate); decoder.resume(&carry).then_some(decoder) } fn rate(context: Context) -> u32 { const RATES: [u32; 4] = [24_000, 32_000, 44_100, 48_000]; RATES[context.field(1, 27, 2) as usize] } struct Voice { decoder: Option, pcm: VecDeque, skip: usize, ended: bool, trace: Trace, } struct Trace { since: Instant, produced: usize, taken: usize, takes: u32, partial_takes: u32, frames: u32, bad_frames: u32, peak: i16, ended_ms: Option, } struct Xma { array: usize, voices: Vec>>, } impl Xma { const EMPTY: Xma = Xma { array: 0, voices: Vec::new(), }; } static XMA: RwLock = RwLock::new(Xma::EMPTY); fn xma() -> RwLockReadGuard<'static, Xma> { XMA.read().unwrap_or_else(|e| e.into_inner()) } #[derive(Clone, Copy)] struct Context(*mut u32); impl Context { fn get(self, word: usize) -> u32 { unsafe { self.0.add(word).read_volatile() } } fn set(self, word: usize, value: u32) { unsafe { self.0.add(word).write_volatile(value) } } fn field(self, word: usize, shift: u32, bits: u32) -> u32 { (self.get(word) >> shift) & ((1 << bits) - 1) } fn set_field(self, word: usize, shift: u32, bits: u32, value: u32) { let mask = ((1u32 << bits) - 1) << shift; self.set(word, (self.get(word) & !mask) | ((value << shift) & mask)); } fn channels(self) -> usize { 1 + self.field(1, 29, 1) as usize } } impl Xma { fn context(&self, index: u32) -> Option { ((index as usize) < self.voices.len() && self.array != 0) .then(|| Context((self.array + index as usize * 64) as *mut u32)) } fn enable(&self, index: u32) { let Some(context) = self.context(index) else { return; }; let mut slot = lock(&self.voices[index as usize]); context.set_field(2, 26, 6, 0); tracing::debug!( index, words = ?(0..10).map(|w| format!("{:08x}", context.get(w))).collect::>(), "XMA voice enabled" ); #[cfg(feature = "diagnostics")] dump_input(index, context); let decoder = resume_carry(context, context.channels(), rate(context)); if decoder.is_some() { tracing::debug!(index, "XMA voice goes on from its overlap buffer"); } *slot = Some(Voice { decoder, pcm: VecDeque::new(), skip: context.field(1, 24, 3) as usize * xma::SUBFRAME_SAMPLES, ended: false, trace: Trace { since: Instant::now(), produced: 0, taken: 0, takes: 0, partial_takes: 0, frames: 0, bad_frames: 0, peak: 0, ended_ms: None, }, }); drop(slot); wake_decoder(); } fn disable(&self, index: u32) { let Some(context) = self.context(index) else { return; }; let Some(voice) = lock(&self.voices[index as usize]).take() else { return; }; let t = &voice.trace; tracing::debug!( index, ms = t.since.elapsed().as_millis(), produced = t.produced, taken = t.taken * SAMPLES_PER_BLOCK / context.channels(), takes = t.takes, partial_takes = t.partial_takes, frames = t.frames, bad_frames = t.bad_frames, peak = t.peak, input_ended_ms = ?t.ended_ms, read_bit = context.field(2, 0, 26), input_bits = context.field(0, 0, 12) * xma::PACKET_BYTES as u32 * 8, "XMA voice disabled" ); } fn advance_read(&self, index: u32, blocks: u32) { let Some(context) = self.context(index) else { return; }; let mut slot = lock(&self.voices[index as usize]); let size = context.field(0, 22, 5).max(1); let read = (context.field(9, 0, 5) + blocks % size) % size; context.set_field(9, 0, 5, read); if blocks > 0 { context.set_field(1, 31, 1, 1); } if let Some(voice) = &mut *slot { let t = &mut voice.trace; t.taken += blocks as usize; t.takes += 1; t.partial_takes += u32::from(blocks < size); } drop(slot); wake_decoder(); } fn pump(&self) { let start = Instant::now(); let mut active = 0; for index in 0..self.voices.len() as u32 { if let (Some(context), Some(voice)) = (self.context(index), &mut *lock(&self.voices[index as usize])) { pump(context, voice); active += 1; } } let took = start.elapsed(); if took.as_millis() >= 4 { tracing::debug!(active, ms = took.as_millis(), "slow XMA decoding pass"); } } } fn pump(context: Context, voice: &mut Voice) { let size = context.field(0, 22, 5); if size == 0 { return; } while context.field(1, 31, 1) == 1 { for _ in 0..8 { if voice.pcm.len() >= SAMPLES_PER_BLOCK || !decode(context, voice) { break; } } if voice.pcm.is_empty() || (voice.pcm.len() < SAMPLES_PER_BLOCK && !voice.ended) { return; } let write = context.field(0, 27, 5) % size; let address = context.get(7) as usize + write as usize * BLOCK_BYTES; let Some(out) = heap_bytes(address as u32, BLOCK_BYTES) else { return; }; for pair in out.as_chunks_mut::<2>().0 { let sample = voice.pcm.pop_front().unwrap_or(0); voice.trace.peak = voice.trace.peak.max(sample.saturating_abs()); pair.copy_from_slice(&sample.to_le_bytes()); } voice.trace.produced += SAMPLES_PER_BLOCK / context.channels(); let write = (write + 1) % size; context.set_field(0, 27, 5, write); if write == context.field(9, 0, 5) % size { context.set_field(1, 31, 1, 0); } } } fn decode(context: Context, voice: &mut Voice) -> bool { let valid = context.field(0, 20, 2); if voice.ended { if valid == 0 { return false; } voice.ended = false; if context.field(2, 26, 5) == INPUT_INVALID { context.set_field(2, 26, 6, 0); } } let channels = context.channels(); let mut current = context.field(4, 31, 1); if valid & (1 << current) == 0 { if valid & (1 << (1 - current)) == 0 { if let Some(decoder) = &mut voice.decoder && !save_carry(context, decoder) { let mut tail = Vec::new(); decoder.flush(&mut tail); voice.pcm.extend(tail); } voice.ended = true; voice.trace.ended_ms = Some(voice.trace.since.elapsed().as_millis()); context.set_field(2, 26, 5, INPUT_INVALID); context.set_field(2, 31, 1, 1); return !voice.pcm.is_empty(); } current = 1 - current; context.set_field(4, 31, 1, current); context.set_field(2, 0, 26, 0); } let (address, packets) = match current { 0 => (context.get(5), context.field(0, 0, 12)), _ => (context.get(6), context.field(1, 0, 12)), }; let Some(data) = heap_bytes(address & !0x7ff, packets as usize * xma::PACKET_BYTES) else { context.set_field(0, 20 + current, 1, 0); return true; }; let mut at = context.field(2, 0, 26) as usize; if at < 32 { at = 32 + xma::packet(data, 0).map_or(0, |p| p.first_frame_bit as usize); } let Some(frame) = xma::read_frame(data, at) else { context.set_field(0, 20 + current, 1, 0); return true; }; let decoder = voice.decoder.get_or_insert_with(|| xma::Decoder::new(channels, rate(context))); let mut pcm = Vec::with_capacity(xma::FRAME_SAMPLES * channels); voice.trace.frames += 1; if let Err(e) = decoder.decode(&frame.data, frame.bits, &mut pcm) { voice.trace.bad_frames += 1; if voice.trace.bad_frames <= 2 { tracing::debug!( at, bits = frame.bits, head = ?&frame.data[..frame.data.len().min(8)], %e, "XMA frame did not decode" ); } } let mut next = frame.next.unwrap_or(0); let loops = context.field(0, 12, 8); let loop_end = context.field(4, 0, 26) as usize; let ends_loop = loop_end != 0 && (frame.start == loop_end || (frame.start < loop_end && frame.next.is_none_or(|n| loop_end < n))); let looping = loops > 0 && ends_loop; if looping { let keep = (context.field(1, 12, 2) as usize + 1) * xma::SUBFRAME_SAMPLES * channels; pcm.truncate(keep); next = context.field(3, 0, 26) as usize; if loops != 255 { context.set_field(0, 12, 8, loops - 1); } } let skip = (voice.skip * channels).min(pcm.len()); voice.skip -= skip / channels; voice.pcm.extend(&pcm[skip..]); if looping { voice.skip = context.field(1, 17, 3) as usize * xma::SUBFRAME_SAMPLES; } if next == 0 { context.set_field(0, 20 + current, 1, 0); } context.set_field(2, 0, 26, next as u32); true } #[cfg(feature = "diagnostics")] fn dump_input(index: u32, context: Context) { static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); let Some(dir) = std::env::var_os("EONACAT_XS_XMA_DUMP") else { return; }; let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); if n >= 32 { return; } let dir = std::path::PathBuf::from(dir); let words: Vec = (0..16).flat_map(|w| context.get(w).to_le_bytes()).collect(); let input = heap_bytes( context.get(5) & !0x7ff, context.field(0, 0, 12) as usize * xma::PACKET_BYTES, ); let _ = std::fs::create_dir_all(&dir); let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words); let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default()); } #[cfg(feature = "diagnostics")] pub(crate) fn voice_log_ms() -> Option { static MS: OnceLock> = OnceLock::new(); *MS.get_or_init(|| { std::env::var("EONACAT_XS_VOICE_LOG") .ok() .and_then(|v| v.parse().ok()) .filter(|&ms| ms > 0) }) } #[cfg(feature = "diagnostics")] fn voice_log(xma: &Xma) { static LAST: Mutex> = Mutex::new(None); let Some(ms) = voice_log_ms() else { return; }; let mut last = lock(&LAST); if last.is_some_and(|t| t.elapsed().as_millis() < ms) { return; } *last = Some(Instant::now()); drop(last); for (index, slot) in xma.voices.iter().enumerate() { let Some(context) = xma.context(index as u32) else { continue; }; let voice = lock(slot); let Some(voice) = voice.as_ref() else { continue; }; let taken = voice.trace.taken * SAMPLES_PER_BLOCK / context.channels(); tracing::info!( index, ms = voice.trace.since.elapsed().as_millis(), produced = voice.trace.produced, taken, read_bit = context.field(2, 0, 26), ended = voice.ended, "XMA voice position" ); } } fn wake_decoder() { static DECODER: OnceLock = OnceLock::new(); DECODER .get_or_init(|| { let priority = std::env::var("EONACAT_XS_XMA_PRIORITY") .ok() .and_then(|v| v.trim().parse::().ok()) .map_or(1, |p| p.clamp(-2, 2)); tracing::info!(priority, "XMA decoder: thread (EONACAT_XS_XMA_PRIORITY)"); std::thread::Builder::new() .name("eonacat-xsbox XMA decoder".into()) .spawn(move || { #[cfg(windows)] if priority != 0 { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority}; unsafe { SetThreadPriority(GetCurrentThread(), priority) }; } loop { #[cfg(feature = "diagnostics")] voice_log(&xma()); xma().pump(); std::thread::park_timeout(std::time::Duration::from_millis(2)); } }) .map_or_else(|_| std::thread::current(), |h| h.thread().clone()) }) .unpark(); } fn xma_command(command: u32, word: impl Fn(usize) -> Option) -> bool { let xma = xma(); match command { ENABLE_XMA => xma.enable(word(0).unwrap_or(u32::MAX)), DISABLE_XMA => xma.disable(word(0).unwrap_or(u32::MAX)), ENABLE_XMAS | DISABLE_XMAS => { for i in 0..xma.voices.len() as u32 { if word(i as usize / 32).unwrap_or(0) & (1 << (i % 32)) != 0 { match command { ENABLE_XMAS => xma.enable(i), _ => xma.disable(i), } } } } ADVANCE_XMA_READ => xma.advance_read(word(0).unwrap_or(u32::MAX), word(1).unwrap_or(0)), _ => return false, } true } const LOAD_FLOWGRAPH: u32 = 1; const REGISTER_MESSAGES: u32 = 2; const UNREGISTER_MESSAGES: u32 = 3; const FLOWGRAPH_COMPLETED: u32 = 0x02; const COMMAND_COMPLETED: u32 = 0x10; const DISCONNECTED: u32 = 0x80; const FRAMES_PER_SECOND: u64 = 375; #[repr(C, packed)] #[derive(Clone, Copy)] struct Message { kind: u32, dropped: u32, usec: u32, data: [u8; 16], } struct State { connected: bool, mask: u32, messages: VecDeque, capacity: usize, dropped: u32, since: Instant, } impl State { fn usec(&self) -> u64 { self.since.elapsed().as_micros() as u64 } fn frame(&self) -> u32 { (self.usec() * FRAMES_PER_SECOND / 1_000_000) as u32 } fn post(&mut self, kind: u32, data: &[u8]) { if self.mask & kind == 0 { return; } if self.messages.len() >= self.capacity { self.dropped = self.dropped.saturating_add(1); tracing::debug!(kind, dropped = self.dropped, "coprocessor message dropped"); return; } let mut message = Message { kind, dropped: std::mem::take(&mut self.dropped), usec: self.usec() as u32, data: [0; 16], }; message.data[..data.len()].copy_from_slice(data); self.messages.push_back(message); } } #[repr(C)] pub struct Acp { vtable: &'static AcpMethods, state: Mutex, } extern "system" fn beyond(_: *mut Acp) -> HRESULT { tracing::warn!( slot = format_args!("{SLOT:#x}"), "audio coprocessor method not implemented" ); E_NOTIMPL } #[repr(C)] struct AcpMethods { connect: extern "system" fn(*mut Acp, u32, u32) -> HRESULT, disconnect: extern "system" fn(*mut Acp) -> HRESULT, submit: extern "system" fn(*mut Acp, u32, u64, u32, *const c_void, u32) -> HRESULT, pop_message: extern "system" fn(*mut Acp, *mut Message) -> bool, message_count: extern "system" fn(*mut Acp) -> u32, release: extern "system" fn(*mut Acp), spare: [extern "system" fn(*mut Acp) -> HRESULT; 8], } static ACP_METHODS: AcpMethods = AcpMethods { connect, disconnect, submit, pop_message, message_count, release, spare: [ beyond::<0x30>, beyond::<0x38>, beyond::<0x40>, beyond::<0x48>, beyond::<0x50>, beyond::<0x58>, beyond::<0x60>, beyond::<0x68>, ], }; fn state(this: *mut Acp) -> MutexGuard<'static, State> { lock(unsafe { &(*this).state }) } extern "system" fn connect(this: *mut Acp, commands: u32, messages: u32) -> HRESULT { if commands == 0 { return E_INVALIDARG; } let mut state = state(this); state.connected = true; state.capacity = messages as usize; S_OK } extern "system" fn disconnect(this: *mut Acp) -> HRESULT { let mut state = state(this); if !state.connected { return E_FAIL; } state.post(DISCONNECTED, &[]); state.connected = false; S_OK } extern "system" fn submit( this: *mut Acp, command: u32, id: u64, _frame: u32, data: *const c_void, notification: u32, ) -> HRESULT { static SEEN: Mutex = Mutex::new(0); if command < 64 && *lock(&SEEN) & 1 << command == 0 { *lock(&SEEN) |= 1 << command; tracing::info!(command, "first coprocessor command of this kind"); } let mut state = state(this); let word = |at: usize| -> Option { (!data.is_null()).then(|| unsafe { data.cast::().add(at).read_unaligned() }) }; match command { REGISTER_MESSAGES => state.mask |= word(0).unwrap_or(0), UNREGISTER_MESSAGES => state.mask &= !word(0).unwrap_or(0), LOAD_FLOWGRAPH => { let flowgraph = word(1).unwrap_or(0); state.post(FLOWGRAPH_COMPLETED, &flowgraph.to_le_bytes()); } _ if xma_command(command, word) => {} _ => {} } if id != 0 { let mut done = [0u8; 16]; done[..4].copy_from_slice(&command.to_le_bytes()); done[4..12].copy_from_slice(&id.to_le_bytes()); done[12..].copy_from_slice(&state.frame().to_le_bytes()); state.post(COMMAND_COMPLETED, &done); } if notification != 0 && let Some(word) = heap_unmap(notification) { unsafe { word.cast::().write_volatile(1) }; } S_OK } extern "system" fn pop_message(this: *mut Acp, out: *mut Message) -> bool { let Some(message) = state(this).messages.pop_front() else { return false; }; if !out.is_null() { unsafe { out.write_unaligned(message) }; } true } extern "system" fn message_count(this: *mut Acp) -> u32 { state(this).messages.len() as u32 } extern "system" fn release(this: *mut Acp) { drop(unsafe { Box::from_raw(this) }); } pub extern "system" fn AcpHalCreate(out: *mut *mut Acp) -> HRESULT { if out.is_null() { return E_INVALIDARG; } let acp = Box::new(Acp { vtable: &ACP_METHODS, state: Mutex::new(State { connected: false, mask: 0, messages: VecDeque::new(), capacity: 0, dropped: 0, since: Instant::now(), }), }); unsafe { out.write(Box::into_raw(acp)) }; S_OK } pub(crate) fn module() -> HleModule { HleModule { name: "audio", dlls: &["acphal.dll"], exports: vec![ hle_export!(AcpHalAllocateShapeContexts), hle_export!(AcpHalReleaseShapeContexts), hle_export!(AcpHalCreate), hle_export!(ApuAlloc), hle_export!(ApuCreateHeap), hle_export!(ApuFree), hle_export!(ApuHeapGetState), hle_export!(ApuIsVirtualAddressValid), hle_export!(ApuMapApuAddress), hle_export!(ApuMapVirtualAddress), ], } }