1use crate::{Error, adpcm, send_sync, vorbis, wav};
8use std::sync::Arc;
9use unityrs_core::limits::{Meter, MeteredVec};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct Header {
14 pub version: u32,
15 pub subsound_count: u32,
16 pub header_size: usize,
17 pub sample_headers_size: u32,
18 pub name_table_size: u32,
19 pub data_size: u32,
20 pub mode: u32,
21}
22const _: () = send_sync::<Header>();
23#[derive(Debug)]
26pub struct Subsound<'a> {
27 pub name: Option<&'a [u8]>,
28 pub frequency: u32,
29 pub channels: u16,
30 pub data_offset: u32,
31 pub samples: u32,
32 pub extra_chunks: &'a [u8],
33 pub(crate) data: &'a [u8],
34 pub(crate) wav_bytes: usize,
35}
36const _: () = send_sync::<Subsound<'static>>();
37
38struct Reader<'a> {
39 bytes: &'a [u8],
40 pos: usize,
41 field: &'static str,
42}
43impl<'a> Reader<'a> {
44 fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
45 let out = span(self.bytes, self.pos, n, self.field)?;
46 self.pos = self.pos.checked_add(n).ok_or(Error::OutputSize)?;
47 Ok(out)
48 }
49 fn u32(&mut self) -> Result<u32, Error> {
50 word(self.take(4)?)
51 }
52 fn u64(&mut self) -> Result<u64, Error> {
53 Ok(u64::from_le_bytes(
54 self.take(8)?
55 .try_into()
56 .map_err(|_| Error::Invalid("sample header"))?,
57 ))
58 }
59}
60fn word(bytes: &[u8]) -> Result<u32, Error> {
61 Ok(u32::from_le_bytes(
62 bytes
63 .try_into()
64 .map_err(|_| Error::Invalid("32-bit field"))?,
65 ))
66}
67fn span<'a>(bytes: &'a [u8], pos: usize, n: usize, field: &'static str) -> Result<&'a [u8], Error> {
68 let end = pos.checked_add(n).ok_or(Error::OutputSize)?;
69 bytes.get(pos..end).ok_or(Error::Truncated {
70 field,
71 offset: pos,
72 length: n,
73 })
74}
75fn rate(index: u64) -> Option<u32> {
76 match index {
77 0 => Some(4000),
78 1 => Some(8000),
79 2 => Some(11000),
80 3 => Some(12000),
81 4 => Some(16000),
82 5 => Some(22050),
83 6 => Some(24000),
84 7 => Some(32000),
85 8 => Some(44100),
86 9 => Some(48000),
87 10 => Some(96000),
88 _ => None,
89 }
90}
91#[allow(
92 clippy::cast_precision_loss,
93 clippy::cast_possible_truncation,
94 clippy::cast_sign_loss,
95 reason = "FMOD returns float32; Python int truncates toward zero"
96)]
97fn wav_frequency(frequency: u32) -> Result<u32, Error> {
98 let frequency = (frequency as f32) as u64;
103 u32::try_from(frequency)
104 .ok()
105 .filter(|&n| n > 0 && i32::try_from(n).is_ok())
106 .ok_or(Error::Invalid("frequency"))
107}
108fn read_sample<'a>(reader: &mut Reader<'a>) -> Result<Subsound<'a>, Error> {
109 let raw = reader.u64()?;
110 let mut frequency = rate((raw >> 1) & 15);
111 let mut channels = match (raw >> 5) & 3 {
112 0 => 1,
113 1 => 2,
114 2 => 6,
115 _ => 8,
116 };
117 let chunks_start = reader.pos;
118 let mut more = raw & 1 != 0;
119 while more {
120 let chunk = reader.u32()?;
121 more = chunk & 1 != 0;
122 let size = ((chunk >> 1) & 0x00ff_ffff) as usize;
123 let payload = reader.take(size)?;
124 match chunk >> 25 {
125 1 => {
126 if payload.len() != 1 {
127 return Err(Error::Invalid("channels chunk size"));
128 }
129 channels = u16::from(*payload.first().ok_or(Error::Invalid("channels chunk"))?);
130 }
131 2 => {
132 frequency = Some(word(payload)?);
133 }
134 _ => {}
135 }
136 }
137 let frequency = wav_frequency(frequency.ok_or(Error::Invalid("frequency"))?)?;
138 if channels == 0 {
139 return Err(Error::Invalid("channels"));
140 }
141 if channels > 32 {
142 return Err(Error::TooManyChannels { channels });
143 }
144 Ok(Subsound {
145 name: None,
146 frequency,
147 channels,
148 data_offset: u32::try_from((raw >> 7) & 0x07ff_ffff).map_err(|_| Error::OutputSize)? * 32,
149 samples: (raw >> 34) as u32,
150 extra_chunks: reader
151 .bytes
152 .get(chunks_start..reader.pos)
153 .ok_or(Error::Invalid("extra chunks"))?,
154 data: &[],
155 wav_bytes: 0,
156 })
157}
158
159type Parsed<'a> = (Header, MeteredVec<Subsound<'a>>, u64);
160#[allow(
161 clippy::too_many_lines,
162 reason = "bounded metadata preflight followed by subsound planning"
163)]
164pub(crate) fn parse<'a>(
165 bytes: &'a [u8],
166 convert: bool,
167 meter: &Arc<Meter>,
168) -> Result<Parsed<'a>, Error> {
169 let mut r = Reader {
170 bytes,
171 pos: 4,
172 field: "bank header",
173 };
174 let version = r.u32()?;
175 let header_size = match version {
176 0 => 64,
177 1 => 60,
178 n => return Err(Error::Version(n)),
179 };
180 let header = Header {
181 version,
182 header_size,
183 subsound_count: r.u32()?,
184 sample_headers_size: r.u32()?,
185 name_table_size: r.u32()?,
186 data_size: r.u32()?,
187 mode: r.u32()?,
188 };
189 span(bytes, 0, header_size, "bank header")?;
190 let mut sections = Reader {
191 bytes,
192 pos: header_size,
193 field: "sample header section",
194 };
195 let sample_bytes = sections.take(header.sample_headers_size as usize)?;
196 sections.field = "name table section";
197 let names = sections.take(header.name_table_size as usize)?;
198 sections.field = "data section";
199 let data = sections.take(header.data_size as usize)?;
200 let data_start = sections.pos - data.len();
201 let count = header.subsound_count as usize;
203 if count == 0 {
204 return Err(Error::Invalid("zero subsound count"));
205 }
206 if count > sample_bytes.len() / 8 {
207 return Err(Error::Invalid("subsound count"));
208 }
209 meter.count_decode(header_size as u64 + sample_bytes.len() as u64 * 2 + names.len() as u64)?;
212 let mut subs = MeteredVec::new(meter);
214 let mut samples = Reader {
215 bytes: sample_bytes,
216 pos: 0,
217 field: "sample header",
218 };
219 if !names.is_empty() && count > names.len() / 4 {
220 return Err(Error::Invalid("name offsets"));
221 }
222 let mut name_offsets = Reader {
223 bytes: names,
224 pos: 0,
225 field: "name offsets",
226 };
227 for _ in 0..count {
230 read_sample(&mut samples)?;
231 }
232 samples.pos = 0;
233 for _ in 0..count {
234 let mut sub = read_sample(&mut samples)?;
235 let name = if names.is_empty() {
236 None
237 } else {
238 let offset = name_offsets.u32()? as usize;
239 if offset < count * 4 {
240 return Err(Error::Invalid("name offset overlaps offsets"));
241 }
242 let tail = names.get(offset..).ok_or(Error::Invalid("name offset"))?;
243 let mut length = 0;
244 for &b in tail {
245 meter.count_decode(1)?;
246 if b == 0 {
247 break;
248 }
249 length += 1;
250 }
251 if length == tail.len() {
252 return Err(Error::Invalid("unterminated name"));
253 }
254 Some(span(tail, 0, length, "name")?)
255 };
256 sub.name = name;
257 subs.push(sub)?;
258 }
259 if subs.as_slice().first().is_some_and(|s| s.samples == 0) {
260 return Err(Error::EmptyFirstSubsound);
261 }
262 let width = wav::width(header.mode)?;
263 let mut total = 0u64;
264 for index in 0..count {
265 let end = subs
266 .as_slice()
267 .get(index + 1)
268 .map_or(header.data_size, |s| s.data_offset);
269 let sub = subs
270 .as_mut_slice()
271 .get_mut(index)
272 .ok_or(Error::Invalid("subsound index"))?;
273 let available = end
274 .checked_sub(sub.data_offset)
275 .ok_or(Error::Invalid("unordered data offsets"))?;
276 let section = span(
277 data,
278 sub.data_offset as usize,
279 available as usize,
280 "subsound data",
281 )?;
282 sub.wav_bytes = wav::size(sub, header.mode, convert)?;
283 if let Some((block, _)) = adpcm::layout(header.mode, sub.channels) {
284 let start = data_start
287 .checked_add(sub.data_offset as usize)
288 .ok_or(Error::OutputSize)?;
289 sub.data = bytes.get(start..).ok_or(Error::Invalid("ADPCM offset"))?;
290 if sub.samples > 0 && sub.data.len() < block {
291 return Err(Error::Invalid("ADPCM first block"));
292 }
293 } else if header.mode == 15 {
294 sub.data = section;
295 vorbis::validate(sub, meter)?;
296 } else {
297 let size = u64::from(sub.samples) * u64::from(sub.channels) * u64::from(width);
298 let size = usize::try_from(size).map_err(|_| Error::OutputSize)?;
299 sub.data = span(section, 0, size, "PCM samples")?;
300 }
301 total = total
302 .checked_add(sub.wav_bytes as u64)
303 .ok_or(Error::OutputSize)?;
304 }
305 Ok((header, subs, total))
306}
307
308#[cfg(test)]
309mod tests {
310 use super::{Error, wav_frequency};
311
312 #[test]
313 fn frequency_uses_float32_ties_to_even_before_integer_validation() {
314 for (input, expected) in [
315 (1, 1),
316 (44100, 44100),
317 (16_777_215, 16_777_215),
318 (16_777_216, 16_777_216),
319 (16_777_217, 16_777_216),
320 (16_777_219, 16_777_220),
321 (2_147_483_583, 2_147_483_520),
322 ] {
323 assert_eq!(wav_frequency(input).unwrap(), expected, "{input}");
324 }
325 for input in [0, 2_147_483_584, i32::MAX as u32, u32::MAX] {
326 assert!(matches!(
327 wav_frequency(input),
328 Err(Error::Invalid("frequency"))
329 ));
330 }
331 }
332}