From 2bd8fccb735c735fab0b61049d7ae0bca2d74d04 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:26:36 +0100 Subject: [PATCH] XAudio2: real Opus decoder via Windows MSOpusDecoder MFT - Add hle::opus: RFC 6716 TOC/packet parser (exact Table 2 frame durations for all 32 configs, codes 0-3, 120 ms limit), RFC 7845 OpusHead parser/builder, framing extractor (Ogg Opus, [u16 LE len][pkt] blocks with zero padding, raw packets), and stateful Decoder backed by dynamically loaded mfplat.dll + MSOpusDecoder.dll (1-2 ch single-stream and 3-8 ch multistream via RFC 6716 Appendix B self-delimited splitting). - Wire Opus voices (WAVE_FORMAT_OPUS 0x704F and WAVE_FORMAT_EXTENSIBLE with MFAudioFormat_Opus) in hle::xaudio2 to decode to PCM16, wrap IXAudio2VoiceCallback to manage decoded buffer lifetimes and forward the title's original pBufferContext, flush decoder state on FlushSourceBuffers, and map tokens back in GetState. - Add AudioStats counters (opus_voices, opus_buffers_decoded, opus_decode_errors), unit tests covering SILK/Hybrid/CELT/5.1/framing/lifetime, and an Opus voice check in tests/testtitle + e2e. --- README.md | 4 +- THIRD_PARTY.md | 2 +- crates/xcl/Cargo.toml | 1 + crates/xcl/src/hle/mod.rs | 1 + crates/xcl/src/hle/opus.rs | 1452 +++++++++++++++++++++++++++++++++ crates/xcl/src/hle/xaudio2.rs | 756 ++++++++++++++++- crates/xcl/tests/e2e.rs | 5 +- tests/testtitle/src/audio.rs | 89 +- 8 files changed, 2266 insertions(+), 44 deletions(-) create mode 100644 crates/xcl/src/hle/opus.rs diff --git a/README.md b/README.md index 4a97939..2889764 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ measurements and next steps: |---|---|---|---| | **XGameRuntime** | ✅ | the GDK thunk protocol real titles use, laid out from a table of all 396 GDK runtime functions; offline XUser, XGameSave, persistent local storage, XPackage, XGame (title id), XSystem – the title sees an Xbox Series X / S; task queues, async, networking and dialogs through the PC's XGameRuntime | the game's libHttpClient initialises; users, saves and storage through the real call path; slot layout cross-checked against the game's own thunks | | **Input** | ✅ | GameInput → the system GameInput | – | -| **Audio** | 🟡 | XAudio2 → system XAudio2.9 (PCM / float voices) | unit tests; Opus / XMA2 voices are silent for now | +| **Audio** | 🟡 | XAudio2 → system XAudio2.9 (PCM / float voices; Opus 0x704F decoded via `MSOpusDecoder.dll`) | unit + end-to-end tests; XMA2 voices are silent for now | ### Graphics @@ -68,7 +68,7 @@ measurements and next steps: | Needs a game executable | Not done yet | Not planned | |---|---|---| -| D3D12.X draw records and `PresentX` / frame pacing | Opus / XMA2 audio decoding | Xbox Live, Store licensing (offline by design) | +| D3D12.X draw records and `PresentX` / frame pacing | XMA2 audio decoding | Xbox Live, Store licensing (offline by design) | | root arguments → shader registers for graphics | performance work (GPU buffers live in system memory) | decrypting XVC packages or any DRM | | texture creation in title memory (binding the detiler), MSAA tiled textures | hull / domain / amplification shaders (none in the sample game) | console SDK headers / binaries in the repository | | Bink GPU decoding, rehydrating prebuilt BVHs | | | diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index c1996ad..1da9fc1 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -16,7 +16,7 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | docs.xbox.com | documentation | signatures, enums, structs written independently | reference | | Rust crates (`Cargo.lock`) | MIT / BSD-2 / Zlib / Unlicense (or with an MIT alternative) | build dependencies | statically linked | | DXC (`dxcompiler.dll`, `dxil.dll`) from the Windows SDK | NCSA (dxcompiler) / Microsoft (dxil) | HLSL → DXIL compilation at runtime | loaded from the user's SDK, **not** distributed with XCL | -| Windows system libraries (d3d12, dxgi, xaudio2_9, ole32 …) | system | target APIs | GPL-2.0 "system library" exception | +| Windows system libraries (d3d12, dxgi, xaudio2_9, mfplat, MSOpusDecoder, ole32 …) | system | target APIs | GPL-2.0 "system library" exception | When adding dependencies: compatible with GPL-2.0-only are MIT, BSD, Zlib, ISC, Unlicense, LGPL-2.1(+), GPL-2.0(+), MPL-2.0 (via its Secondary License clause). Incompatible: Apache-2.0 without an alternative, diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index 65b6a96..5bd7fe5 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -32,6 +32,7 @@ features = [ "Win32_Graphics_Dxgi_Common", "Win32_Graphics_Gdi", "Win32_Media_Audio", + "Win32_Media_MediaFoundation", "Win32_Security", "Win32_System_Com", "Win32_System_LibraryLoader", diff --git a/crates/xcl/src/hle/mod.rs b/crates/xcl/src/hle/mod.rs index 8759fe8..e7cf076 100644 --- a/crates/xcl/src/hle/mod.rs +++ b/crates/xcl/src/hle/mod.rs @@ -13,6 +13,7 @@ use crate::util::glob_match; pub mod d3d12_layout; pub mod d3d12x; pub mod kernelx; +pub mod opus; pub mod xaudio2; pub mod xgameruntime; diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs new file mode 100644 index 0000000..58299ee --- /dev/null +++ b/crates/xcl/src/hle/opus.rs @@ -0,0 +1,1452 @@ +//! RFC 6716 Opus packet framing and real decoding via Windows' `MSOpusDecoder.dll` +//! (Media Foundation `IMFTransform`). +//! +//! `mfplat.dll` and `MSOpusDecoder.dll` are loaded dynamically at run time (like DXC and +//! `xaudio2_9.dll`), so XCL has no static dependency on Media Foundation and falls back +//! cleanly if a Windows installation lacks the Media Feature Pack. +//! +//! Windows' `MSOpusDecoder.dll` decodes single-stream Opus (1 or 2 channels). Multistream +//! Opus (3–8 channels, RFC 7845 mapping family 1 / 255) is decoded by splitting each +//! packet's RFC 6716 Appendix B self-delimited sub-packets across `stream_count` MFT +//! instances (`coupled_count` stereo + uncoupled mono) and interleaving via the channel map. + +use std::borrow::Cow; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::OnceLock; + +use windows::core::{GUID, HRESULT, Interface}; +use windows::Win32::Media::MediaFoundation::{ + IMFMediaBuffer, IMFMediaType, IMFSample, IMFTransform, MFAudioFormat_Float, MFAudioFormat_Opus, + MFAudioFormat_PCM, MFMediaType_Audio, MFT_MESSAGE_COMMAND_FLUSH, + MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM, + MFT_OUTPUT_DATA_BUFFER, MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES, + MFT_OUTPUT_STREAM_PROVIDES_SAMPLES, MF_E_NOTACCEPTING, MF_E_TRANSFORM_NEED_MORE_INPUT, + MF_E_TRANSFORM_STREAM_CHANGE, MF_MT_AUDIO_BITS_PER_SAMPLE, MF_MT_AUDIO_NUM_CHANNELS, + MF_MT_AUDIO_SAMPLES_PER_SECOND, MF_MT_MAJOR_TYPE, MF_MT_SUBTYPE, MF_MT_USER_DATA, + MFSTARTUP_LITE, MF_VERSION, +}; +use windows::Win32::System::Com::IClassFactory; + +/// CLSID of Windows' built-in Microsoft Opus Audio Decoder MFT (`MSOpusDecoder.dll`). +const CLSID_MS_OPUS_DECODER: GUID = GUID::from_u128(0x63e17c10_2d43_4c42_8fe3_8d8b63e46a6a); + +/// Opus maximum packet duration (RFC 6716 §3.2.5): 120 ms = 5760 samples at 48 kHz. +pub const MAX_PACKET_SAMPLES_48K: u32 = 5760; + +// --------------------------------------------------------------------------------------- +// RFC 6716 TOC & packet parser (pure Rust) +// --------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + Silk, + Hybrid, + Celt, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Bandwidth { + Narrow, + Medium, + Wide, + SuperWide, + Full, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PacketInfo { + pub config: u8, + pub mode: Mode, + pub bandwidth: Bandwidth, + pub stereo: bool, + pub code: u8, + pub frames: u8, + /// Duration of one frame in samples at 48 kHz (120, 240, 480, 960, 1920, or 2880). + pub frame_samples_48k: u32, + /// Total duration of the packet in samples at 48 kHz (`frames * frame_samples_48k`, <= 5760). + pub total_samples_48k: u32, +} + +/// RFC 6716 §3.1 Table 2: TOC configuration number (0..=31) -> (mode, bandwidth, frame samples @ 48 kHz). +pub const fn config_info(config: u8) -> (Mode, Bandwidth, u32) { + match config & 0x1F { + 0 => (Mode::Silk, Bandwidth::Narrow, 480), // 10 ms + 1 => (Mode::Silk, Bandwidth::Narrow, 960), // 20 ms + 2 => (Mode::Silk, Bandwidth::Narrow, 1920), // 40 ms + 3 => (Mode::Silk, Bandwidth::Narrow, 2880), // 60 ms + 4 => (Mode::Silk, Bandwidth::Medium, 480), // 10 ms + 5 => (Mode::Silk, Bandwidth::Medium, 960), // 20 ms + 6 => (Mode::Silk, Bandwidth::Medium, 1920), // 40 ms + 7 => (Mode::Silk, Bandwidth::Medium, 2880), // 60 ms + 8 => (Mode::Silk, Bandwidth::Wide, 480), // 10 ms + 9 => (Mode::Silk, Bandwidth::Wide, 960), // 20 ms + 10 => (Mode::Silk, Bandwidth::Wide, 1920), // 40 ms + 11 => (Mode::Silk, Bandwidth::Wide, 2880), // 60 ms + 12 => (Mode::Hybrid, Bandwidth::SuperWide, 480), // 10 ms + 13 => (Mode::Hybrid, Bandwidth::SuperWide, 960), // 20 ms + 14 => (Mode::Hybrid, Bandwidth::Full, 480), // 10 ms + 15 => (Mode::Hybrid, Bandwidth::Full, 960), // 20 ms + 16 => (Mode::Celt, Bandwidth::Narrow, 120), // 2.5 ms + 17 => (Mode::Celt, Bandwidth::Narrow, 240), // 5 ms + 18 => (Mode::Celt, Bandwidth::Narrow, 480), // 10 ms + 19 => (Mode::Celt, Bandwidth::Narrow, 960), // 20 ms + 20 => (Mode::Celt, Bandwidth::Wide, 120), // 2.5 ms + 21 => (Mode::Celt, Bandwidth::Wide, 240), // 5 ms + 22 => (Mode::Celt, Bandwidth::Wide, 480), // 10 ms + 23 => (Mode::Celt, Bandwidth::Wide, 960), // 20 ms + 24 => (Mode::Celt, Bandwidth::SuperWide, 120), // 2.5 ms + 25 => (Mode::Celt, Bandwidth::SuperWide, 240), // 5 ms + 26 => (Mode::Celt, Bandwidth::SuperWide, 480), // 10 ms + 27 => (Mode::Celt, Bandwidth::SuperWide, 960), // 20 ms + 28 => (Mode::Celt, Bandwidth::Full, 120), // 2.5 ms + 29 => (Mode::Celt, Bandwidth::Full, 240), // 5 ms + 30 => (Mode::Celt, Bandwidth::Full, 480), // 10 ms + 31 => (Mode::Celt, Bandwidth::Full, 960), // 20 ms + _ => unreachable!(), + } +} + +/// Convert samples at 48 kHz to 100-nanosecond Media Foundation duration units. +/// Exact for every valid Opus frame size (120 samples = 2.5 ms = 25,000 * 100 ns). +pub const fn duration_100ns(samples_48k: u32) -> i64 { + (samples_48k as i64 * 10_000_000) / 48_000 +} + +/// Convert samples at 48 kHz to samples at `rate` Hz (Opus supports 8/12/16/24/48 kHz). +pub const fn samples_at_rate(samples_48k: u32, rate: u32) -> u32 { + ((samples_48k as u64 * rate as u64) / 48_000) as u32 +} + +/// Read an RFC 6716 §3.2.1 frame length field (1 or 2 bytes). +fn read_frame_len(data: &[u8], pos: &mut usize) -> Option { + let b0 = *data.get(*pos)? as usize; + *pos += 1; + if b0 < 252 { + Some(b0) + } else { + let b1 = *data.get(*pos)? as usize; + *pos += 1; + Some(b0 + 4 * b1) + } +} + +/// Write an RFC 6716 §3.2.1 frame length field (1 or 2 bytes, max 1275). +fn write_frame_len(len: usize, out: &mut Vec) -> Option<()> { + if len > 1275 { + return None; + } + if len < 252 { + out.push(len as u8); + } else { + let b1 = (len - 252) / 4; + let b0 = len - 4 * b1; // 252..=255 + out.push(b0 as u8); + out.push(b1 as u8); + } + Some(()) +} + +/// Parse and validate an RFC 6716 Opus packet. +/// +/// When `multistream` is false (mono/stereo, mapping family 0), validates the exact single-stream +/// byte-length rules in RFC 6716 §3.2.2–§3.2.5. When `multistream` is true (3..=8 channels, +/// mapping family 1/255), streams `0..N-2` use self-delimited framing (Appendix B) so only the +/// leading TOC / frame-count / 120 ms rules are enforced here. +pub fn parse_packet(packet: &[u8], multistream: bool) -> Option { + let toc = *packet.first()?; + let config = toc >> 3; + let stereo = (toc & 0x04) != 0; + let code = toc & 0x03; + let (mode, bandwidth, frame_samples_48k) = config_info(config); + + let frames: u8 = match code { + 0 => { + if !multistream && packet.len() - 1 > 1275 { + return None; + } + 1 + } + 1 => { + if !multistream { + let payload = packet.len() - 1; + if payload % 2 != 0 || payload / 2 > 1275 { + return None; + } + } + 2 + } + 2 => { + if !multistream { + let mut pos = 1; + let len1 = read_frame_len(packet, &mut pos)?; + if pos + len1 > packet.len() { + return None; + } + let len2 = packet.len() - pos - len1; + if len2 > 1275 { + return None; + } + } else if packet.len() < 2 { + return None; + } + 2 + } + 3 => { + let fcb = *packet.get(1)?; + let vbr = (fcb & 0x80) != 0; + let padded = (fcb & 0x40) != 0; + let count = fcb & 0x3F; + if count == 0 || count > 48 { + return None; + } + if !multistream { + let mut pos = 2usize; + let mut pad_len = 0usize; + if padded { + loop { + let b = *packet.get(pos)? as usize; + pos += 1; + if b == 255 { + pad_len = pad_len.checked_add(254)?; + } else { + pad_len = pad_len.checked_add(b)?; + break; + } + } + } + if pos + pad_len > packet.len() { + return None; + } + let end = packet.len() - pad_len; + if vbr { + let mut sum = 0usize; + for _ in 0..(count - 1) { + let flen = read_frame_len(packet, &mut pos)?; + sum = sum.checked_add(flen)?; + } + if pos + sum > end { + return None; + } + let last = end - pos - sum; + if last > 1275 { + return None; + } + } else { + let rem = end - pos; + let m = count as usize; + if rem % m != 0 || rem / m > 1275 { + return None; + } + } + } + count + } + _ => unreachable!(), + }; + + let total_samples_48k = frame_samples_48k.checked_mul(frames as u32)?; + if total_samples_48k > MAX_PACKET_SAMPLES_48K { + return None; + } + + Some(PacketInfo { + config, + mode, + bandwidth, + stereo, + code, + frames, + frame_samples_48k, + total_samples_48k, + }) +} + +/// Parse one RFC 6716 Appendix B self-delimited Opus packet starting at `data[*pos..]` and +/// convert it into a standard (non-self-delimited) RFC 6716 Opus packet. +fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option> { + let toc = *data.get(*pos)?; + *pos += 1; + let code = toc & 0x03; + let (_, _, frame_samples) = config_info(toc >> 3); + + match code { + 0 => { + let len = read_frame_len(data, pos)?; + let end = pos.checked_add(len)?; + let payload = data.get(*pos..end)?; + *pos = end; + let mut out = Vec::with_capacity(1 + len); + out.push(toc); + out.extend_from_slice(payload); + Some(out) + } + 1 => { + let len = read_frame_len(data, pos)?; + let total = len.checked_mul(2)?; + let end = pos.checked_add(total)?; + let payload = data.get(*pos..end)?; + *pos = end; + let mut out = Vec::with_capacity(1 + total); + out.push(toc); + out.extend_from_slice(payload); + Some(out) + } + 2 => { + let len1 = read_frame_len(data, pos)?; + let len2 = read_frame_len(data, pos)?; + let total = len1.checked_add(len2)?; + let end = pos.checked_add(total)?; + let payload = data.get(*pos..end)?; + *pos = end; + let mut out = Vec::with_capacity(3 + total); + out.push(toc); + write_frame_len(len1, &mut out)?; + out.extend_from_slice(payload); + Some(out) + } + 3 => { + let fcb = *data.get(*pos)?; + *pos += 1; + let vbr = (fcb & 0x80) != 0; + let padded = (fcb & 0x40) != 0; + let count = (fcb & 0x3F) as usize; + if count == 0 || count > 48 || frame_samples.checked_mul(count as u32)? > MAX_PACKET_SAMPLES_48K { + return None; + } + let pad_hdr_start = *pos; + let mut pad_len = 0usize; + if padded { + loop { + let b = *data.get(*pos)? as usize; + *pos += 1; + if b == 255 { + pad_len = pad_len.checked_add(254)?; + } else { + pad_len = pad_len.checked_add(b)?; + break; + } + } + } + let pad_hdr = &data[pad_hdr_start..*pos]; + let mut out = Vec::new(); + out.push(toc); + out.push(fcb); + out.extend_from_slice(pad_hdr); + + let total_payload = if vbr { + let mut sum = 0usize; + for i in 0..count { + let flen = read_frame_len(data, pos)?; + if i + 1 < count { + write_frame_len(flen, &mut out)?; + } + sum = sum.checked_add(flen)?; + } + sum + } else { + let flen = read_frame_len(data, pos)?; + flen.checked_mul(count)? + }; + let end = pos.checked_add(total_payload)?.checked_add(pad_len)?; + let body = data.get(*pos..end)?; + *pos = end; + out.extend_from_slice(body); + Some(out) + } + _ => unreachable!(), + } +} + +/// Split an RFC 7845 multistream packet into `stream_count` standard single-stream packets. +pub fn split_multistream_packet<'a>(packet: &'a [u8], stream_count: usize) -> Option>> { + if stream_count == 0 { + return None; + } + if stream_count == 1 { + parse_packet(packet, false)?; + return Some(vec![Cow::Borrowed(packet)]); + } + let mut out = Vec::with_capacity(stream_count); + let mut pos = 0usize; + for _ in 0..(stream_count - 1) { + let sub = split_self_delimited(packet, &mut pos)?; + parse_packet(&sub, false)?; + out.push(Cow::Owned(sub)); + } + let last = packet.get(pos..)?; + parse_packet(last, false)?; + out.push(Cow::Borrowed(last)); + Some(out) +} + +// --------------------------------------------------------------------------------------- +// RFC 7845 OpusHead builder & parser +// --------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OpusHead { + pub channels: u8, + pub pre_skip: u16, + pub input_rate: u32, + pub output_gain: i16, + pub mapping_family: u8, + pub stream_count: u8, + pub coupled_count: u8, + pub mapping: Vec, + pub raw: Vec, +} + +/// Standard Vorbis surround channel mappings for RFC 7845 mapping family 1 (3..=8 channels). +fn vorbis_mapping(channels: u8) -> Option<(u8, u8, &'static [u8])> { + match channels { + 3 => Some((2, 1, &[0, 2, 1])), + 4 => Some((2, 2, &[0, 1, 2, 3])), + 5 => Some((3, 2, &[0, 4, 1, 2, 3])), + 6 => Some((4, 2, &[0, 4, 1, 2, 3, 5])), + 7 => Some((4, 3, &[0, 4, 1, 2, 3, 5, 6])), + 8 => Some((5, 3, &[0, 6, 1, 2, 3, 4, 5, 7])), + _ => None, + } +} + +/// Build a canonical RFC 7845 `OpusHead` identification header. +pub fn build_opus_head(channels: u8, input_rate: u32, pre_skip: u16, output_gain: i16) -> Vec { + let ch = channels.clamp(1, 8); + let mut h = Vec::with_capacity(if ch <= 2 { 19 } else { 21 + ch as usize }); + h.extend_from_slice(b"OpusHead"); + h.push(1); // version + h.push(ch); + h.extend_from_slice(&pre_skip.to_le_bytes()); + h.extend_from_slice(&input_rate.to_le_bytes()); + h.extend_from_slice(&output_gain.to_le_bytes()); + if let Some((streams, coupled, map)) = vorbis_mapping(ch) { + h.push(1); // mapping family 1 (Vorbis order) + h.push(streams); + h.push(coupled); + h.extend_from_slice(map); + } else { + h.push(0); // mapping family 0 (mono / stereo) + } + h +} + +/// Parse an RFC 7845 `OpusHead` header if `data` starts with `"OpusHead"`. +pub fn parse_opus_head(data: &[u8]) -> Option { + if data.len() < 19 || &data[..8] != b"OpusHead" { + return None; + } + if data[8] != 1 { + return None; + } + let channels = data[9]; + if channels == 0 || channels > 8 { + return None; + } + let pre_skip = u16::from_le_bytes([data[10], data[11]]); + let input_rate = u32::from_le_bytes([data[12], data[13], data[14], data[15]]); + let output_gain = i16::from_le_bytes([data[16], data[17]]); + let mapping_family = data[18]; + let (stream_count, coupled_count, mapping, expected_len) = if mapping_family == 0 { + if channels > 2 { + return None; + } + let coupled = if channels == 2 { 1 } else { 0 }; + let map = if channels == 2 { vec![0, 1] } else { vec![0] }; + (1u8, coupled, map, 19usize) + } else { + let len = 21 + channels as usize; + if data.len() < len { + return None; + } + let sc = data[19]; + let cc = data[20]; + if sc == 0 || cc > sc { + return None; + } + let decoded_ch = sc as usize + cc as usize; + let map = data[21..len].to_vec(); + if map.iter().any(|&idx| idx != 255 && idx as usize >= decoded_ch) { + return None; + } + (sc, cc, map, len) + }; + Some(OpusHead { + channels, + pre_skip, + input_rate, + output_gain, + mapping_family, + stream_count, + coupled_count, + mapping, + raw: data[..expected_len].to_vec(), + }) +} + +// --------------------------------------------------------------------------------------- +// Packet extraction: Ogg Opus, length-prefixed [u16 LE len][pkt]... (+ zero padding), raw +// --------------------------------------------------------------------------------------- + +/// Try parsing one contiguous block of `[u16 LE len][opus_packet]...` with optional trailing zeros. +/// Returns `(packets, had_zero_padding)` on success. +fn try_length_prefixed_block<'a>(block: &'a [u8], multistream: bool) -> Option<(Vec<&'a [u8]>, bool)> { + if block.len() < 3 { + return None; + } + let mut packets = Vec::new(); + let mut pos = 0usize; + let mut zero_padded = false; + while pos < block.len() { + if pos + 2 > block.len() { + if block[pos..].iter().all(|&b| b == 0) && !packets.is_empty() { + zero_padded = true; + break; + } + return None; + } + let len = u16::from_le_bytes([block[pos], block[pos + 1]]) as usize; + if len == 0 { + if !packets.is_empty() && block[pos..].iter().all(|&b| b == 0) { + zero_padded = true; + break; + } + return None; + } + let start = pos + 2; + let end = start.checked_add(len)?; + if end > block.len() { + return None; + } + let pkt = &block[start..end]; + parse_packet(pkt, multistream)?; + packets.push(pkt); + pos = end; + } + if packets.is_empty() { + return None; + } + Some((packets, zero_padded)) +} + +/// Extract Opus audio packets from an Ogg Opus stream (skipping `OpusHead` and `OpusTags`). +fn extract_ogg_opus<'a>(data: &'a [u8], multistream: bool) -> Option>> { + if data.len() < 27 || &data[..4] != b"OggS" { + return None; + } + let mut packets: Vec> = Vec::new(); + let mut cur: Vec = Vec::new(); + let mut pos = 0usize; + while pos < data.len() { + if pos + 27 > data.len() || &data[pos..pos + 4] != b"OggS" { + return None; + } + let nseg = data[pos + 26] as usize; + let seg_start = pos + 27; + let mut body = seg_start + nseg; + if body > data.len() { + return None; + } + for &l in &data[seg_start..seg_start + nseg] { + let l = l as usize; + let next = body.checked_add(l)?; + if next > data.len() { + return None; + } + let slice = &data[body..next]; + body = next; + if cur.is_empty() && l < 255 { + if !slice.is_empty() + && !slice.starts_with(b"OpusHead") + && !slice.starts_with(b"OpusTags") + { + parse_packet(slice, multistream)?; + packets.push(Cow::Borrowed(slice)); + } + } else { + cur.extend_from_slice(slice); + if l < 255 { + if !cur.is_empty() + && !cur.starts_with(b"OpusHead") + && !cur.starts_with(b"OpusTags") + { + parse_packet(&cur, multistream)?; + packets.push(Cow::Owned(std::mem::take(&mut cur))); + } else { + cur.clear(); + } + } + } + } + pos = body; + } + Some(packets) +} + +/// Extract RFC 6716 Opus packets from a submitted audio buffer. +/// +/// Supports: +/// 1. Ogg Opus container (`"OggS"`), skipping `OpusHead`/`OpusTags`, +/// 2. Multi-block length-prefixed `[u16 LE len][packet]...` (+ zero padding) when `block_align >= 64`, +/// 3. Single-block length-prefixed `[u16 LE len][packet]...` (2+ packets or zero-padded block, +/// such as 2048 B console AWC blocks), +/// 4. A single raw RFC 6716 Opus packet, +/// 5. A single unpadded `[u16 LE len][packet]` if raw parsing rejected the buffer. +pub fn extract_packets<'a>(data: &'a [u8], block_align: u16, multistream: bool) -> Vec> { + if data.is_empty() { + return Vec::new(); + } + if data.starts_with(b"OggS") { + if let Some(pkts) = extract_ogg_opus(data, multistream) { + return pkts; + } + } + // Multiple fixed-size blocks (e.g. N * 2048 B AWC blocks) + let ba = block_align as usize; + if ba >= 64 && data.len() >= ba && data.len() % ba == 0 { + let mut all = Vec::new(); + let mut ok = true; + for chunk in data.chunks_exact(ba) { + if chunk.iter().all(|&b| b == 0) { + continue; + } + match try_length_prefixed_block(chunk, multistream) { + Some((pkts, _)) => all.extend(pkts.into_iter().map(Cow::Borrowed)), + None => { + ok = false; + break; + } + } + } + if ok && !all.is_empty() { + return all; + } + } + // Single length-prefixed buffer with >= 2 packets or zero-padding tail + if let Some((pkts, zero_padded)) = try_length_prefixed_block(data, multistream) { + if pkts.len() >= 2 || zero_padded { + return pkts.into_iter().map(Cow::Borrowed).collect(); + } + // Single length-prefixed packet with no zero tail: prefer raw RFC 6716 packet unless raw is invalid. + if parse_packet(data, multistream).is_some() { + return vec![Cow::Borrowed(data)]; + } + return pkts.into_iter().map(Cow::Borrowed).collect(); + } + if parse_packet(data, multistream).is_some() { + return vec![Cow::Borrowed(data)]; + } + Vec::new() +} + +/// Total expected PCM frames (samples per channel at `rate` Hz) across all extracted Opus packets. +/// Used as a fallback estimate if Media Foundation is unavailable. +pub fn estimate_buffer_frames(data: &[u8], block_align: u16, rate: u32, multistream: bool) -> Option { + let pkts = extract_packets(data, block_align, multistream); + if pkts.is_empty() { + return None; + } + let mut samples_48k = 0u64; + for p in &pkts { + let info = parse_packet(p, multistream)?; + samples_48k += info.total_samples_48k as u64; + } + Some((samples_48k * rate as u64) / 48_000) +} + +// --------------------------------------------------------------------------------------- +// Dynamic loader for mfplat.dll + MSOpusDecoder.dll +// --------------------------------------------------------------------------------------- + +type MfStartupFn = unsafe extern "system" fn(u32, u32) -> HRESULT; +type MfCreateMediaTypeFn = unsafe extern "system" fn(*mut *mut c_void) -> HRESULT; +type MfCreateSampleFn = unsafe extern "system" fn(*mut *mut c_void) -> HRESULT; +type MfCreateMemoryBufferFn = unsafe extern "system" fn(u32, *mut *mut c_void) -> HRESULT; +type DllGetClassObjectFn = unsafe extern "system" fn(*const GUID, *const GUID, *mut *mut c_void) -> HRESULT; + +struct MfRuntime { + create_media_type: MfCreateMediaTypeFn, + create_sample: MfCreateSampleFn, + create_memory_buffer: MfCreateMemoryBufferFn, + opus_get_class_object: DllGetClassObjectFn, +} + +static MF: OnceLock> = OnceLock::new(); + +fn mf_runtime() -> Result<&'static MfRuntime, String> { + MF.get_or_init(|| unsafe { + let load_fn = |module: usize, name: &str| -> Result { + crate::resolver::system_proc_in( + module, + &crate::pe::ImportName::Name { hint: 0, name: name.into() }, + ) + .ok_or_else(|| format!("missing export {name}")) + }; + + let mfplat = crate::resolver::system_module("mfplat.dll") + .ok_or_else(|| "mfplat.dll not available".to_string())?; + let startup: MfStartupFn = std::mem::transmute(load_fn(mfplat, "MFStartup")?); + let create_media_type: MfCreateMediaTypeFn = + std::mem::transmute(load_fn(mfplat, "MFCreateMediaType")?); + let create_sample: MfCreateSampleFn = + std::mem::transmute(load_fn(mfplat, "MFCreateSample")?); + let create_memory_buffer: MfCreateMemoryBufferFn = + std::mem::transmute(load_fn(mfplat, "MFCreateMemoryBuffer")?); + + let opus_dll = crate::resolver::system_module("MSOpusDecoder.dll") + .ok_or_else(|| "MSOpusDecoder.dll not available".to_string())?; + let opus_get_class_object: DllGetClassObjectFn = + std::mem::transmute(load_fn(opus_dll, "DllGetClassObject")?); + + let hr = startup(MF_VERSION, MFSTARTUP_LITE); + if hr.is_err() { + return Err(format!("MFStartup failed: {:#x}", hr.0 as u32)); + } + + Ok(MfRuntime { + create_media_type, + create_sample, + create_memory_buffer, + opus_get_class_object, + }) + }) + .as_ref() + .map_err(|e| e.clone()) +} + +/// Whether Windows' built-in `MSOpusDecoder.dll` + Media Foundation runtime is available. +pub fn is_available() -> bool { + mf_runtime().is_ok() +} + +fn mf_create_media_type(rt: &MfRuntime) -> Result { + let mut p = std::ptr::null_mut(); + let hr = unsafe { (rt.create_media_type)(&mut p) }; + if hr.is_err() || p.is_null() { + return Err(format!("MFCreateMediaType: {:#x}", hr.0 as u32)); + } + Ok(unsafe { IMFMediaType::from_raw(p) }) +} + +fn mf_create_sample(rt: &MfRuntime) -> Result { + let mut p = std::ptr::null_mut(); + let hr = unsafe { (rt.create_sample)(&mut p) }; + if hr.is_err() || p.is_null() { + return Err(format!("MFCreateSample: {:#x}", hr.0 as u32)); + } + Ok(unsafe { IMFSample::from_raw(p) }) +} + +fn mf_create_memory_buffer(rt: &MfRuntime, bytes: u32) -> Result { + let mut p = std::ptr::null_mut(); + let hr = unsafe { (rt.create_memory_buffer)(bytes, &mut p) }; + if hr.is_err() || p.is_null() { + return Err(format!("MFCreateMemoryBuffer({bytes}): {:#x}", hr.0 as u32)); + } + Ok(unsafe { IMFMediaBuffer::from_raw(p) }) +} + +fn create_opus_mft(rt: &MfRuntime) -> Result { + unsafe { + let mut cf_raw = std::ptr::null_mut(); + let hr = (rt.opus_get_class_object)(&CLSID_MS_OPUS_DECODER, &IClassFactory::IID, &mut cf_raw); + if hr.is_err() || cf_raw.is_null() { + return Err(format!("MSOpusDecoder DllGetClassObject: {:#x}", hr.0 as u32)); + } + let factory = IClassFactory::from_raw(cf_raw); + factory + .CreateInstance::<_, IMFTransform>(None) + .map_err(|e| format!("MSOpusDecoder CreateInstance: {:#x}", e.code().0 as u32)) + } +} + +// --------------------------------------------------------------------------------------- +// Single-stream MSOpusDecoder MFT (1 or 2 channels) + Multistream Decoder (1..=8 channels) +// --------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum OutputSampleFormat { + Pcm16, + Float32, +} + +struct SingleStreamDecoder { + mft: IMFTransform, + channels: u16, + output_rate: u32, + output_fmt: OutputSampleFormat, + mft_provides_samples: bool, + min_output_bytes: u32, + timestamp_100ns: i64, +} + +impl SingleStreamDecoder { + fn new(channels: u16, sample_rate: u32, head_bytes: Option<&[u8]>) -> Result { + let rt = mf_runtime()?; + let mft = create_opus_mft(rt)?; + let ch = channels.clamp(1, 2); + let rate = if sample_rate == 0 { 48_000 } else { sample_rate }; + + unsafe { + let in_type = mf_create_media_type(rt)?; + in_type + .SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Audio) + .map_err(|e| format!("SetGUID(MAJOR): {e}"))?; + in_type + .SetGUID(&MF_MT_SUBTYPE, &MFAudioFormat_Opus) + .map_err(|e| format!("SetGUID(Opus): {e}"))?; + in_type + .SetUINT32(&MF_MT_AUDIO_NUM_CHANNELS, ch as u32) + .map_err(|e| format!("SetUINT32(CH): {e}"))?; + in_type + .SetUINT32(&MF_MT_AUDIO_SAMPLES_PER_SECOND, rate) + .map_err(|e| format!("SetUINT32(RATE): {e}"))?; + if let Some(ud) = head_bytes { + in_type + .SetBlob(&MF_MT_USER_DATA, ud) + .map_err(|e| format!("SetBlob(USER_DATA): {e}"))?; + } + + if let Err(e) = mft.SetInputType(0, &in_type, 0) { + if rate != 48_000 { + in_type + .SetUINT32(&MF_MT_AUDIO_SAMPLES_PER_SECOND, 48_000) + .map_err(|e2| format!("SetUINT32(48k): {e2}"))?; + mft.SetInputType(0, &in_type, 0) + .map_err(|e2| format!("SetInputType(Opus 48k): {e2}"))?; + } else { + return Err(format!("SetInputType(Opus): {e}")); + } + } + + let mut dec = Self { + mft, + channels: ch, + output_rate: rate, + output_fmt: OutputSampleFormat::Pcm16, + mft_provides_samples: false, + min_output_bytes: 0, + timestamp_100ns: 0, + }; + dec.configure_output()?; + let _ = dec.mft.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0); + let _ = dec.mft.ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0); + Ok(dec) + } + } + + unsafe fn configure_output(&mut self) -> Result<(), String> { + let mut chosen: Option<(IMFMediaType, OutputSampleFormat, u32, u16)> = None; + for idx in 0..32u32 { + let Ok(mt) = self.mft.GetOutputAvailableType(0, idx) else { + break; + }; + let Ok(sub) = mt.GetGUID(&MF_MT_SUBTYPE) else { + continue; + }; + let bits = mt.GetUINT32(&MF_MT_AUDIO_BITS_PER_SAMPLE).unwrap_or(0); + let rate = mt.GetUINT32(&MF_MT_AUDIO_SAMPLES_PER_SECOND).unwrap_or(48_000); + let ch = mt.GetUINT32(&MF_MT_AUDIO_NUM_CHANNELS).unwrap_or(self.channels as u32) as u16; + if sub == MFAudioFormat_PCM && bits == 16 { + chosen = Some((mt, OutputSampleFormat::Pcm16, rate, ch)); + break; + } + if sub == MFAudioFormat_Float && bits == 32 && chosen.is_none() { + chosen = Some((mt, OutputSampleFormat::Float32, rate, ch)); + } + } + let (mt, fmt, rate, ch) = + chosen.ok_or_else(|| "MSOpusDecoder offered no PCM16 or Float32 output type".to_string())?; + self.mft + .SetOutputType(0, &mt, 0) + .map_err(|e| format!("SetOutputType: {e}"))?; + let info = self + .mft + .GetOutputStreamInfo(0) + .map_err(|e| format!("GetOutputStreamInfo: {e}"))?; + let provides = (info.dwFlags + & (MFT_OUTPUT_STREAM_PROVIDES_SAMPLES.0 as u32 + | MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES.0 as u32)) + != 0; + self.output_fmt = fmt; + self.output_rate = rate; + self.channels = ch; + self.mft_provides_samples = provides; + let bytes_per_sample = match fmt { + OutputSampleFormat::Pcm16 => 2u32, + OutputSampleFormat::Float32 => 4u32, + }; + let max_pkt_bytes = MAX_PACKET_SAMPLES_48K * ch as u32 * bytes_per_sample; + self.min_output_bytes = info.cbSize.max(max_pkt_bytes); + Ok(()) + } + + fn flush(&mut self) { + unsafe { + let _ = self.mft.ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0); + let _ = self.mft.ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0); + } + self.timestamp_100ns = 0; + } + + fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + let info = parse_packet(packet, false) + .ok_or_else(|| "invalid RFC 6716 Opus packet".to_string())?; + let rt = mf_runtime()?; + let dur = duration_100ns(info.total_samples_48k); + let before = out.len(); + + unsafe { + let sample = mf_create_sample(rt)?; + let buf = mf_create_memory_buffer(rt, packet.len() as u32)?; + let mut ptr = std::ptr::null_mut(); + buf.Lock(&mut ptr, None, None) + .map_err(|e| format!("input Lock: {e}"))?; + std::ptr::copy_nonoverlapping(packet.as_ptr(), ptr, packet.len()); + let _ = buf.Unlock(); + buf.SetCurrentLength(packet.len() as u32) + .map_err(|e| format!("input SetCurrentLength: {e}"))?; + sample + .AddBuffer(&buf) + .map_err(|e| format!("input AddBuffer: {e}"))?; + let _ = sample.SetSampleTime(self.timestamp_100ns); + let _ = sample.SetSampleDuration(dur); + self.timestamp_100ns = self.timestamp_100ns.saturating_add(dur); + + match self.mft.ProcessInput(0, &sample, 0) { + Ok(()) => {} + Err(e) if e.code() == MF_E_NOTACCEPTING => { + self.drain_output(rt, out)?; + self.mft + .ProcessInput(0, &sample, 0) + .map_err(|e2| format!("ProcessInput retry: {e2}"))?; + } + Err(e) => return Err(format!("ProcessInput: {e}")), + } + + self.drain_output(rt, out)?; + } + + let added = out.len() - before; + Ok(added / self.channels.max(1) as usize) + } + + unsafe fn drain_output(&mut self, rt: &MfRuntime, out: &mut Vec) -> Result<(), String> { + loop { + let alloc_sample = if self.mft_provides_samples { + None + } else { + let s = mf_create_sample(rt)?; + let b = mf_create_memory_buffer(rt, self.min_output_bytes)?; + s.AddBuffer(&b).map_err(|e| format!("output AddBuffer: {e}"))?; + Some(s) + }; + + let mut out_buf = [MFT_OUTPUT_DATA_BUFFER { + dwStreamID: 0, + pSample: ManuallyDrop::new(alloc_sample), + dwStatus: 0, + pEvents: ManuallyDrop::new(None), + }]; + let mut status = 0u32; + let res = self.mft.ProcessOutput(0, &mut out_buf, &mut status); + + // Always take ownership back out of ManuallyDrop so COM refcounts never leak. + let sample = ManuallyDrop::into_inner(std::ptr::read(&out_buf[0].pSample)); + let _events = ManuallyDrop::into_inner(std::ptr::read(&out_buf[0].pEvents)); + + match res { + Ok(()) => { + if let Some(s) = sample { + self.append_sample_pcm16(&s, out)?; + } + } + Err(e) if e.code() == MF_E_TRANSFORM_NEED_MORE_INPUT => break, + Err(e) if e.code() == MF_E_TRANSFORM_STREAM_CHANGE => { + self.configure_output()?; + continue; + } + Err(e) => return Err(format!("ProcessOutput: {e}")), + } + } + Ok(()) + } + + unsafe fn append_sample_pcm16(&self, sample: &IMFSample, out: &mut Vec) -> Result<(), String> { + let buf = sample + .ConvertToContiguousBuffer() + .map_err(|e| format!("ConvertToContiguousBuffer: {e}"))?; + let mut ptr = std::ptr::null_mut(); + let mut cur_len = 0u32; + buf.Lock(&mut ptr, None, Some(&mut cur_len)) + .map_err(|e| format!("output Lock: {e}"))?; + if cur_len > 0 && !ptr.is_null() { + let bytes = std::slice::from_raw_parts(ptr, cur_len as usize); + match self.output_fmt { + OutputSampleFormat::Pcm16 => { + let n = bytes.len() / 2; + out.reserve(n); + for chunk in bytes.chunks_exact(2) { + out.push(i16::from_le_bytes([chunk[0], chunk[1]])); + } + } + OutputSampleFormat::Float32 => { + let n = bytes.len() / 4; + out.reserve(n); + for chunk in bytes.chunks_exact(4) { + let f = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); + out.push(f32_to_i16(f)); + } + } + } + } + let _ = buf.Unlock(); + Ok(()) + } +} + +/// Stateful RFC 6716 / RFC 7845 Opus decoder (1–8 channels) backed by `MSOpusDecoder.dll`. +/// +/// `MSOpusDecoder.dll` registers `ThreadingModel = Both` (free-threaded); access is serialized +/// via `&mut self` (or an external `Mutex`). +pub struct Decoder { + streams: Vec, + channels: u16, + coupled_count: u8, + mapping: Vec, + output_rate: u32, + multistream: bool, + pre_skip: u16, + pre_skip_left: usize, + output_gain_scale: f32, +} + +// SAFETY: MSOpusDecoder.dll is ThreadingModel=Both (MTA-safe) and Decoder requires &mut self. +unsafe impl Send for Decoder {} + +impl Decoder { + /// Create a new Opus decoder for `channels` (1..=8), `sample_rate` Hz, and optional + /// codec-private `extra_data` (e.g. RFC 7845 `OpusHead` from `WAVEFORMATEX` extra bytes). + pub fn new(channels: u16, sample_rate: u32, extra_data: &[u8]) -> Result { + let rate = if sample_rate == 0 { 48_000 } else { sample_rate }; + let parsed = parse_opus_head(extra_data); + let head = match parsed { + Some(h) => h, + None => { + let raw = build_opus_head(channels.clamp(1, 8) as u8, rate, 0, 0); + parse_opus_head(&raw).unwrap() + } + }; + + let ch = head.channels as u16; + let multistream = head.stream_count > 1 || ch > 2; + let mut streams = Vec::with_capacity(head.stream_count as usize); + if !multistream { + let ud = build_opus_head(ch as u8, rate, 0, 0); + streams.push(SingleStreamDecoder::new(ch, rate, Some(&ud))?); + } else { + for s in 0..head.stream_count { + let sch = if s < head.coupled_count { 2 } else { 1 }; + let ud = build_opus_head(sch as u8, rate, 0, 0); + streams.push(SingleStreamDecoder::new(sch, rate, Some(&ud))?); + } + } + let output_rate = streams[0].output_rate; + let pre_skip_scaled = ((head.pre_skip as u64 * output_rate as u64) / 48_000) as usize; + let output_gain_scale = if head.output_gain == 0 { + 1.0 + } else { + 10.0f32.powf(head.output_gain as f32 / (20.0 * 256.0)) + }; + + Ok(Self { + streams, + channels: ch, + coupled_count: head.coupled_count, + mapping: head.mapping, + output_rate, + multistream, + pre_skip: head.pre_skip, + pre_skip_left: pre_skip_scaled, + output_gain_scale, + }) + } + + pub fn channels(&self) -> u16 { + self.channels + } + + pub fn output_rate(&self) -> u32 { + self.output_rate + } + + pub fn is_multistream(&self) -> bool { + self.multistream + } + + /// Reset internal decoder state (e.g. on `FlushSourceBuffers` or stream boundary). + pub fn flush(&mut self) { + for s in &mut self.streams { + s.flush(); + } + self.pre_skip_left = ((self.pre_skip as u64 * self.output_rate as u64) / 48_000) as usize; + } + + /// Decode one RFC 6716 (single-stream or multistream) Opus packet and append interleaved + /// PCM16 samples to `out`. Returns the number of PCM frames (samples per channel) appended. + pub fn decode_packet(&mut self, packet: &[u8], out: &mut Vec) -> Result { + let start = out.len(); + let ch = self.channels as usize; + + if !self.multistream { + self.streams[0].decode_packet(packet, out)?; + } else { + let subs = split_multistream_packet(packet, self.streams.len()) + .ok_or_else(|| "invalid RFC 7845 multistream Opus packet".to_string())?; + let mut decoded: Vec> = Vec::with_capacity(self.streams.len()); + let mut frames = usize::MAX; + for (i, sub) in subs.iter().enumerate() { + let mut buf = Vec::new(); + let n = self.streams[i].decode_packet(sub, &mut buf)?; + frames = frames.min(n); + decoded.push(buf); + } + if frames == usize::MAX { + frames = 0; + } + // Map decoded stream channels to output channels per RFC 7845 mapping table. + let coupled = self.coupled_count as usize; + out.reserve(frames * ch); + for f in 0..frames { + for &idx in &self.mapping { + let sample = if idx == 255 { + 0i16 + } else { + let idx = idx as usize; + if idx < coupled * 2 { + let s = idx / 2; + let c = idx % 2; + decoded[s][f * 2 + c] + } else { + let s = coupled + (idx - coupled * 2); + decoded[s][f] + } + }; + out.push(sample); + } + } + } + + // Apply RFC 7845 output gain if non-zero. + if (self.output_gain_scale - 1.0).abs() > 1e-6 { + for s in &mut out[start..] { + let v = (*s as f32 * self.output_gain_scale).round(); + *s = v.clamp(i16::MIN as f32, i16::MAX as f32) as i16; + } + } + + // Trim RFC 7845 pre-skip samples if declared by OpusHead. + if self.pre_skip_left > 0 { + let produced_frames = (out.len() - start) / ch; + let drop_frames = produced_frames.min(self.pre_skip_left); + if drop_frames > 0 { + out.drain(start..start + drop_frames * ch); + self.pre_skip_left -= drop_frames; + } + } + + Ok((out.len() - start) / ch) + } + + /// Extract and decode all Opus packets from `data` into interleaved PCM16. + pub fn decode_buffer(&mut self, data: &[u8], block_align: u16) -> Result, String> { + let packets = extract_packets(data, block_align, self.multistream); + if packets.is_empty() { + return Err("buffer contains no valid RFC 6716 Opus packets".to_string()); + } + let mut out = Vec::new(); + for pkt in &packets { + self.decode_packet(pkt, &mut out)?; + } + Ok(out) + } +} + +#[inline] +fn f32_to_i16(x: f32) -> i16 { + if !x.is_finite() { + return 0; + } + let scaled = (x * 32768.0).round(); + scaled.clamp(i16::MIN as f32, i16::MAX as f32) as i16 +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + #[test] + fn rfc6716_table2_all_32_configs() { + let expected: [(Mode, Bandwidth, u32); 32] = [ + (Mode::Silk, Bandwidth::Narrow, 480), + (Mode::Silk, Bandwidth::Narrow, 960), + (Mode::Silk, Bandwidth::Narrow, 1920), + (Mode::Silk, Bandwidth::Narrow, 2880), + (Mode::Silk, Bandwidth::Medium, 480), + (Mode::Silk, Bandwidth::Medium, 960), + (Mode::Silk, Bandwidth::Medium, 1920), + (Mode::Silk, Bandwidth::Medium, 2880), + (Mode::Silk, Bandwidth::Wide, 480), + (Mode::Silk, Bandwidth::Wide, 960), + (Mode::Silk, Bandwidth::Wide, 1920), + (Mode::Silk, Bandwidth::Wide, 2880), + (Mode::Hybrid, Bandwidth::SuperWide, 480), + (Mode::Hybrid, Bandwidth::SuperWide, 960), + (Mode::Hybrid, Bandwidth::Full, 480), + (Mode::Hybrid, Bandwidth::Full, 960), + (Mode::Celt, Bandwidth::Narrow, 120), + (Mode::Celt, Bandwidth::Narrow, 240), + (Mode::Celt, Bandwidth::Narrow, 480), + (Mode::Celt, Bandwidth::Narrow, 960), + (Mode::Celt, Bandwidth::Wide, 120), + (Mode::Celt, Bandwidth::Wide, 240), + (Mode::Celt, Bandwidth::Wide, 480), + (Mode::Celt, Bandwidth::Wide, 960), + (Mode::Celt, Bandwidth::SuperWide, 120), + (Mode::Celt, Bandwidth::SuperWide, 240), + (Mode::Celt, Bandwidth::SuperWide, 480), + (Mode::Celt, Bandwidth::SuperWide, 960), + (Mode::Celt, Bandwidth::Full, 120), + (Mode::Celt, Bandwidth::Full, 240), + (Mode::Celt, Bandwidth::Full, 480), + (Mode::Celt, Bandwidth::Full, 960), + ]; + for (cfg, exp) in expected.iter().enumerate() { + assert_eq!(config_info(cfg as u8), *exp, "config {cfg}"); + } + assert_eq!(duration_100ns(120), 25_000); + assert_eq!(duration_100ns(240), 50_000); + assert_eq!(duration_100ns(480), 100_000); + assert_eq!(duration_100ns(960), 200_000); + assert_eq!(duration_100ns(1920), 400_000); + assert_eq!(duration_100ns(2880), 600_000); + } + + #[test] + fn rfc6716_packet_codes_and_limits() { + let p = parse_packet(&[0xFC, 0x01, 0x02], false).unwrap(); + assert_eq!((p.config, p.stereo, p.code, p.frames, p.total_samples_48k), (31, true, 0, 1, 960)); + + assert!(parse_packet(&[0xF9, 0xAA, 0xBB], false).is_some()); + assert!(parse_packet(&[0xF9, 0xAA], false).is_none()); + + let p = parse_packet(&[0xFA, 3, 1, 2, 3, 4, 5], false).unwrap(); + assert_eq!((p.frames, p.total_samples_48k), (2, 1920)); + assert!(parse_packet(&[0xFA, 10, 1, 2], false).is_none()); + + let p = parse_packet(&[0x7B, 3, 1, 2, 3, 4, 5, 6], false).unwrap(); + assert_eq!((p.frames, p.total_samples_48k), (3, 2880)); + assert!(parse_packet(&[0x7B, 3, 1, 2, 3, 4], false).is_none()); + + let p = parse_packet(&[0x73, 0xC2, 2, 2, 0xAA, 0xBB, 0xCC, 0, 0], false).unwrap(); + assert_eq!((p.frames, p.total_samples_48k), (2, 960)); + + assert!(parse_packet(&[0xFB, 6, 0, 0, 0, 0, 0, 0], false).is_some()); + assert!(parse_packet(&[0xFB, 7, 0, 0, 0, 0, 0, 0, 0], false).is_none()); + assert!(parse_packet(&[0xFB, 0], false).is_none()); + } + + #[test] + fn opus_head_roundtrip_mono_stereo_surround() { + for ch in 1..=8u8 { + let raw = build_opus_head(ch, 48_000, 312, -256); + let h = parse_opus_head(&raw).unwrap(); + assert_eq!(h.channels, ch); + assert_eq!(h.input_rate, 48_000); + assert_eq!(h.pre_skip, 312); + assert_eq!(h.output_gain, -256); + assert_eq!(h.mapping_family, if ch <= 2 { 0 } else { 1 }); + } + } + + #[test] + fn framing_detection_awc_blocks_and_raw() { + let pkt1 = [0x78u8, 0x11, 0x22, 0x33]; + let pkt2 = [0xF8u8, 0x44, 0x55]; + let mut block = vec![0u8; 2048]; + block[0..2].copy_from_slice(&(pkt1.len() as u16).to_le_bytes()); + block[2..6].copy_from_slice(&pkt1); + block[6..8].copy_from_slice(&(pkt2.len() as u16).to_le_bytes()); + block[8..11].copy_from_slice(&pkt2); + let got = extract_packets(&block, 0, false); + assert_eq!(got.len(), 2); + assert_eq!(got[0].as_ref(), &pkt1); + assert_eq!(got[1].as_ref(), &pkt2); + + let mut two = block.clone(); + two.extend_from_slice(&block); + let got2 = extract_packets(&two, 2048, false); + assert_eq!(got2.len(), 4); + + let mut tricky = vec![0u8; 250]; + tricky[0] = 0xF8; + tricky[1] = 0x00; + let got_raw = extract_packets(&tricky, 1, false); + assert_eq!(got_raw.len(), 1); + assert_eq!(got_raw[0].as_ref(), tricky.as_slice()); + } + + // Compact real libopus RFC 6716 test packets (440 Hz mono, 440/880 Hz stereo, SILK/Hybrid/CELT, 5.1). + const MONO_HYBRID_20MS_HEAD: &[u8] = &[79, 112, 117, 115, 72, 101, 97, 100, 1, 1, 56, 1, 128, 187, 0, 0, 0, 0, 0]; + pub(crate) const MONO_HYBRID_20MS: &[&[u8]] = &[ + &[0x78, 0x81, 0x7b, 0xc6, 0x11, 0x76, 0xf4, 0x75, 0x00, 0x00, 0x07, 0x8e, 0xca, 0x69, 0xdb, 0xbb, 0xcc, 0x48, 0xdc, 0x16, 0xbd, 0x9b, 0xd3, 0x58, 0x27, 0x78, 0x93, 0xbc, 0x37, 0x44, 0x5e, 0xcf, 0x2d, 0x97, 0x00, 0x69, 0x80, 0x11, 0x80, 0x2c, 0x03, 0x38, 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xa9, 0xcf, 0x0b, 0x8a, 0x81, 0xa5, 0xb5, 0xf3, 0x01, 0x45, 0xb1], + ]; + const MONO_CODE3_60MS: &[&[u8]] = &[ + &[0x7b, 0x83, 0x27, 0x27, 0x82, 0x02, 0xb0, 0x35, 0xed, 0x11, 0xad, 0xa5, 0x17, 0xe6, 0x7f, 0x8f, 0x87, 0xad, 0x63, 0x65, 0x38, 0x0b, 0x91, 0x53, 0x0d, 0x78, 0xde, 0xf4, 0xc5, 0xd4, 0x80, 0x81, 0x3b, 0x4b, 0xab, 0x38, 0x52, 0x5b, 0x09, 0x7f, 0x17, 0x1b, 0x79, 0xaa, 0x7e, 0x84, 0x2f, 0x24, 0x6b, 0xa0, 0xbc, 0xfd, 0x0a, 0x5b, 0xb9, 0x1d, 0x64, 0xfc, 0x53, 0xcc, 0x60, 0x3c, 0x99, 0x6c, 0x66, 0x38, 0x1e, 0x5b, 0x74, 0x51, 0x1c, 0xe5, 0x39, 0x44, 0x4e, 0xba, 0x2b, 0x66, 0xb2, 0xb4, 0xd2, 0x06, 0x9f, 0x6d, 0x4e, 0x97, 0x56, 0x68, 0x72, 0x72, 0xdc, 0xa2, 0x63, 0x5c, 0x47, 0x6c, 0x9a, 0x78, 0xde, 0x47, 0x6e, 0xbe, 0x0e, 0xb8, 0x4e, 0x73, 0x0c, 0x42, 0x45, 0xa5, 0x40, 0x16, 0x94, 0x29, 0x8b], + ]; + const MONO_CELT_10MS: &[&[u8]] = &[ + &[0xf0, 0xb4, 0xcd, 0x66, 0xcc, 0xcb, 0xa8, 0xe4, 0xa4, 0x4b, 0x77, 0x2a, 0xfd, 0x0c, 0x8f, 0xb9, 0xb8, 0x29, 0x30, 0x4a, 0xb4, 0x8d, 0x09, 0xbd, 0x99, 0x19, 0xb0, 0xc8, 0xed, 0xd3, 0xb1, 0x82, 0xcd, 0x45, 0x49, 0x24, 0x13, 0xa8, 0x02, 0x55, 0xed, 0x28, 0x1a, 0x0f, 0x70, 0x77, 0x00, 0x5b, 0xfd, 0xd8, 0x99, 0x7b, 0x14, 0x89, 0xb8, 0x50, 0x96, 0xbd, 0x84, 0x98, 0xf0, 0x72, 0xa6, 0x32, 0xbb, 0x21, 0xaf, 0xa6, 0xca, 0xc1, 0x8b, 0x18, 0x6d, 0x4f, 0xd1, 0x16, 0x14, 0xe1, 0x49, 0x94, 0x3f, 0x54, 0x27, 0x99, 0x9c, 0x23, 0xff, 0x3b, 0xc7, 0xbf, 0x53, 0x0e, 0x18, 0x1e, 0x4c, 0x17, 0xef, 0x6d, 0x27, 0xf7, 0x9d, 0x5e, 0xc8, 0xed, 0x0f, 0x54, 0x0b, 0x9d, 0x14, 0xbf, 0xa8, 0xb9, 0x72, 0x6b, 0x3e, 0x0c, 0x5a, 0xd4, 0xd0, 0x9f, 0x47, 0x87, 0x6d, 0x25, 0xc2, 0x9f, 0xa9, 0x63, 0x9e, 0xea, 0xa1, 0x16, 0x99, 0xa1, 0x25, 0xd6, 0x7f, 0x84, 0x11, 0xde, 0x81, 0xeb, 0xde, 0x56, 0xd3, 0x64, 0x85, 0xca, 0xdb, 0x95, 0x1f, 0x27, 0x34, 0x31, 0x9f, 0x3c, 0x77, 0x6d], + &[0xf0, 0xb3, 0x8b, 0x65, 0x03, 0x2f, 0xa0, 0x43, 0x16, 0x98, 0x92, 0x38, 0x19, 0x4e, 0x50, 0x2b, 0x86, 0x08, 0x36, 0x63, 0xb1, 0x41, 0xec, 0xed, 0xae, 0x10, 0x5b, 0x9f, 0xea, 0x59, 0xdb, 0x9b, 0x37, 0x2d, 0x8c, 0xc6, 0x38, 0x4b, 0x9a, 0x21, 0x9a, 0x7f, 0x90, 0xd7, 0xfb, 0x13, 0xb4, 0xfd, 0xbe, 0x38, 0x5f, 0x15, 0xb8, 0xc9, 0x3c, 0x10, 0x4e, 0x43, 0x5c, 0x91, 0x63, 0x6f, 0xe7, 0x27, 0xed, 0xae], + ]; + const MONO_CELT_5MS: &[&[u8]] = &[ + &[0xe8, 0xb5, 0x34, 0x27, 0x9d, 0xd6, 0x3d, 0xfd, 0x6a, 0x91, 0xc0, 0xea, 0x6b, 0x56, 0x74, 0x99, 0xca, 0xbc, 0x57, 0x8d, 0x8f, 0x15, 0xfb, 0xdc, 0x45, 0x17, 0xd5, 0xd4, 0xae, 0x69, 0xc2, 0x53, 0x3a, 0x9a, 0x72, 0x5f, 0x1b, 0x28, 0xc9, 0xd4, 0xc0, 0xda, 0x55, 0xc9, 0x52, 0xf0, 0x6d, 0xc6, 0x88, 0x0e, 0xce, 0x5b, 0x6e, 0x98, 0x37, 0x47, 0xd6, 0xed, 0xcc, 0x53, 0x41, 0xbf, 0xd9, 0x85, 0x5e, 0x01, 0x6f, 0x2c, 0x74, 0x35, 0x2c], + &[0xe8, 0xb3, 0x10, 0xa2, 0x14, 0x17, 0x6b, 0x67, 0xbe, 0x9c, 0x54, 0x83, 0xc5, 0x29, 0xf3, 0x21, 0xcb, 0xdb, 0xea, 0xc4, 0x78, 0x11, 0x93, 0x64, 0xd8, 0x52, 0x51, 0xed, 0x9b, 0xf2, 0x1f, 0xc4, 0x03, 0x2b, 0x2f, 0xdb, 0x6e], + ]; + const MONO_CELT_2_5MS: &[&[u8]] = &[ + &[0xe0, 0x73, 0xf6, 0x70, 0x46, 0x04, 0xc8, 0x84, 0x73, 0x77, 0x5f, 0xb0, 0x74, 0x6d, 0xe1, 0xb0, 0x0f, 0x51, 0xa7, 0x3a, 0x67, 0xba, 0x98, 0x50, 0xfc, 0xbd, 0x94, 0x02], + &[0xe0, 0xb4, 0x44, 0xd2, 0x0f, 0x30, 0xd6, 0xdb, 0x01, 0x69, 0xf3, 0xf7, 0xb4, 0xc7, 0x56, 0x3e, 0xdf, 0x4e, 0x1d, 0x45, 0xae], + ]; + const SURROUND51_20MS_HEAD: &[u8] = &[79, 112, 117, 115, 72, 101, 97, 100, 1, 6, 56, 1, 128, 187, 0, 0, 0, 0, 1, 4, 2, 0, 4, 1, 2, 3, 5]; + const SURROUND51_20MS: &[&[u8]] = &[ + &[0xfc, 0x02, 0xff, 0xfe, 0xfc, 0x02, 0xff, 0xfe, 0x78, 0x5c, 0x81, 0x7b, 0xc6, 0x11, 0x76, 0xf4, 0x75, 0x00, 0x00, 0x07, 0x8e, 0xca, 0x69, 0xdb, 0xbb, 0xcc, 0x48, 0xdc, 0x16, 0xbd, 0x9b, 0xd3, 0x58, 0x27, 0x78, 0x93, 0xbc, 0x37, 0x44, 0x5e, 0xcf, 0x2d, 0x97, 0x00, 0x69, 0x80, 0x11, 0x80, 0x2c, 0x03, 0x38, 0xab, 0x45, 0x61, 0xfd, 0x89, 0xb7, 0x7e, 0x0d, 0x17, 0xbf, 0x20, 0xa5, 0x2b, 0xb5, 0xd8, 0x89, 0x9b, 0x71, 0x04, 0x2a, 0x3b, 0x68, 0x89, 0xb8, 0x5a, 0xef, 0x37, 0x35, 0xa4, 0x0f, 0x35, 0x4b, 0xc7, 0x72, 0x05, 0x78, 0x74, 0xff, 0xc1, 0xe3, 0x95, 0x9b, 0x67, 0x7e, 0xcb, 0x20, 0xd5, 0xff, 0x17, 0x1b, 0x02, 0x98, 0xff, 0xfe], + &[0xfc, 0x02, 0xff, 0xfe, 0xfc, 0x02, 0xff, 0xfe, 0x78, 0x34, 0x9e, 0x1e, 0xa1, 0xe7, 0xfc, 0x95, 0x4d, 0x4e, 0xaa, 0x18, 0x01, 0xbc, 0x6b, 0xfc, 0x27, 0xeb, 0xac, 0xa4, 0xee, 0xeb, 0xe4, 0xd6, 0x01, 0x11, 0x26, 0x0b, 0xc0, 0xae, 0xfb, 0x24, 0x73, 0x57, 0xd4, 0xe5, 0x70, 0xdf, 0xc1, 0x94, 0xdd, 0xc4, 0xa4, 0xa5, 0x71, 0xe2, 0x96, 0xe1, 0x6b, 0x31, 0x09, 0xd1, 0xb7, 0xa6, 0x98, 0xff, 0xfe], + ]; + + fn goertzel_energy(samples: &[f64], rate: f64, freq_hz: f64) -> f64 { + let n = samples.len(); + let k = (0.5 + (n as f64 * freq_hz) / rate).floor(); + let w = (2.0 * std::f64::consts::PI * k) / n as f64; + let coeff = 2.0 * w.cos(); + let (mut s1, mut s2) = (0.0, 0.0); + for &x in samples { + let s0 = x + coeff * s1 - s2; + s2 = s1; + s1 = s0; + } + (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt() / (n as f64) + } + + #[test] + fn decode_silk_hybrid_celt_all_frame_sizes() { + if !is_available() { + eprintln!("skipping: MSOpusDecoder.dll not available"); + return; + } + let cases: &[(&str, &[&[u8]], usize)] = &[ + ("Hybrid FB 20ms", MONO_HYBRID_20MS, 960), + ("SILK WB 40ms", MONO_SILK_40MS, 1920), + ("Hybrid code-3 60ms", MONO_CODE3_60MS, 2880), + ("CELT FB 10ms", MONO_CELT_10MS, 480), + ("CELT FB 5ms", MONO_CELT_5MS, 240), + ("CELT FB 2.5ms", MONO_CELT_2_5MS, 120), + ]; + for &(name, pkts, expected_per_pkt) in cases { + let mut dec = Decoder::new(1, 48_000, &[]).expect(name); + let mut pcm = Vec::new(); + for &pkt in pkts { + let n = dec.decode_packet(pkt, &mut pcm).expect(name); + assert_eq!(n, expected_per_pkt, "{name}: frame count"); + } + let peak = pcm.iter().map(|&s| s.unsigned_abs()).max().unwrap_or(0); + assert!(peak > 2000, "{name}: decoded PCM looks silent (peak={peak})"); + } + // Verify 440 Hz tone accuracy on the 100 ms Hybrid mono stream + let mut dec = Decoder::new(1, 48_000, &[]).unwrap(); + let mut pcm = Vec::new(); + for &pkt in MONO_HYBRID_20MS { + dec.decode_packet(pkt, &mut pcm).unwrap(); + } + let f: Vec = pcm.iter().skip(480).map(|&s| s as f64 / 32768.0).collect(); + let e440 = goertzel_energy(&f, 48_000.0, 440.0); + let e880 = goertzel_energy(&f, 48_000.0, 880.0); + assert!(e440 > 0.04 && e440 > e880 * 10.0, "440 Hz vs 880 Hz: {e440} vs {e880}"); + } + + #[test] + fn decode_stereo_and_multistream_5_1() { + if !is_available() { + eprintln!("skipping: MSOpusDecoder.dll not available"); + return; + } + // Stereo: 440 Hz on left, 880 Hz on right + let mut dec = Decoder::new(2, 48_000, &[]).unwrap(); + let mut pcm = Vec::new(); + for &pkt in STEREO_CELT_20MS { + assert_eq!(dec.decode_packet(pkt, &mut pcm).unwrap(), 960); + } + let left: Vec = pcm.chunks_exact(2).skip(480).map(|c| c[0] as f64 / 32768.0).collect(); + let right: Vec = pcm.chunks_exact(2).skip(480).map(|c| c[1] as f64 / 32768.0).collect(); + assert!(goertzel_energy(&left, 48_000.0, 440.0) > goertzel_energy(&left, 48_000.0, 880.0) * 10.0); + assert!(goertzel_energy(&right, 48_000.0, 880.0) > goertzel_energy(&right, 48_000.0, 440.0) * 10.0); + + // 5.1 surround (6 channels, mapping family 1): channel 1 (FC) carries the 440 Hz tone + let mut dec51 = Decoder::new(6, 48_000, SURROUND51_20MS_HEAD).unwrap(); + let mut pcm51 = Vec::new(); + let f0 = dec51.decode_packet(SURROUND51_20MS[0], &mut pcm51).unwrap(); + let f1 = dec51.decode_packet(SURROUND51_20MS[1], &mut pcm51).unwrap(); + // OpusHead declares pre_skip = 312 -> first packet trimmed by 312 samples + assert_eq!((f0, f1), (960 - 312, 960)); + let peak_ch = |c: usize| pcm51.chunks_exact(6).map(|fr| fr[c].unsigned_abs()).max().unwrap_or(0); + assert!(peak_ch(1) > 2000, "center channel should carry the tone"); + assert!(peak_ch(0) < 50 && peak_ch(5) < 50, "silent channels should remain near zero"); + } + + #[test] + fn decode_awc_block_preskip_rate_and_flush() { + if !is_available() { + eprintln!("skipping: MSOpusDecoder.dll not available"); + return; + } + // Pack 5 mono 20 ms packets into a 2048-byte zero-padded AWC block + let mut block = vec![0u8; 2048]; + let mut pos = 0; + for &pkt in MONO_HYBRID_20MS { + block[pos..pos + 2].copy_from_slice(&(pkt.len() as u16).to_le_bytes()); + block[pos + 2..pos + 2 + pkt.len()].copy_from_slice(pkt); + pos += 2 + pkt.len(); + } + let mut dec = Decoder::new(1, 48_000, MONO_HYBRID_20MS_HEAD).unwrap(); + let pcm = dec.decode_buffer(&block, 2048).unwrap(); + assert_eq!(pcm.len(), 5 * 960 - 312); + + // Flush resets pre-skip and decoder state cleanly + dec.flush(); + let pcm2 = dec.decode_buffer(&block, 2048).unwrap(); + assert_eq!(pcm2.len(), 5 * 960 - 312); + + // 24 kHz output rate: 20 ms = 480 samples + let mut d24 = Decoder::new(1, 24_000, &[]).unwrap(); + assert_eq!(d24.output_rate(), 24_000); + let mut out24 = Vec::new(); + assert_eq!(d24.decode_packet(MONO_HYBRID_20MS[0], &mut out24).unwrap(), 480); + + // Invalid packet returns Err without breaking subsequent valid decodes + assert!(d24.decode_packet(&[0xFB, 0], &mut out24).is_err()); + assert_eq!(d24.decode_packet(MONO_HYBRID_20MS[1], &mut out24).unwrap(), 480); + } +} diff --git a/crates/xcl/src/hle/xaudio2.rs b/crates/xcl/src/hle/xaudio2.rs index 7cbb5d1..e4c60a5 100644 --- a/crates/xcl/src/hle/xaudio2.rs +++ b/crates/xcl/src/hle/xaudio2.rs @@ -1,21 +1,26 @@ //! xaudio2_9.dll – console XAudio2 on top of the Windows XAudio2 2.9. //! -//! The console API is the Windows 2.9 API plus XMA2 source voices (decoded by audio -//! hardware on the console) and a few console-only flags. `XAudio2Create` / -//! `XAudio2CreateWithVersionInfo` create the genuine Windows engine with console-only -//! flags dropped and patch its vtables **in place** (the Windows classes have internal -//! virtual methods after the public ones, so a vtable copy of the public part is not -//! safe): +//! The console API is the Windows 2.9 API plus compressed source voices (XMA2, Opus) and a +//! few console-only flags. `XAudio2Create` / `XAudio2CreateWithVersionInfo` create the +//! genuine Windows engine with console-only flags dropped and patch its vtables **in place** +//! (the Windows classes have internal virtual methods after the public ones, so a vtable +//! copy of the public part is not safe): //! -//! * IXAudio2 slot 5 `CreateSourceVoice` – XMA/XMA2 formats become a PCM16 voice with -//! the same channel count and sample rate; other formats pass through, and a compressed -//! format Windows rejects (e.g. Opus, 0x704F) also gets a silent PCM16 voice, +//! * IXAudio2 slot 5 `CreateSourceVoice` – Opus formats (`WAVE_FORMAT_OPUS` 0x704F or +//! `WAVE_FORMAT_EXTENSIBLE` with `MFAudioFormat_Opus`) become PCM16 voices backed by a +//! real RFC 6716 / RFC 7845 decoder (`hle::opus`, using Windows' `MSOpusDecoder.dll`); +//! XMA/XMA2 and any other format Windows rejects become silent PCM16 voices of matching +//! length, //! * IXAudio2 slot 7 `CreateMasteringVoice` – console device ids are ignored (default //! device); on failure retried with default channels/rate and the game-effects category, -//! * IXAudio2SourceVoice slot 21 `SubmitSourceBuffer` – on such voices the buffer becomes -//! silence of the same length, so callbacks (OnBufferEnd, OnStreamEnd, loops) keep the -//! title's timing, -//! * IXAudio2SourceVoice slot 18 `DestroyVoice` – forget the silent voice. +//! * IXAudio2SourceVoice slot 21 `SubmitSourceBuffer` – Opus voices decode the submitted +//! packets to PCM16 and keep each decoded buffer alive until `OnBufferEnd` (or voice +//! destruction); silent voices submit silence of matching length, preserving callbacks, +//! * IXAudio2SourceVoice slot 22 `FlushSourceBuffers` – flushes the Opus decoder state, +//! * IXAudio2SourceVoice slot 25 `GetState` – maps internal buffer tokens back to the +//! title's original `pBufferContext`, +//! * IXAudio2SourceVoice slot 18 `DestroyVoice` – tears down the voice, then releases any +//! remaining decoded buffers and callback wrapper. //! //! Next step: a real XMA2 decoder (FFmpeg libavcodec, LGPL-2.1+). //! Exports we do not implement (X3DAudio*, CreateFX, CreateAudioReverb…) fall back to the @@ -25,19 +30,26 @@ use std::collections::HashMap; use std::ffi::c_void; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; use serde::{Deserialize, Serialize}; +use crate::hle::opus; use crate::util::{E_FAIL, E_POINTER, HRESULT, S_OK}; pub const WAVE_FORMAT_PCM: u16 = 1; +pub const WAVE_FORMAT_IEEE_FLOAT: u16 = 3; pub const WAVE_FORMAT_XMA: u16 = 0x165; pub const WAVE_FORMAT_XMA2: u16 = 0x166; -pub const WAVE_FORMAT_IEEE_FLOAT: u16 = 3; +pub const WAVE_FORMAT_OPUS: u16 = 0x704F; pub const WAVE_FORMAT_EXTENSIBLE: u16 = 0xFFFE; +/// `MFAudioFormat_Opus` / `KSDATAFORMAT_SUBTYPE_OPUS`: `{0000704F-0000-0010-8000-00AA00389B71}`. +pub const SUBFORMAT_OPUS: [u8; 16] = [ + 0x4F, 0x70, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71, +]; + /// XAudio2Create flags Windows accepts: STOP_ENGINE_WHEN_IDLE, 1024_QUANTUM, NO_VIRTUAL_AUDIO_CLIENT. pub const ENGINE_FLAGS: u32 = 0x2000 | 0x8000 | 0x1_0000; /// CreateSourceVoice flags Windows accepts: NOPITCH, NOSRC, USEFILTER. @@ -47,12 +59,15 @@ pub const MASTERING_FLAGS: u32 = 0x1_0000; const XAUDIO2_DEFAULT_PROCESSOR: u32 = 1; const NTDDI_WIN10_RS5: u32 = 0x0A00_0006; const AUDIO_CATEGORY_GAME_EFFECTS: u32 = 6; +const XAUDIO2_END_OF_STREAM: u32 = 0x40; const CO_E_NOTINITIALIZED: HRESULT = 0x8004_01F0u32 as i32; const ENGINE_CREATE_SOURCE_VOICE: usize = 5; const ENGINE_CREATE_MASTERING_VOICE: usize = 7; const VOICE_DESTROY: usize = 18; const VOICE_SUBMIT_SOURCE_BUFFER: usize = 21; +const VOICE_FLUSH_SOURCE_BUFFERS: usize = 22; +const VOICE_GET_STATE: usize = 25; /// Size of the shared silence buffer (zero pages are only backed once read). const SILENCE_BYTES: usize = 32 << 20; @@ -69,6 +84,15 @@ pub struct WaveFormatEx { pub cb_size: u16, } +#[repr(C, packed)] +#[derive(Clone, Copy, Default, Debug)] +pub struct WaveFormatExtensible { + pub wfx: WaveFormatEx, + pub samples: u16, + pub channel_mask: u32, + pub sub_format: [u8; 16], +} + /// XMA2WAVEFORMATEX (xma2defs.h, packed). #[repr(C, packed)] #[derive(Clone, Copy, Default, Debug)] @@ -102,17 +126,39 @@ pub struct XAudio2Buffer { pub context: *mut c_void, } +/// XAUDIO2_VOICE_STATE (packed). +#[repr(C, packed)] +#[derive(Clone, Copy, Debug)] +pub struct XAudio2VoiceState { + pub current_buffer_context: *mut c_void, + pub buffers_queued: u32, + pub samples_played: u64, +} + const _: () = assert!(std::mem::size_of::() == 18); +const _: () = assert!(std::mem::size_of::() == 40); const _: () = assert!(std::mem::size_of::() == 52); const _: () = assert!(std::mem::size_of::() == 44); +const _: () = assert!(std::mem::size_of::() == 20); type CreateWithVersionFn = unsafe extern "system" fn(*mut *mut c_void, u32, u32, u32) -> HRESULT; type CreateFn = unsafe extern "system" fn(*mut *mut c_void, u32, u32) -> HRESULT; -type CreateSourceVoiceFn = - unsafe extern "system" fn(*mut c_void, *mut *mut c_void, *const WaveFormatEx, u32, f32, *mut c_void, *const c_void, *const c_void) -> HRESULT; -type CreateMasteringVoiceFn = unsafe extern "system" fn(*mut c_void, *mut *mut c_void, u32, u32, u32, *const u16, *const c_void, u32) -> HRESULT; +type CreateSourceVoiceFn = unsafe extern "system" fn( + *mut c_void, + *mut *mut c_void, + *const WaveFormatEx, + u32, + f32, + *mut c_void, + *const c_void, + *const c_void, +) -> HRESULT; +type CreateMasteringVoiceFn = + unsafe extern "system" fn(*mut c_void, *mut *mut c_void, u32, u32, u32, *const u16, *const c_void, u32) -> HRESULT; type DestroyVoiceFn = unsafe extern "system" fn(*mut c_void); type SubmitSourceBufferFn = unsafe extern "system" fn(*mut c_void, *const XAudio2Buffer, *const c_void) -> HRESULT; +type FlushSourceBuffersFn = unsafe extern "system" fn(*mut c_void) -> HRESULT; +type GetStateFn = unsafe extern "system" fn(*mut c_void, *mut XAudio2VoiceState, u32); pub fn exports() -> Vec<(&'static str, usize)> { crate::hle_exports![XAudio2Create, XAudio2CreateWithVersionInfo] @@ -132,7 +178,13 @@ pub struct AudioStats { pub source_voices: u64, /// XMA/XMA2 voices replaced by PCM16 voices (no decoder yet → silence) pub xma_voices: u64, - /// other formats the Windows engine rejected, replaced the same way (tags, e.g. "0x704f") + /// Opus voices decoded to PCM16 via MSOpusDecoder + pub opus_voices: u64, + /// Opus buffers decoded to PCM16 + pub opus_buffers_decoded: u64, + /// Opus buffers that failed decoding (fell back to silence) + pub opus_decode_errors: u64, + /// other formats the Windows engine rejected, replaced the same way (tags, e.g. "0x161") pub unsupported_formats: Vec, pub silent_voices: u64, pub buffers_silenced: u64, @@ -148,6 +200,9 @@ static MASTERING_RETRIES: AtomicU64 = AtomicU64::new(0); static MASTERING_ERRORS: AtomicU64 = AtomicU64::new(0); static SOURCE_VOICES: AtomicU64 = AtomicU64::new(0); static XMA_VOICES: AtomicU64 = AtomicU64::new(0); +static OPUS_VOICES_CREATED: AtomicU64 = AtomicU64::new(0); +static OPUS_BUFFERS_DECODED: AtomicU64 = AtomicU64::new(0); +static OPUS_DECODE_ERRORS: AtomicU64 = AtomicU64::new(0); static SILENT_VOICES: AtomicU64 = AtomicU64::new(0); static SILENCED: AtomicU64 = AtomicU64::new(0); static UNSUPPORTED: Mutex> = Mutex::new(Vec::new()); @@ -163,6 +218,9 @@ pub fn stats() -> AudioStats { mastering_errors: MASTERING_ERRORS.load(Ordering::Relaxed), source_voices: SOURCE_VOICES.load(Ordering::Relaxed), xma_voices: XMA_VOICES.load(Ordering::Relaxed), + opus_voices: OPUS_VOICES_CREATED.load(Ordering::Relaxed), + opus_buffers_decoded: OPUS_BUFFERS_DECODED.load(Ordering::Relaxed), + opus_decode_errors: OPUS_DECODE_ERRORS.load(Ordering::Relaxed), unsupported_formats: UNSUPPORTED.lock().map(|d| d.clone()).unwrap_or_default(), silent_voices: SILENT_VOICES.load(Ordering::Relaxed), buffers_silenced: SILENCED.load(Ordering::Relaxed), @@ -196,9 +254,21 @@ pub struct XmaInfo { pub rate: u32, /// WAVEFORMATEX.nAvgBytesPerSec of the original format pub avg_bytes: u32, + pub block_align: u16, pub samples_encoded: u32, pub bytes_per_block: u32, pub block_count: u16, + pub is_opus: bool, +} + +/// Parsed fields of an Opus `WAVEFORMATEX` / `WAVEFORMATEXTENSIBLE`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OpusFormat<'a> { + pub channels: u16, + pub rate: u32, + pub block_align: u16, + pub avg_bytes: u32, + pub extra: &'a [u8], } pub fn is_xma(tag: u16) -> bool { @@ -210,6 +280,38 @@ pub fn is_plain_pcm(tag: u16) -> bool { matches!(tag, WAVE_FORMAT_PCM | WAVE_FORMAT_IEEE_FLOAT | WAVE_FORMAT_EXTENSIBLE) } +/// Recognize an Opus format (`WAVE_FORMAT_OPUS` 0x704F or `WAVE_FORMAT_EXTENSIBLE` with +/// `MFAudioFormat_Opus`) and return its header fields + codec-private extra bytes. +/// +/// # Safety +/// `fmt` must point to a `WAVEFORMATEX` followed by `cbSize` readable bytes. +pub unsafe fn opus_format<'a>(fmt: *const WaveFormatEx) -> Option> { + let w = fmt.read_unaligned(); + let channels = w.channels.clamp(1, 8); + let rate = if w.rate == 0 { 48_000 } else { w.rate }; + if w.tag == WAVE_FORMAT_OPUS { + let extra = if w.cb_size > 0 { + std::slice::from_raw_parts((fmt as *const u8).add(std::mem::size_of::()), w.cb_size as usize) + } else { + &[] + }; + return Some(OpusFormat { channels, rate, block_align: w.block_align, avg_bytes: w.avg_bytes, extra }); + } + if w.tag == WAVE_FORMAT_EXTENSIBLE && w.cb_size >= 22 { + let ext = (fmt as *const WaveFormatExtensible).read_unaligned(); + if ext.sub_format == SUBFORMAT_OPUS { + let extra_len = (w.cb_size - 22) as usize; + let extra = if extra_len > 0 { + std::slice::from_raw_parts((fmt as *const u8).add(std::mem::size_of::()), extra_len) + } else { + &[] + }; + return Some(OpusFormat { channels, rate, block_align: w.block_align, avg_bytes: w.avg_bytes, extra }); + } + } + None +} + /// Voice info from a format (XMA2WAVEFORMATEX fields only when cbSize says they are there). /// /// # Safety @@ -220,6 +322,8 @@ pub unsafe fn xma_info(fmt: *const WaveFormatEx) -> XmaInfo { channels: w.channels.clamp(1, 8), rate: if w.rate == 0 { 48_000 } else { w.rate }, avg_bytes: w.avg_bytes, + block_align: w.block_align, + is_opus: opus_format(fmt).is_some(), ..Default::default() }; if w.tag == WAVE_FORMAT_XMA2 && w.cb_size as usize >= std::mem::size_of::() - 18 { @@ -231,10 +335,52 @@ pub unsafe fn xma_info(fmt: *const WaveFormatEx) -> XmaInfo { i } +/// PCM16 format with the channel count and sample rate of a voice. +pub fn pcm16_for_rate(channels: u16, rate: u32) -> WaveFormatEx { + let ch = channels.clamp(1, 8); + let block = ch * 2; + WaveFormatEx { + tag: WAVE_FORMAT_PCM, + channels: ch, + rate, + avg_bytes: rate * block as u32, + block_align: block, + bits: 16, + cb_size: 0, + } +} + /// PCM16 format with the channel count and sample rate of an XMA voice. pub fn pcm16_for(i: &XmaInfo) -> WaveFormatEx { - let block = i.channels * 2; - WaveFormatEx { tag: WAVE_FORMAT_PCM, channels: i.channels, rate: i.rate, avg_bytes: i.rate * block as u32, block_align: block, bits: 16, cb_size: 0 } + pcm16_for_rate(i.channels, i.rate) +} + +/// Clamp play/loop sample regions to `total_frames` so XAudio2 never rejects a decoded +/// buffer with `XAUDIO2_E_INVALID_CALL`. +pub fn clamp_regions(b: &mut XAudio2Buffer, total_frames: u32) { + if total_frames == 0 { + b.play_begin = 0; + b.play_length = 0; + b.loop_begin = 0; + b.loop_length = 0; + b.loop_count = 0; + return; + } + if b.play_begin >= total_frames { + b.play_begin = 0; + b.play_length = 0; + } else if b.play_length > 0 && b.play_begin.saturating_add(b.play_length) > total_frames { + b.play_length = total_frames - b.play_begin; + } + if b.loop_count > 0 { + if b.loop_begin >= total_frames { + b.loop_begin = 0; + b.loop_length = 0; + b.loop_count = 0; + } else if b.loop_length > 0 && b.loop_begin.saturating_add(b.loop_length) > total_frames { + b.loop_length = total_frames - b.loop_begin; + } + } } /// Frames (samples per channel) a compressed buffer of `audio_bytes` decodes to: XMA2 in @@ -252,13 +398,23 @@ pub fn estimate_frames(i: &XmaInfo, audio_bytes: u32) -> u64 { f.max(128) } -/// The PCM16 silence buffer that stands in for an XMA buffer: same play/loop region and -/// flags/context; length from PlayBegin+PlayLength (or the estimate), clamped to -/// `max_bytes` (then the whole – shorter – buffer is played). +/// The PCM16 silence buffer that stands in for an XMA (or fallback) buffer: same play/loop +/// region and flags/context; length from PlayBegin+PlayLength (or RFC 6716 Opus packet +/// durations / XMA2 estimate), clamped to `max_bytes`. pub fn silent_buffer(i: &XmaInfo, b: &XAudio2Buffer, silence: *const u8, max_bytes: usize) -> XAudio2Buffer { + let opus_est = if i.is_opus && !b.audio_data.is_null() && b.audio_bytes > 0 { + let data = unsafe { std::slice::from_raw_parts(b.audio_data, b.audio_bytes as usize) }; + opus::estimate_buffer_frames(data, i.block_align, i.rate, i.channels > 2) + } else { + None + }; let mut nb = *b; let (pb, pl, lb, ll) = (b.play_begin as u64, b.play_length as u64, b.loop_begin as u64, b.loop_length as u64); - let mut frames = if pl > 0 { pb + pl } else { estimate_frames(i, b.audio_bytes).max(pb + 1) }; + let mut frames = if pl > 0 { + pb + pl + } else { + opus_est.unwrap_or_else(|| estimate_frames(i, b.audio_bytes)).max(pb + 1) + }; if b.loop_count > 0 { frames = frames.max(lb + ll); } @@ -276,14 +432,163 @@ pub fn silent_buffer(i: &XmaInfo, b: &XAudio2Buffer, silence: *const u8, max_byt nb } +// --------------------------------------------------------------------------------------- +// Opus voice state & IXAudio2VoiceCallback wrapper (decoded PCM buffer lifetime manager) +// --------------------------------------------------------------------------------------- + +/// Owned decoded PCM16 buffer kept alive at a stable heap address until `OnBufferEnd` +/// or `DestroyVoice`. +struct DecodedBuffer { + orig_context: usize, + _pcm: Box<[u8]>, +} + +struct OpusVoiceState { + decoder: Mutex, + block_align: u16, + channels: u16, + rate: u32, + avg_bytes: u32, + title_cb: usize, + /// Maps stable token (`&*DecodedBuffer as usize`) → owned `DecodedBuffer`. + live_buffers: Mutex>>, +} + +struct OpusVoiceHandle { + state: Arc, + cb_ptr: usize, +} + +// IXAudio2VoiceCallback vtable (7 methods, no IUnknown). +#[repr(C)] +struct VoiceCallbackVtbl { + pass_start: unsafe extern "system" fn(*mut c_void, u32), + pass_end: unsafe extern "system" fn(*mut c_void), + stream_end: unsafe extern "system" fn(*mut c_void), + buffer_start: unsafe extern "system" fn(*mut c_void, *mut c_void), + buffer_end: unsafe extern "system" fn(*mut c_void, *mut c_void), + loop_end: unsafe extern "system" fn(*mut c_void, *mut c_void), + voice_error: unsafe extern "system" fn(*mut c_void, *mut c_void, HRESULT), +} + +#[repr(C)] +struct OpusCallback { + vtbl: &'static VoiceCallbackVtbl, + state: Arc, +} + +unsafe fn title_cb_vtbl(cb: usize) -> Option<(*mut c_void, *const VoiceCallbackVtbl)> { + if cb == 0 { + return None; + } + let obj = cb as *mut c_void; + let vtbl = *(obj as *const *const VoiceCallbackVtbl); + if vtbl.is_null() { + return None; + } + Some((obj, vtbl)) +} + +unsafe extern "system" fn opus_cb_pass_start(this: *mut c_void, bytes: u32) { + let cb = &*(this as *const OpusCallback); + if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { + ((*vt).pass_start)(obj, bytes); + } +} + +unsafe extern "system" fn opus_cb_pass_end(this: *mut c_void) { + let cb = &*(this as *const OpusCallback); + if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { + ((*vt).pass_end)(obj); + } +} + +unsafe extern "system" fn opus_cb_stream_end(this: *mut c_void) { + let cb = &*(this as *const OpusCallback); + if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { + ((*vt).stream_end)(obj); + } +} + +unsafe extern "system" fn opus_cb_buffer_start(this: *mut c_void, ctx: *mut c_void) { + let cb = &*(this as *const OpusCallback); + let orig = cb + .state + .live_buffers + .lock() + .unwrap() + .get(&(ctx as usize)) + .map(|b| b.orig_context as *mut c_void) + .unwrap_or(ctx); + if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { + ((*vt).buffer_start)(obj, orig); + } +} + +unsafe extern "system" fn opus_cb_buffer_end(this: *mut c_void, ctx: *mut c_void) { + let cb = &*(this as *const OpusCallback); + // Remove and drop the decoded PCM buffer before invoking the title's callback so + // the lock is released and no double-free or deadlock can occur. + let removed = cb.state.live_buffers.lock().unwrap().remove(&(ctx as usize)); + let orig = removed.as_ref().map(|b| b.orig_context as *mut c_void).unwrap_or(ctx); + drop(removed); + if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { + ((*vt).buffer_end)(obj, orig); + } +} + +unsafe extern "system" fn opus_cb_loop_end(this: *mut c_void, ctx: *mut c_void) { + let cb = &*(this as *const OpusCallback); + let orig = cb + .state + .live_buffers + .lock() + .unwrap() + .get(&(ctx as usize)) + .map(|b| b.orig_context as *mut c_void) + .unwrap_or(ctx); + if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { + ((*vt).loop_end)(obj, orig); + } +} + +unsafe extern "system" fn opus_cb_voice_error(this: *mut c_void, ctx: *mut c_void, hr: HRESULT) { + let cb = &*(this as *const OpusCallback); + let orig = cb + .state + .live_buffers + .lock() + .unwrap() + .get(&(ctx as usize)) + .map(|b| b.orig_context as *mut c_void) + .unwrap_or(ctx); + if let Some((obj, vt)) = title_cb_vtbl(cb.state.title_cb) { + ((*vt).voice_error)(obj, orig, hr); + } +} + +static OPUS_CALLBACK_VTBL: VoiceCallbackVtbl = VoiceCallbackVtbl { + pass_start: opus_cb_pass_start, + pass_end: opus_cb_pass_end, + stream_end: opus_cb_stream_end, + buffer_start: opus_cb_buffer_start, + buffer_end: opus_cb_buffer_end, + loop_end: opus_cb_loop_end, + voice_error: opus_cb_voice_error, +}; + // --------------------------------------------------------------------------------------- // the system engine and in-place vtable patches // --------------------------------------------------------------------------------------- /// Originals of patched slots: (vtable address, slot) → function. static ORIGINALS: Mutex> = Mutex::new(Vec::new()); -/// Live XMA voices (voice pointer → info). +/// Live silent voices (voice pointer → info). static XMA: Mutex>> = Mutex::new(None); +/// Live decoded Opus voices (voice pointer → handle). +static OPUS_VOICES: Mutex>> = Mutex::new(None); +/// Count of live Opus voices (fast path for non-Opus voices). +static OPUS_LIVE_COUNT: AtomicUsize = AtomicUsize::new(0); unsafe fn vtable(obj: *mut c_void) -> *mut usize { *(obj as *const *mut usize) @@ -390,13 +695,62 @@ unsafe extern "system" fn create_source_voice( return orig(this, pp, fmt, flags, max_ratio, cb, sends, chain); } let tag = (*fmt).tag; - let mut silent = is_xma(tag).then(|| xma_info(fmt)); + + // 1. Opus voice (WAVE_FORMAT_OPUS 0x704F or WAVE_FORMAT_EXTENSIBLE with MFAudioFormat_Opus) + if let Some(of) = opus_format(fmt) { + match opus::Decoder::new(of.channels, of.rate, of.extra) { + Ok(dec) => { + let pcm_ch = dec.channels(); + let pcm_rate = dec.output_rate(); + let pcm = pcm16_for_rate(pcm_ch, pcm_rate); + let state = Arc::new(OpusVoiceState { + decoder: Mutex::new(dec), + block_align: of.block_align, + channels: pcm_ch, + rate: pcm_rate, + avg_bytes: of.avg_bytes, + title_cb: cb as usize, + live_buffers: Mutex::new(HashMap::new()), + }); + let wrapped_cb = Box::into_raw(Box::new(OpusCallback { + vtbl: &OPUS_CALLBACK_VTBL, + state: Arc::clone(&state), + })); + let hr = orig(this, pp, &pcm, flags, max_ratio, wrapped_cb as *mut c_void, sends, chain); + if hr < 0 || (*pp).is_null() { + drop(Box::from_raw(wrapped_cb)); + SOURCE_ERRORS.fetch_add(1, Ordering::Relaxed); + crate::xlog_warn!("XAudio2: CreateSourceVoice(Opus→PCM16) failed ({:#x})", hr as u32); + return hr; + } + let voice = *pp; + patch_source_voice(voice); + OPUS_VOICES + .lock() + .unwrap() + .get_or_insert_with(HashMap::new) + .insert(voice as usize, OpusVoiceHandle { state, cb_ptr: wrapped_cb as usize }); + OPUS_LIVE_COUNT.fetch_add(1, Ordering::Release); + SOURCE_VOICES.fetch_add(1, Ordering::Relaxed); + if OPUS_VOICES_CREATED.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("XAudio2: Opus voice ({pcm_ch} ch., {pcm_rate} Hz) → real PCM16 decoding via MSOpusDecoder"); + } + return hr; + } + Err(e) => { + crate::xlog_warn!("XAudio2: Opus decoder unavailable ({e}) – falling back to silence"); + } + } + } + + // 2. XMA/XMA2 or other formats (including Opus fallback if MSOpusDecoder is missing) + let mut silent = (is_xma(tag) || opus_format(fmt).is_some()).then(|| xma_info(fmt)); let mut hr = match &silent { Some(i) => orig(this, pp, &pcm16_for(i), flags, max_ratio, cb, sends, chain), None => orig(this, pp, fmt, flags, max_ratio, cb, sends, chain), }; if hr < 0 && silent.is_none() && !is_plain_pcm(tag) { - // a compressed format the Windows engine does not know (console-only, e.g. Opus) + // a compressed format the Windows engine does not know let i = xma_info(fmt); let h2 = orig(this, pp, &pcm16_for(&i), flags, max_ratio, cb, sends, chain); if h2 >= 0 { @@ -421,8 +775,7 @@ unsafe extern "system" fn create_source_voice( return hr; } let voice = *pp; - patch(voice, VOICE_SUBMIT_SOURCE_BUFFER, submit_source_buffer as usize); - patch(voice, VOICE_DESTROY, destroy_voice as usize); + patch_source_voice(voice); SOURCE_VOICES.fetch_add(1, Ordering::Relaxed); if let Some(i) = silent { XMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(voice as usize, i); @@ -439,6 +792,13 @@ unsafe extern "system" fn create_source_voice( hr } +unsafe fn patch_source_voice(voice: *mut c_void) { + patch(voice, VOICE_SUBMIT_SOURCE_BUFFER, submit_source_buffer as usize); + patch(voice, VOICE_FLUSH_SOURCE_BUFFERS, flush_source_buffers as usize); + patch(voice, VOICE_GET_STATE, get_state as usize); + patch(voice, VOICE_DESTROY, destroy_voice as usize); +} + unsafe extern "system" fn create_mastering_voice( this: *mut c_void, pp: *mut *mut c_void, @@ -489,9 +849,92 @@ fn silence() -> *const u8 { *P.get_or_init(|| unsafe { VirtualAlloc(std::ptr::null(), SILENCE_BYTES, MEM_COMMIT | MEM_RESERVE, PAGE_READONLY) as usize }) as *const u8 } +unsafe fn submit_opus_buffer( + this: *mut c_void, + orig: SubmitSourceBufferFn, + state: &OpusVoiceState, + orig_buf: XAudio2Buffer, +) -> HRESULT { + let data = if !orig_buf.audio_data.is_null() && orig_buf.audio_bytes > 0 { + std::slice::from_raw_parts(orig_buf.audio_data, orig_buf.audio_bytes as usize) + } else { + &[] + }; + + let decoded_pcm = { + let mut dec = state.decoder.lock().unwrap(); + let res = dec.decode_buffer(data, state.block_align); + if (orig_buf.flags & XAUDIO2_END_OF_STREAM) != 0 { + dec.flush(); + } + res + }; + + let mut nb = orig_buf; + let pcm_bytes: Box<[u8]> = match decoded_pcm { + Ok(samples) if !samples.is_empty() => { + let total_frames = (samples.len() / state.channels.max(1) as usize) as u32; + clamp_regions(&mut nb, total_frames); + let mut bytes = Vec::with_capacity(samples.len() * 2); + for s in samples { + bytes.extend_from_slice(&s.to_le_bytes()); + } + OPUS_BUFFERS_DECODED.fetch_add(1, Ordering::Relaxed); + bytes.into_boxed_slice() + } + res => { + if let Err(e) = res { + if OPUS_DECODE_ERRORS.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_warn!("XAudio2: Opus decode error ({e}) – substituting silence"); + } + } else { + OPUS_DECODE_ERRORS.fetch_add(1, Ordering::Relaxed); + } + let info = XmaInfo { + channels: state.channels, + rate: state.rate, + avg_bytes: state.avg_bytes, + block_align: state.block_align, + is_opus: true, + ..Default::default() + }; + let sb = silent_buffer(&info, &orig_buf, std::ptr::null(), SILENCE_BYTES); + nb = sb; + SILENCED.fetch_add(1, Ordering::Relaxed); + vec![0u8; sb.audio_bytes as usize].into_boxed_slice() + } + }; + + let pcm_ptr = pcm_bytes.as_ptr(); + let pcm_len = pcm_bytes.len() as u32; + let boxed = Box::new(DecodedBuffer { orig_context: orig_buf.context as usize, _pcm: pcm_bytes }); + let token = &*boxed as *const DecodedBuffer as usize; + state.live_buffers.lock().unwrap().insert(token, boxed); + + nb.audio_data = pcm_ptr; + nb.audio_bytes = pcm_len; + nb.context = token as *mut c_void; + + let hr = orig(this, &nb, std::ptr::null()); + if hr < 0 { + state.live_buffers.lock().unwrap().remove(&token); + } + hr +} + unsafe extern "system" fn submit_source_buffer(this: *mut c_void, buf: *const XAudio2Buffer, wma: *const c_void) -> HRESULT { let Some(orig) = original(this, VOICE_SUBMIT_SOURCE_BUFFER) else { return E_FAIL }; let orig: SubmitSourceBufferFn = std::mem::transmute(orig); + if !buf.is_null() && OPUS_LIVE_COUNT.load(Ordering::Acquire) != 0 { + let state = OPUS_VOICES + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(this as usize)).map(|h| Arc::clone(&h.state))); + if let Some(state) = state { + return submit_opus_buffer(this, orig, &state, buf.read_unaligned()); + } + } let info = XMA.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()); match info { Some(i) if !buf.is_null() => { @@ -507,13 +950,65 @@ unsafe extern "system" fn submit_source_buffer(this: *mut c_void, buf: *const XA } } +unsafe extern "system" fn flush_source_buffers(this: *mut c_void) -> HRESULT { + let Some(orig) = original(this, VOICE_FLUSH_SOURCE_BUFFERS) else { return E_FAIL }; + let orig: FlushSourceBuffersFn = std::mem::transmute(orig); + let hr = orig(this); + if hr >= 0 && OPUS_LIVE_COUNT.load(Ordering::Acquire) != 0 { + let state = OPUS_VOICES + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(this as usize)).map(|h| Arc::clone(&h.state))); + if let Some(state) = state { + state.decoder.lock().unwrap().flush(); + } + } + hr +} + +unsafe extern "system" fn get_state(this: *mut c_void, state_out: *mut XAudio2VoiceState, flags: u32) { + let Some(orig) = original(this, VOICE_GET_STATE) else { return }; + let orig: GetStateFn = std::mem::transmute(orig); + orig(this, state_out, flags); + if !state_out.is_null() && OPUS_LIVE_COUNT.load(Ordering::Acquire) != 0 { + let voice_state = OPUS_VOICES + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(this as usize)).map(|h| Arc::clone(&h.state))); + if let Some(voice_state) = voice_state { + let cur = (*state_out).current_buffer_context as usize; + if cur != 0 { + if let Some(buf) = voice_state.live_buffers.lock().unwrap().get(&cur) { + (*state_out).current_buffer_context = buf.orig_context as *mut c_void; + } + } + } + } +} + unsafe extern "system" fn destroy_voice(this: *mut c_void) { let Some(orig) = original(this, VOICE_DESTROY) else { return }; let orig: DestroyVoiceFn = std::mem::transmute(orig); if let Some(m) = XMA.lock().unwrap().as_mut() { m.remove(&(this as usize)); } - orig(this) + let opus_handle = if OPUS_LIVE_COUNT.load(Ordering::Acquire) != 0 { + OPUS_VOICES.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))) + } else { + None + }; + if opus_handle.is_some() { + OPUS_LIVE_COUNT.fetch_sub(1, Ordering::Release); + } + // Destroy the Windows voice first so its audio thread stops using the callback and any + // queued PCM buffers before we free them. + orig(this); + if let Some(h) = opus_handle { + h.state.live_buffers.lock().unwrap().clear(); + drop(Box::from_raw(h.cb_ptr as *mut OpusCallback)); + } } #[cfg(test)] @@ -548,7 +1043,19 @@ mod tests { fn xma2_format_to_pcm16() { let f = xma2(2, 44_100, 441_000, 0x8000, 4); let i = unsafe { xma_info(&f as *const Xma2WaveFormatEx as *const WaveFormatEx) }; - assert_eq!(i, XmaInfo { channels: 2, rate: 44_100, avg_bytes: 0, samples_encoded: 441_000, bytes_per_block: 0x8000, block_count: 4 }); + assert_eq!( + i, + XmaInfo { + channels: 2, + rate: 44_100, + avg_bytes: 0, + block_align: 1, + samples_encoded: 441_000, + bytes_per_block: 0x8000, + block_count: 4, + is_opus: false, + } + ); let p = pcm16_for(&i); assert_eq!((p.tag, p.channels, p.rate, p.block_align, p.bits, p.avg_bytes), (1, 2, 44_100, 4, 16, 176_400)); // plain XMA (or a short cbSize): no XMA2 fields are read @@ -558,9 +1065,39 @@ mod tests { assert!(is_xma(0x166) && is_xma(0x165) && !is_xma(1)); } + #[test] + fn opus_format_detection_and_region_clamping() { + // Plain WAVE_FORMAT_OPUS (0x704F) with OpusHead extra data + let head = opus::build_opus_head(2, 48_000, 312, 0); + let mut raw = Vec::with_capacity(18 + head.len()); + let wfx = WaveFormatEx { tag: WAVE_FORMAT_OPUS, channels: 2, rate: 48_000, avg_bytes: 16_000, block_align: 2048, bits: 0, cb_size: head.len() as u16 }; + raw.extend_from_slice(unsafe { std::slice::from_raw_parts(&wfx as *const _ as *const u8, 18) }); + raw.extend_from_slice(&head); + let of = unsafe { opus_format(raw.as_ptr() as *const WaveFormatEx) }.unwrap(); + assert_eq!((of.channels, of.rate, of.block_align, of.extra), (2, 48_000, 2048, head.as_slice())); + + // WAVE_FORMAT_EXTENSIBLE with MFAudioFormat_Opus subformat + let ext = WaveFormatExtensible { + wfx: WaveFormatEx { tag: WAVE_FORMAT_EXTENSIBLE, channels: 6, rate: 48_000, avg_bytes: 0, block_align: 0, bits: 0, cb_size: 22 }, + samples: 0, + channel_mask: 0x3F, + sub_format: SUBFORMAT_OPUS, + }; + let of2 = unsafe { opus_format(&ext as *const _ as *const WaveFormatEx) }.unwrap(); + assert_eq!((of2.channels, of2.rate, of2.extra.len()), (6, 48_000, 0)); + + // Region clamping + let mut b = buffer(100, 200, 5000, 100, 4000, 1); + clamp_regions(&mut b, 960); + assert_eq!(({ b.play_begin }, { b.play_length }, { b.loop_begin }, { b.loop_length }), (200, 760, 100, 860)); + let mut b2 = buffer(100, 1000, 100, 1000, 100, 1); + clamp_regions(&mut b2, 960); + assert_eq!(({ b2.play_begin }, { b2.play_length }, { b2.loop_count }), (0, 0, 0)); + } + #[test] fn silence_has_the_length_of_the_xma_buffer() { - let i = XmaInfo { channels: 2, rate: 48_000, avg_bytes: 0, samples_encoded: 480_000, bytes_per_block: 0x10000, block_count: 2 }; + let i = XmaInfo { channels: 2, rate: 48_000, avg_bytes: 0, samples_encoded: 480_000, bytes_per_block: 0x10000, block_count: 2, ..Default::default() }; let z = 0x5000 as *const u8; // explicit play region: PlayBegin + PlayLength frames let b = silent_buffer(&i, &buffer(4096, 128, 4800, 0, 0, 0), z, 1 << 20); @@ -607,4 +1144,155 @@ mod tests { assert!(stats().dropped_flags.iter().any(|f| f == "XAudio2Create:0x1")); } } + + #[test] + fn opus_source_voice_decodes_and_manages_lifetime() { + if !opus::is_available() { + eprintln!("skipping: MSOpusDecoder.dll not available"); + return; + } + use std::sync::atomic::AtomicUsize; + + static ENDED: AtomicUsize = AtomicUsize::new(0); + static STARTED: AtomicUsize = AtomicUsize::new(0); + static STREAM_END: AtomicUsize = AtomicUsize::new(0); + + unsafe extern "system" fn on_pass_start(_: *mut c_void, _: u32) {} + unsafe extern "system" fn on_nothing(_: *mut c_void) {} + unsafe extern "system" fn on_stream_end(_: *mut c_void) { + STREAM_END.fetch_add(1, Ordering::SeqCst); + } + unsafe extern "system" fn on_buf_start(_: *mut c_void, ctx: *mut c_void) { + STARTED.fetch_add(ctx as usize, Ordering::SeqCst); + } + unsafe extern "system" fn on_buf_end(_: *mut c_void, ctx: *mut c_void) { + ENDED.fetch_add(ctx as usize, Ordering::SeqCst); + } + unsafe extern "system" fn on_loop(_: *mut c_void, _: *mut c_void) {} + unsafe extern "system" fn on_err(_: *mut c_void, _: *mut c_void, _: HRESULT) {} + + static TEST_VTBL: VoiceCallbackVtbl = VoiceCallbackVtbl { + pass_start: on_pass_start, + pass_end: on_nothing, + stream_end: on_stream_end, + buffer_start: on_buf_start, + buffer_end: on_buf_end, + loop_end: on_loop, + voice_error: on_err, + }; + #[repr(C)] + struct TestCb { + vtbl: &'static VoiceCallbackVtbl, + } + static TEST_CB: TestCb = TestCb { vtbl: &TEST_VTBL }; + + unsafe { + let mut eng: *mut c_void = std::ptr::null_mut(); + assert_eq!(XAudio2Create(&mut eng, 0, 1), S_OK); + let vt_eng = vtable(eng); + let create_master: CreateMasteringVoiceFn = std::mem::transmute(vt_eng.add(ENGINE_CREATE_MASTERING_VOICE).read()); + let mut master: *mut c_void = std::ptr::null_mut(); + if create_master(eng, &mut master, 0, 0, 0, std::ptr::null(), std::ptr::null(), AUDIO_CATEGORY_GAME_EFFECTS) < 0 { + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(vt_eng.add(2).read()); + release(eng); + eprintln!("skipping: no audio device"); + return; + } + + let create_src: CreateSourceVoiceFn = std::mem::transmute(vt_eng.add(ENGINE_CREATE_SOURCE_VOICE).read()); + let opus_wfx = WaveFormatEx { tag: WAVE_FORMAT_OPUS, channels: 1, rate: 48_000, avg_bytes: 4000, block_align: 2048, bits: 0, cb_size: 0 }; + let mut voice: *mut c_void = std::ptr::null_mut(); + let hr = create_src(eng, &mut voice, &opus_wfx, 0, 2.0, &TEST_CB as *const _ as *mut c_void, std::ptr::null(), std::ptr::null()); + assert_eq!(hr, S_OK, "CreateSourceVoice(Opus) → {:#x}", hr as u32); + assert!(!voice.is_null()); + + // Pack 2 packets into a 2048 B AWC block + 1 raw packet + let mut block = vec![0u8; 2048]; + let mut pos = 0; + for &pkt in &opus::tests::MONO_HYBRID_20MS[..2] { + block[pos..pos + 2].copy_from_slice(&(pkt.len() as u16).to_le_bytes()); + block[pos + 2..pos + 2 + pkt.len()].copy_from_slice(pkt); + pos += 2 + pkt.len(); + } + + let vt_v = vtable(voice); + let submit: SubmitSourceBufferFn = std::mem::transmute(vt_v.add(VOICE_SUBMIT_SOURCE_BUFFER).read()); + let get_st: GetStateFn = std::mem::transmute(vt_v.add(VOICE_GET_STATE).read()); + let start: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT = std::mem::transmute(vt_v.add(19).read()); + let flush: FlushSourceBuffersFn = std::mem::transmute(vt_v.add(VOICE_FLUSH_SOURCE_BUFFERS).read()); + let destroy: DestroyVoiceFn = std::mem::transmute(vt_v.add(VOICE_DESTROY).read()); + + const CTX1: usize = 0x1001; + const CTX2: usize = 0x2002; + let b1 = XAudio2Buffer { + flags: 0, + audio_bytes: block.len() as u32, + audio_data: block.as_ptr(), + play_begin: 0, + play_length: 0, + loop_begin: 0, + loop_length: 0, + loop_count: 0, + context: CTX1 as *mut c_void, + }; + let raw = opus::tests::MONO_HYBRID_20MS[2]; + let b2 = XAudio2Buffer { + flags: XAUDIO2_END_OF_STREAM, + audio_bytes: raw.len() as u32, + audio_data: raw.as_ptr(), + play_begin: 0, + play_length: 0, + loop_begin: 0, + loop_length: 0, + loop_count: 0, + context: CTX2 as *mut c_void, + }; + + let before_decoded = stats().opus_buffers_decoded; + assert_eq!(submit(voice, &b1, std::ptr::null()), S_OK); + assert_eq!(submit(voice, &b2, std::ptr::null()), S_OK); + assert_eq!(stats().opus_buffers_decoded, before_decoded + 2); + + // GetState must return the title's original CTX1, not our internal token! + let mut st = XAudio2VoiceState { current_buffer_context: std::ptr::null_mut(), buffers_queued: 0, samples_played: 0 }; + get_st(voice, &mut st, 0); + assert_eq!({ st.buffers_queued }, 2); + assert_eq!({ st.current_buffer_context } as usize, CTX1); + + // Mute voice so the test runs silently on developer machines, then play to completion + let set_vol: unsafe extern "system" fn(*mut c_void, f32, u32) -> HRESULT = std::mem::transmute(vt_v.add(12).read()); + let _ = set_vol(voice, 0.0, 0); + assert_eq!(start(voice, 0, 0), S_OK); + + let t0 = std::time::Instant::now(); + while (ENDED.load(Ordering::SeqCst) != CTX1 + CTX2 || STREAM_END.load(Ordering::SeqCst) == 0) + && t0.elapsed() < std::time::Duration::from_secs(3) + { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + assert_eq!(STARTED.load(Ordering::SeqCst), CTX1 + CTX2); + assert_eq!(ENDED.load(Ordering::SeqCst), CTX1 + CTX2); + assert!(STREAM_END.load(Ordering::SeqCst) >= 1); + + // All decoded buffers must have been freed on OnBufferEnd! + let remaining = OPUS_VOICES + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(voice as usize)).map(|h| h.state.live_buffers.lock().unwrap().len())) + .unwrap_or(999); + assert_eq!(remaining, 0, "decoded PCM buffers leaked after OnBufferEnd"); + + // Test FlushSourceBuffers while stopped + DestroyVoice cleanup + let stop: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT = std::mem::transmute(vt_v.add(20).read()); + let _ = stop(voice, 0, 0); + assert_eq!(submit(voice, &b2, std::ptr::null()), S_OK); + assert_eq!(flush(voice), S_OK); + + destroy(voice); + destroy(master); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(vt_eng.add(2).read()); + release(eng); + } + } } diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 83866f8..cf48614 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -160,8 +160,11 @@ fn test_title_runs_and_game_folder_is_untouched() { assert!(a["dropped_flags"].as_array().unwrap().iter().any(|f| f == "XAudio2Create:0x41"), "audio: {a}"); if a["mastering_voices"] == 1 { assert_eq!(a["xma_voices"], 1, "audio: {a}"); + assert_eq!(a["opus_voices"], 1, "audio: {a}"); + assert_eq!(a["opus_buffers_decoded"], 1, "audio: {a}"); + assert_eq!(a["opus_decode_errors"], 0, "audio: {a}"); assert_eq!(a["silent_voices"], 1, "audio: {a}"); - assert_eq!(a["source_voices"], 2, "audio: {a}"); + assert_eq!(a["source_voices"], 3, "audio: {a}"); assert_eq!(a["buffers_silenced"], 1, "audio: {a}"); assert_eq!(a["source_voice_errors"], 0, "audio: {a}"); } else { diff --git a/tests/testtitle/src/audio.rs b/tests/testtitle/src/audio.rs index 7f2dac6..b7eecd5 100644 --- a/tests/testtitle/src/audio.rs +++ b/tests/testtitle/src/audio.rs @@ -64,9 +64,27 @@ struct VoiceDetails { rate: u32, } +#[repr(C, packed)] +#[derive(Default)] +struct VoiceState { + current_buffer_context: *mut c_void, + buffers_queued: u32, + samples_played: u64, +} + const END_OF_STREAM: u32 = 0x40; const XMA_CONTEXT: usize = 0x100; const PCM_CONTEXT: usize = 0x2_0000; +const OPUS_CONTEXT: usize = 0x4000; + +// Five real 20 ms (960-sample) Hybrid FB mono Opus packets (100 ms total at 48 kHz). +const OPUS_PACKETS: &[&[u8]] = &[ + &[0x78, 0x81, 0x7b, 0xc6, 0x11, 0x76, 0xf4, 0x75, 0x00, 0x00, 0x07, 0x8e, 0xca, 0x69, 0x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xa1, 0xd7, 0xce, 0xb0, 0x1b, 0x08, 0x44, 0x28, 0x21, 0xcb, 0x80, 0x40, 0xaf, 0xc4, 0x08, 0xdc, 0x96, 0xfd, 0xb6, 0x95, 0x96, 0xda, 0xf3, 0xae, 0x6c, 0x2b, 0x04, 0xc4, 0x23, 0xb8, 0x12, 0x45, 0x51, 0xf9, 0x5f, 0x9b, 0xb0, 0xc6, 0x86, 0xed, 0x08, 0x0c], +]; static BUFFER_END: AtomicUsize = AtomicUsize::new(0); static STREAM_END: AtomicUsize = AtomicUsize::new(0); @@ -74,6 +92,8 @@ static VOICE_ERRORS: AtomicUsize = AtomicUsize::new(0); static STARTED: OnceLock = OnceLock::new(); /// ms from Start to the end of the XMA2 buffer static XMA_END_MS: AtomicU64 = AtomicU64::new(u64::MAX); +/// ms from Start to the end of the Opus buffer +static OPUS_END_MS: AtomicU64 = AtomicU64::new(u64::MAX); // IXAudio2VoiceCallback (no IUnknown) #[repr(C)] @@ -98,6 +118,10 @@ unsafe extern "system" fn on_buffer_end(_: *mut c_void, ctx: *mut c_void) { if let Some(t0) = STARTED.get() { XMA_END_MS.store(t0.elapsed().as_millis() as u64, Ordering::SeqCst); } + } else if ctx as usize == OPUS_CONTEXT { + if let Some(t0) = STARTED.get() { + OPUS_END_MS.store(t0.elapsed().as_millis() as u64, Ordering::SeqCst); + } } BUFFER_END.fetch_add(ctx as usize, Ordering::SeqCst); } @@ -131,7 +155,9 @@ type CreateSourceVoice = unsafe extern "system" fn(*mut c_void, *mut *mut c_void, *const c_void, u32, f32, *const c_void, *const c_void, *const c_void) -> i32; type CreateMasteringVoice = unsafe extern "system" fn(*mut c_void, *mut *mut c_void, u32, u32, u32, *const u16, *const c_void, u32) -> i32; type GetVoiceDetails = unsafe extern "system" fn(*mut c_void, *mut VoiceDetails); +type SetVolume = unsafe extern "system" fn(*mut c_void, f32, u32) -> i32; type Submit = unsafe extern "system" fn(*mut c_void, *const Buffer, *const c_void) -> i32; +type GetState = unsafe extern "system" fn(*mut c_void, *mut VoiceState, u32); type Start = unsafe extern "system" fn(*mut c_void, u32, u32) -> i32; type Destroy = unsafe extern "system" fn(*mut c_void); type Release = unsafe extern "system" fn(*mut c_void) -> u32; @@ -217,21 +243,68 @@ pub fn xaudio2_console_voices() -> Result<(), String> { if method::(pv, 21)(pv, &pb, std::ptr::null()) != 0 { return Err("SubmitSourceBuffer(PCM)".into()); } + + // Opus mono 48 kHz (0x704F) in a 2048 B AWC-framed block – decoded to PCM16 by XCL + let opus_fmt = WaveFormatEx { tag: 0x704F, channels: 1, rate: 48_000, avg_bytes: 4000, block_align: 2048, bits: 0, cb_size: 0 }; + let mut ov: *mut c_void = std::ptr::null_mut(); + let hr = create_source(eng, &mut ov, &opus_fmt as *const WaveFormatEx as *const c_void, 0, 2.0, cb, std::ptr::null(), std::ptr::null()); + if hr != 0 || ov.is_null() { + return Err(format!("CreateSourceVoice(Opus) → {:#x}", hr as u32)); + } + let mut odet = VoiceDetails::default(); + method::(ov, 0)(ov, &mut odet); + if (odet.channels, odet.rate) != (1, 48_000) { + return Err(format!("Opus voice: {} ch., {} Hz", { odet.channels }, { odet.rate })); + } + let _ = method::(ov, 12)(ov, 0.0, 0); // stay silent during automated tests + let mut opus_block = vec![0u8; 2048]; + let mut pos = 0usize; + for &pkt in OPUS_PACKETS { + opus_block[pos..pos + 2].copy_from_slice(&(pkt.len() as u16).to_le_bytes()); + opus_block[pos + 2..pos + 2 + pkt.len()].copy_from_slice(pkt); + pos += 2 + pkt.len(); + } + let ob = Buffer { + flags: END_OF_STREAM, + audio_bytes: opus_block.len() as u32, + audio_data: opus_block.as_ptr(), + play_begin: 0, + play_length: 0, // decoded length: 5 * 960 = 4800 samples = 0.1 s + loop_begin: 0, + loop_length: 0, + loop_count: 0, + context: OPUS_CONTEXT as *mut c_void, + }; + let hr = method::(ov, 21)(ov, &ob, std::ptr::null()); + if hr != 0 { + return Err(format!("SubmitSourceBuffer(Opus) → {:#x}", hr as u32)); + } + let mut ost = VoiceState::default(); + method::(ov, 25)(ov, &mut ost, 0); + if { ost.current_buffer_context } as usize != OPUS_CONTEXT || { ost.buffers_queued } != 1 { + return Err(format!( + "Opus GetState: ctx={:#x}, queued={}", + { ost.current_buffer_context } as usize, + { ost.buffers_queued } + )); + } + STARTED.get_or_init(Instant::now); - for v in [xv, pv] { + for v in [xv, pv, ov] { let hr = method::(v, 19)(v, 0, 0); if hr != 0 { return Err(format!("Start → {:#x}", hr as u32)); } } + let expected_ctx = XMA_CONTEXT + PCM_CONTEXT + OPUS_CONTEXT; let t0 = Instant::now(); - while (BUFFER_END.load(Ordering::SeqCst) != XMA_CONTEXT + PCM_CONTEXT || STREAM_END.load(Ordering::SeqCst) < 2) + while (BUFFER_END.load(Ordering::SeqCst) != expected_ctx || STREAM_END.load(Ordering::SeqCst) < 3) && t0.elapsed() < Duration::from_secs(5) { std::thread::sleep(Duration::from_millis(10)); } let ends = BUFFER_END.load(Ordering::SeqCst); - if ends != XMA_CONTEXT + PCM_CONTEXT || STREAM_END.load(Ordering::SeqCst) < 2 { + if ends != expected_ctx || STREAM_END.load(Ordering::SeqCst) < 3 { return Err(format!("callbacks: OnBufferEnd context sum {ends:#x}, OnStreamEnd {}", STREAM_END.load(Ordering::SeqCst))); } if VOICE_ERRORS.load(Ordering::SeqCst) != 0 { @@ -243,12 +316,16 @@ pub fn xaudio2_console_voices() -> Result<(), String> { if !(70..=2000).contains(&ms) { return Err(format!("XMA2 buffer ended after {ms} ms (expected ≈100)")); } - println!(" (XMA2 buffer ended after {ms} ms)"); - for v in [xv, pv, master] { + let oms = OPUS_END_MS.load(Ordering::SeqCst); + if !(70..=2000).contains(&oms) { + return Err(format!("Opus buffer ended after {oms} ms (expected ≈100)")); + } + println!(" (XMA2 buffer ended after {ms} ms; Opus buffer ended after {oms} ms)"); + for v in [xv, pv, ov, master] { method::(v, 18)(v); } release(eng); - drop((packet, samples)); + drop((packet, samples, opus_block)); Ok(()) } }