Skip to main content

unityrs_audio/
lib.rs

1// Ported from UnityPy 1.25.2 (MIT): export/AudioClipConverter.py and enums/Audio.py. See THIRD_PARTY_LICENSES.
2// Ported from fmod_toolkit 0.1.3 (MIT): fmod.py subsound filenames. See THIRD_PARTY_LICENSES.
3//! `AudioClip` dispatch and FSB5 PCM/ADPCM/Vorbis exports, with no FMOD dependency.
4//!
5//! [`plan`] validates the real bank boundaries and bounds WAV output before
6//! decoding. Its metadata, every output name and payload are metered and
7//! allocated fallibly. Vorbis uses an explicit runtime setup provider; lewton
8//! alone allocates infallibly, so audio stays off batch. Plans borrow the input,
9//! preventing decode against a
10//! different bank. Work is charged before traversal or output writes.
11//!
12//! UnityPy's magic dispatch is export/AudioClipConverter.py:35-49. Contrary
13//! to older converters, this release never dispatches on `m_Type`; legacy
14//! non-passthrough data is [`Error::UnsupportedContainer`] (Tier U).
15//! [`extension`] reproduces the shared-enum table and property, independently
16//! of sample dispatch (classes/legacy_patch/AudioClip.py:5-6).
17//!
18//! Integer PCM is copied, float defaults to numpy's saturated int16 rule.
19//! WAVs shorter than four data bytes are Tier C (`fmod_toolkit` raises).
20//! A bank with an empty first subsound is Tier U and refused. Other codecs
21//! are typed unsupported errors, deferred to optional future work.
22#![forbid(unsafe_code)]
23#![cfg_attr(
24    not(test),
25    deny(
26        clippy::unwrap_used,
27        clippy::expect_used,
28        clippy::panic,
29        clippy::unreachable,
30        clippy::indexing_slicing
31    )
32)]
33
34mod adpcm;
35mod fsb5;
36mod vorbis;
37mod vorbis_headers;
38mod wav;
39
40pub use fsb5::{Header, Subsound};
41use std::sync::Arc;
42use unityrs_core::limits::{ChargeError, Meter, MeteredVec};
43pub use vorbis_headers::VorbisHeaders;
44
45/// A malformed bank field, a deliberate format refusal, or resource exhaustion.
46#[derive(Debug, thiserror::Error)]
47pub enum Error {
48    #[error("truncated {field} at {offset}: need {length} bytes")]
49    Truncated {
50        field: &'static str,
51        offset: usize,
52        length: usize,
53    },
54    #[error("invalid FSB5 field: {0}")]
55    Invalid(&'static str),
56    #[error("unsupported FSB5 version {0}")]
57    Version(u32),
58    #[error("unsupported FSB5 codec {codec}")]
59    Unsupported { codec: u32 },
60    #[error("unsupported audio container (including legacy non-passthrough audio)")]
61    UnsupportedContainer,
62    #[error("unsupported FSB5 bank with no samples in its first subsound (Tier U)")]
63    EmptyFirstSubsound,
64    #[error("FSB5 channel count {channels} exceeds FMOD's maximum of 32")]
65    TooManyChannels { channels: u16 },
66    #[error("Vorbis requires setup headers loaded from a caller-supplied path")]
67    VorbisHeadersRequired,
68    #[error("cannot read the caller-supplied Vorbis setup table: {0}")]
69    VorbisHeadersIo(std::io::Error),
70    #[error("Vorbis setup header is absent for CRC {crc:#010x}")]
71    VorbisSetupMissing { crc: u32 },
72    #[error("unsupported Vorbis subsound with fewer than four WAV data bytes (Tier U)")]
73    VorbisShortSubsound,
74    #[error("Vorbis decoder panicked on malformed data")]
75    VorbisPanicked,
76    #[error("audio output exceeds WAV's signed 32-bit fields or address space")]
77    OutputSize,
78    #[error(transparent)]
79    Charge(#[from] ChargeError),
80}
81const _: () = send_sync::<Error>();
82
83/// A validated, borrowed decode recipe. Output bytes exclude filenames and
84/// metadata; their allocations are also charged by `decode` before creation.
85#[derive(Debug)]
86pub struct Plan<'a> {
87    kind: Kind<'a>,
88    output_bytes: u64,
89    convert_float: bool,
90}
91const _: () = send_sync::<Plan<'static>>();
92#[derive(Debug)]
93enum Kind<'a> {
94    Pass {
95        data: &'a [u8],
96        extension: &'static [u8],
97    },
98    Bank {
99        header: Header,
100        subsounds: MeteredVec<Subsound<'a>>,
101    },
102}
103impl<'a> Plan<'a> {
104    #[must_use]
105    pub const fn output_bytes(&self) -> u64 {
106        self.output_bytes
107    }
108    #[must_use]
109    pub const fn header(&self) -> Option<&Header> {
110        match &self.kind {
111            Kind::Bank { header, .. } => Some(header),
112            Kind::Pass { .. } => None,
113        }
114    }
115    #[must_use]
116    pub fn subsounds(&self) -> &[Subsound<'a>] {
117        match &self.kind {
118            Kind::Bank { subsounds, .. } => subsounds.as_slice(),
119            Kind::Pass { .. } => &[],
120        }
121    }
122}
123
124/// One sample export, retaining the charges for its raw UTF-8/surrogateescape
125/// filename bytes and file content. Callers apply their own path policy.
126#[derive(Debug)]
127pub struct Sample {
128    pub name: MeteredVec<u8>,
129    pub bytes: MeteredVec<u8>,
130}
131const _: () = send_sync::<Sample>();
132
133/// The final 20 keys of UnityPy's `AUDIO_TYPE_EXTEMSION` table. Values 1 and
134/// 2 are overwritten by compression formats (enums/Audio.py:33-56).
135#[must_use]
136pub const fn extension(format: Option<i32>) -> &'static str {
137    match format {
138        Some(0..=3 | 8 | 24) => ".fsb",
139        Some(4 | 5 | 23) => ".vag",
140        Some(6 | 20 | 22) => ".wav",
141        Some(7) => ".m4a",
142        Some(9) => ".at9",
143        Some(10) => ".it",
144        Some(12) => ".mod",
145        Some(13) => ".mp3",
146        Some(14) => ".ogg",
147        Some(17) => ".s3m",
148        Some(21) => ".xm",
149        _ => ".audioclip",
150    }
151}
152
153/// Inspect magic, then validate an FSB5 bank and compute its total WAV size.
154/// This reads metadata only, never allocates or decodes a PCM payload.
155pub fn plan<'a>(
156    data: &'a [u8],
157    convert_float: bool,
158    meter: &Arc<Meter>,
159) -> Result<Plan<'a>, Error> {
160    meter.count_decode(8.min(data.len()) as u64)?;
161    let suffix: Option<&'static [u8]> = if data.starts_with(b"OggS") {
162        Some(b".ogg")
163    } else if data.starts_with(b"RIFF") {
164        Some(b".wav")
165    } else if data.get(4..8) == Some(b"ftyp") {
166        Some(b".m4a")
167    } else {
168        None
169    };
170    if let Some(extension) = suffix {
171        return Ok(Plan {
172            kind: Kind::Pass { data, extension },
173            output_bytes: data.len() as u64,
174            convert_float,
175        });
176    }
177    if !data.starts_with(b"FSB5") {
178        return Err(Error::UnsupportedContainer);
179    }
180    let (header, subsounds, output_bytes) = fsb5::parse(data, convert_float, meter)?;
181    Ok(Plan {
182        kind: Kind::Bank { header, subsounds },
183        output_bytes,
184        convert_float,
185    })
186}
187
188/// Materialize the plan's files. Names follow `fmod_toolkit` 0.1.3
189/// `fmod.py` lines 77-98: the clip name, then a numeric suffix; the bank's
190/// own name table does not determine export filenames.
191pub fn decode(
192    plan: &Plan<'_>,
193    name: &[u8],
194    meter: &Arc<Meter>,
195) -> Result<MeteredVec<Sample>, Error> {
196    decode_with_vorbis(plan, name, None, meter)
197}
198
199/// Decode with an explicit runtime Vorbis setup provider. WAV output is
200/// charged before lewton is entered. Lewton's internal allocations are
201/// infallible and unmetered (P3 decision 19); never use this on a batch path.
202pub fn decode_with_vorbis(
203    plan: &Plan<'_>,
204    name: &[u8],
205    headers: Option<&VorbisHeaders>,
206    meter: &Arc<Meter>,
207) -> Result<MeteredVec<Sample>, Error> {
208    if plan.header().is_some_and(|h| h.mode == 15) && headers.is_none() {
209        return Err(Error::VorbisHeadersRequired);
210    }
211    let count = match &plan.kind {
212        Kind::Pass { .. } => 1,
213        Kind::Bank { subsounds, .. } => subsounds.len(),
214    };
215    meter.count_decode(count as u64)?;
216    let mut files = MeteredVec::with_capacity(meter, count)?;
217    match &plan.kind {
218        Kind::Pass { data, extension } => {
219            let filename = filename(name, 0, extension, meter)?;
220            meter.count_decode(data.len() as u64)?;
221            let mut bytes = MeteredVec::with_capacity(meter, data.len())?;
222            bytes.extend_from_slice(data)?;
223            files.push(Sample {
224                name: filename,
225                bytes,
226            })?;
227        }
228        Kind::Bank { header, subsounds } => {
229            for (i, sub) in subsounds.as_slice().iter().enumerate() {
230                let filename = filename(name, i, b".wav", meter)?;
231                let bytes = wav::decode(sub, header.mode, plan.convert_float, headers, meter)?;
232                files.push(Sample {
233                    name: filename,
234                    bytes,
235                })?;
236            }
237        }
238    }
239    Ok(files)
240}
241fn filename(
242    name: &[u8],
243    index: usize,
244    extension: &[u8],
245    meter: &Arc<Meter>,
246) -> Result<MeteredVec<u8>, Error> {
247    let mut digits = [0u8; 20];
248    let mut pos = digits.len();
249    let mut n = index;
250    while n > 0 {
251        pos = pos.checked_sub(1).ok_or(Error::OutputSize)?;
252        *digits.get_mut(pos).ok_or(Error::OutputSize)? =
253            b'0' + u8::try_from(n % 10).map_err(|_| Error::OutputSize)?;
254        n /= 10;
255    }
256    let suffix = digits.get(pos..).ok_or(Error::OutputSize)?;
257    let size = name
258        .len()
259        .checked_add(extension.len())
260        .and_then(|n| n.checked_add(suffix.len() + usize::from(index > 0)))
261        .ok_or(Error::OutputSize)?;
262    meter.count_decode(size as u64)?;
263    let mut out = MeteredVec::with_capacity(meter, size)?;
264    out.extend_from_slice(name)?;
265    if index > 0 {
266        out.push(b'-')?;
267        out.extend_from_slice(suffix)?;
268    }
269    out.extend_from_slice(extension)?;
270    Ok(out)
271}
272pub(crate) const fn send_sync<T: Send + Sync + ?Sized>() {}
273
274#[cfg(test)]
275mod tests {
276    #[test]
277    fn public_types_are_send_sync_and_decoders_never_wait() {
278        let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
279        let missing = unityrs_testkit::public_types::unasserted(&src);
280        assert!(
281            missing.is_empty(),
282            "public types missing Send + Sync: {missing:?}"
283        );
284        let waits = unityrs_testkit::waits::waits(&src);
285        assert!(
286            waits.is_empty(),
287            "decoder starts threads or waits: {waits:?}"
288        );
289    }
290}