1use core::fmt;
2use core::iter::FusedIterator;
3
4use crate::error::Failure;
5use crate::{Error, Fourcc, Result};
6
7pub const MAX_DEPTH: usize = 32;
9
10#[derive(Clone, Copy, PartialEq, Eq, Debug)]
12pub enum Form {
13 Riff,
15 Rifx,
17 Rf64,
19 Bw64,
21}
22
23impl Form {
24 pub const fn is_big_endian(self) -> bool {
26 matches!(self, Self::Rifx)
27 }
28
29 pub const fn has_ds64(self) -> bool {
31 matches!(self, Self::Rf64 | Self::Bw64)
32 }
33
34 #[cfg(feature = "std")]
35 pub(crate) const fn id(self) -> Fourcc {
36 match self {
37 Self::Riff => Fourcc::RIFF,
38 Self::Rifx => Fourcc::RIFX,
39 Self::Rf64 => Fourcc::RF64,
40 Self::Bw64 => Fourcc::BW64,
41 }
42 }
43}
44
45#[derive(Clone, Copy, PartialEq, Eq, Debug)]
47pub struct Header {
48 pub form: Form,
50 pub size: u32,
52 pub form_type: Fourcc,
54}
55
56#[derive(Clone, Copy, Debug)]
58pub struct Ds64<'a> {
59 pub riff_size: u64,
61 pub data_size: u64,
63 pub sample_count: u64,
65 pub(crate) table: &'a [u8],
66}
67
68impl<'a> Ds64<'a> {
69 pub fn table(&self) -> impl Iterator<Item = (Fourcc, u64)> + 'a {
71 self.table.chunks_exact(12).map(|entry| {
72 let id = Fourcc([entry[0], entry[1], entry[2], entry[3]]);
73 let size = read_u64_le(&entry[4..12]);
74 (id, size)
75 })
76 }
77
78 pub fn size_of(&self, id: Fourcc) -> Option<u64> {
80 if id == Fourcc(*b"data") {
81 Some(self.data_size)
82 } else {
83 self.table()
84 .find_map(|(entry_id, size)| (entry_id == id).then_some(size))
85 }
86 }
87}
88
89#[derive(Clone, Copy, PartialEq, Eq, Debug)]
91pub struct ChunkHeader {
92 pub id: Fourcc,
94 pub size: u64,
96 pub offset: u64,
98 pub depth: u8,
100}
101
102impl ChunkHeader {
103 pub fn is_list(&self) -> bool {
105 self.id.0 == Fourcc::LIST.0
106 }
107
108 pub const fn padded_size(&self) -> u64 {
113 self.size.saturating_add(self.size & 1)
114 }
115
116 pub const fn extent(&self) -> u64 {
120 8_u64.saturating_add(self.padded_size())
121 }
122}
123
124pub struct Riff<'a> {
126 data: &'a [u8],
127 header: Header,
128 ds64: Option<Ds64<'a>>,
129}
130
131impl fmt::Debug for Riff<'_> {
132 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
133 formatter
134 .debug_struct("Riff")
135 .field("header", &self.header)
136 .field("ds64", &self.ds64)
137 .field("len", &self.data.len())
138 .finish()
139 }
140}
141
142impl<'a> Riff<'a> {
143 pub fn parse(data: &'a [u8]) -> Result<Self> {
158 let header = parse_header(data)?;
159 let ds64 = if header.form.has_ds64() {
160 Some(parse_borrowed_ds64(data)?)
161 } else {
162 None
163 };
164 Ok(Self { data, header, ds64 })
165 }
166
167 pub const fn header(&self) -> Header {
169 self.header
170 }
171
172 pub const fn ds64(&self) -> Option<Ds64<'a>> {
174 self.ds64
175 }
176
177 pub fn chunks(&self) -> Chunks<'a> {
179 Chunks::new(
180 &self.data[12..],
181 12,
182 0,
183 self.header.form.is_big_endian(),
184 self.ds64,
185 false,
186 )
187 }
188
189 pub fn body(&self) -> &'a [u8] {
191 &self.data[12..]
192 }
193}
194
195#[derive(Clone, Copy, Debug)]
197pub struct Chunk<'a> {
198 pub header: ChunkHeader,
200 pub payload: &'a [u8],
202 big_endian: bool,
203 ds64: Option<Ds64<'a>>,
204}
205
206impl<'a> Chunk<'a> {
207 pub fn list_type(&self) -> Result<Fourcc> {
209 if !self.header.is_list() {
210 return Err(Error::NotAList { id: self.header.id });
211 }
212 if self.payload.len() < 4 {
213 return Err(Error::ListTooShort {
214 id: self.header.id,
215 size: self.header.size,
216 });
217 }
218 Ok(Fourcc([
219 self.payload[0],
220 self.payload[1],
221 self.payload[2],
222 self.payload[3],
223 ]))
224 }
225
226 pub fn children(&self) -> Result<Chunks<'a>> {
228 self.list_type()?;
229 if usize::from(self.header.depth) >= MAX_DEPTH {
230 return Err(Error::TooDeep { max: MAX_DEPTH });
231 }
232 Ok(Chunks::new(
233 &self.payload[4..],
234 self.header.offset.saturating_add(12),
235 self.header.depth + 1,
236 self.big_endian,
237 self.ds64,
238 true,
239 ))
240 }
241}
242
243#[derive(Clone, Copy, Debug)]
244enum IterState {
245 Running,
246 Pending(Failure),
247 Done,
248}
249
250pub struct Chunks<'a> {
252 data: &'a [u8],
253 pos: usize,
254 base: u64,
255 depth: u8,
256 big_endian: bool,
257 ds64: Option<Ds64<'a>>,
258 parent_bound: bool,
259 state: IterState,
260}
261
262impl fmt::Debug for Chunks<'_> {
263 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
264 formatter
265 .debug_struct("Chunks")
266 .field("pos", &self.pos)
267 .field("base", &self.base)
268 .field("depth", &self.depth)
269 .field("state", &self.state)
270 .finish_non_exhaustive()
271 }
272}
273
274impl<'a> Chunks<'a> {
275 fn new(
276 data: &'a [u8],
277 base: u64,
278 depth: u8,
279 big_endian: bool,
280 ds64: Option<Ds64<'a>>,
281 parent_bound: bool,
282 ) -> Self {
283 Self {
284 data,
285 pos: 0,
286 base,
287 depth,
288 big_endian,
289 ds64,
290 parent_bound,
291 state: IterState::Running,
292 }
293 }
294
295 pub fn find(&mut self, id: Fourcc) -> Result<Option<Chunk<'a>>> {
297 for item in self.by_ref() {
298 let chunk = item?;
299 if chunk.header.id == id {
300 return Ok(Some(chunk));
301 }
302 }
303 Ok(None)
304 }
305
306 fn fail(&mut self, failure: Failure) -> Option<Result<Chunk<'a>>> {
307 self.state = IterState::Done;
308 Some(Err(failure.into_error()))
309 }
310}
311
312impl<'a> Iterator for Chunks<'a> {
313 type Item = Result<Chunk<'a>>;
314
315 fn next(&mut self) -> Option<Self::Item> {
316 match self.state {
317 IterState::Done => return None,
318 IterState::Pending(failure) => return self.fail(failure),
319 IterState::Running => {}
320 }
321
322 let remaining = self.data.len().saturating_sub(self.pos);
323 if remaining == 0 {
324 self.state = IterState::Done;
325 return None;
326 }
327
328 let offset = self
329 .base
330 .saturating_add(u64::try_from(self.pos).unwrap_or(u64::MAX));
331 if remaining < 8 {
332 return self.fail(Failure::TruncatedHeader(
333 offset,
334 u64::try_from(remaining).unwrap_or(u64::MAX),
335 ));
336 }
337
338 let header_bytes = &self.data[self.pos..self.pos + 8];
339 let id = Fourcc([
340 header_bytes[0],
341 header_bytes[1],
342 header_bytes[2],
343 header_bytes[3],
344 ]);
345 let size32 = read_u32(&header_bytes[4..8], self.big_endian);
346 let size = match resolve_size(size32, id, self.ds64) {
347 Ok(size) => size,
348 Err(error) => {
349 self.state = IterState::Done;
350 return Some(Err(error));
351 }
352 };
353
354 if id == Fourcc::LIST && size < 4 {
355 return self.fail(Failure::ListTooShort(id, size));
356 }
357
358 let payload_end = match 8_u64.checked_add(size) {
359 Some(end) => end,
360 None => {
361 return self.fail(Failure::Truncated(
362 id,
363 size,
364 u64::try_from(remaining - 8).unwrap_or(u64::MAX),
365 ));
366 }
367 };
368 let extent = match payload_end.checked_add(size & 1) {
369 Some(end) => end,
370 None => {
371 return self.fail(Failure::Truncated(
372 id,
373 size,
374 u64::try_from(remaining - 8).unwrap_or(u64::MAX),
375 ));
376 }
377 };
378 let remaining_u64 = u64::try_from(remaining).unwrap_or(u64::MAX);
379
380 if self.parent_bound && extent > remaining_u64 {
381 return self.fail(Failure::ChildExceedsParent(id, size, remaining_u64));
382 }
383 if payload_end > remaining_u64 {
384 return self.fail(Failure::Truncated(
385 id,
386 size,
387 remaining_u64.saturating_sub(8),
388 ));
389 }
390
391 let payload_size = match usize::try_from(size) {
392 Ok(size) => size,
393 Err(_) => {
394 return self.fail(Failure::Truncated(
395 id,
396 size,
397 remaining_u64.saturating_sub(8),
398 ));
399 }
400 };
401 let payload_start = self.pos + 8;
402 let payload_stop = match payload_start.checked_add(payload_size) {
403 Some(stop) => stop,
404 None => {
405 return self.fail(Failure::Truncated(
406 id,
407 size,
408 remaining_u64.saturating_sub(8),
409 ));
410 }
411 };
412 let payload = &self.data[payload_start..payload_stop];
413 let missing_pad = extent > remaining_u64;
414 self.pos = if missing_pad {
415 payload_stop
416 } else {
417 match usize::try_from(extent) {
418 Ok(extent) => self.pos + extent,
419 Err(_) => self.data.len(),
420 }
421 };
422
423 if missing_pad {
424 self.state = IterState::Pending(Failure::MissingPad(
425 id,
426 offset.saturating_add(8).saturating_add(size),
427 ));
428 }
429
430 Some(Ok(Chunk {
431 header: ChunkHeader {
432 id,
433 size,
434 offset,
435 depth: self.depth,
436 },
437 payload,
438 big_endian: self.big_endian,
439 ds64: self.ds64,
440 }))
441 }
442}
443
444impl FusedIterator for Chunks<'_> {}
445
446pub(crate) fn parse_header(data: &[u8]) -> Result<Header> {
447 if data.len() < 12 {
448 return Err(Error::TruncatedHeader {
449 offset: 0,
450 available: u64::try_from(data.len()).unwrap_or(u64::MAX),
451 });
452 }
453 let found = [data[0], data[1], data[2], data[3]];
454 let form = form_from_id(found)?;
455 Ok(Header {
456 form,
457 size: read_u32(&data[4..8], form.is_big_endian()),
458 form_type: Fourcc([data[8], data[9], data[10], data[11]]),
459 })
460}
461
462pub(crate) fn form_from_id(found: [u8; 4]) -> Result<Form> {
463 match Fourcc(found) {
464 Fourcc::RIFF => Ok(Form::Riff),
465 Fourcc::RIFX => Ok(Form::Rifx),
466 Fourcc::RF64 => Ok(Form::Rf64),
467 Fourcc::BW64 => Ok(Form::Bw64),
468 _ => Err(Error::NotRiff { found }),
469 }
470}
471
472pub(crate) fn read_u32(bytes: &[u8], big_endian: bool) -> u32 {
473 let value = [bytes[0], bytes[1], bytes[2], bytes[3]];
474 if big_endian {
475 u32::from_be_bytes(value)
476 } else {
477 u32::from_le_bytes(value)
478 }
479}
480
481pub(crate) fn read_u64_le(bytes: &[u8]) -> u64 {
482 u64::from_le_bytes([
483 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
484 ])
485}
486
487pub(crate) fn parse_ds64_payload(payload: &[u8], declared: u64) -> Result<Ds64<'_>> {
488 if declared < 28 || payload.len() < 28 {
489 return Err(Error::BadDs64 { size: declared });
490 }
491 let table_len = read_u32(&payload[24..28], false);
492 let table_bytes = match u64::from(table_len).checked_mul(12) {
493 Some(bytes) => bytes,
494 None => return Err(Error::BadDs64 { size: declared }),
495 };
496 let required = match 28_u64.checked_add(table_bytes) {
497 Some(required) => required,
498 None => return Err(Error::BadDs64 { size: declared }),
499 };
500 if required > declared {
501 return Err(Error::BadDs64 { size: declared });
502 }
503 let required_usize = match usize::try_from(required) {
504 Ok(required) if required <= payload.len() => required,
505 _ => return Err(Error::BadDs64 { size: declared }),
506 };
507 Ok(Ds64 {
508 riff_size: read_u64_le(&payload[0..8]),
509 data_size: read_u64_le(&payload[8..16]),
510 sample_count: read_u64_le(&payload[16..24]),
511 table: &payload[28..required_usize],
512 })
513}
514
515fn parse_borrowed_ds64(data: &[u8]) -> Result<Ds64<'_>> {
516 if data.len() < 20 {
517 return Err(Error::TruncatedHeader {
518 offset: 12,
519 available: u64::try_from(data.len().saturating_sub(12)).unwrap_or(u64::MAX),
520 });
521 }
522 let id = Fourcc([data[12], data[13], data[14], data[15]]);
523 if id != Fourcc::DS64 {
524 return Err(Error::MissingDs64 { found: id });
525 }
526 let size = u64::from(read_u32(&data[16..20], false));
527 if size < 28 {
528 return Err(Error::BadDs64 { size });
529 }
530 let available = data.len().saturating_sub(20);
531 let size_usize = match usize::try_from(size) {
532 Ok(size) if size <= available => size,
533 _ => {
534 return Err(Error::Truncated {
535 id,
536 declared: size,
537 available: u64::try_from(available).unwrap_or(u64::MAX),
538 });
539 }
540 };
541 parse_ds64_payload(&data[20..20 + size_usize], size)
542}
543
544pub(crate) fn resolve_size(size32: u32, id: Fourcc, ds64: Option<Ds64<'_>>) -> Result<u64> {
545 if size32 != u32::MAX {
546 return Ok(u64::from(size32));
547 }
548 match ds64 {
549 Some(ds64) => ds64.size_of(id).ok_or(Error::UnresolvedSize { id }),
550 None => Ok(u64::from(size32)),
551 }
552}