Skip to main content

unityrs_audio/
vorbis_headers.rs

1//! Caller-owned setup packets. No FMOD-derived table is embedded or distributed.
2//!
3//! The VST1 interchange format is little endian: magic `VST1`, u32 entry
4//! count, then strictly increasing (u32 CRC, u32 byte length, setup packet)
5//! records. Packets include the `\x05vorbis` prefix. No trailing bytes.
6//! Convert an externally obtained table outside the repository; do not save
7//! that table or anything derived from it as a fixture.
8use crate::{Error, send_sync};
9use std::{io::Read, path::Path, sync::Arc};
10use unityrs_core::limits::{Meter, MeteredVec};
11
12/// Runtime setup headers, retaining their memory charge. The caller supplies
13/// a path; there is no default path, network fetch or embedded fallback.
14#[derive(Debug)]
15pub struct VorbisHeaders {
16    bytes: MeteredVec<u8>,
17}
18const _: () = send_sync::<VorbisHeaders>();
19impl VorbisHeaders {
20    /// Bound the provider even when the path names a growing file or stream.
21    pub const MAX_BYTES: usize = 64 << 20;
22
23    pub fn load(path: &Path, meter: &Arc<Meter>) -> Result<Self, Error> {
24        let mut file = std::fs::File::open(path).map_err(Error::VorbisHeadersIo)?;
25        let mut bytes = MeteredVec::new(meter);
26        let mut block = [0u8; 8192];
27        loop {
28            let n = file.read(&mut block).map_err(Error::VorbisHeadersIo)?;
29            if n == 0 {
30                break;
31            }
32            if bytes.len().saturating_add(n) > Self::MAX_BYTES {
33                return Err(Error::Invalid("Vorbis table size"));
34            }
35            meter.count_decode(n as u64)?;
36            bytes.extend_from_slice(block.get(..n).ok_or(Error::OutputSize)?)?;
37        }
38        Self::validate(bytes, meter)
39    }
40
41    /// Load an in-memory VST1 table with the same validation as [`Self::load`].
42    pub fn from_bytes(input: &[u8], meter: &Arc<Meter>) -> Result<Self, Error> {
43        if input.len() > Self::MAX_BYTES {
44            return Err(Error::Invalid("Vorbis table size"));
45        }
46        meter.count_decode(input.len() as u64)?;
47        // Validate before allocating an input-sized copy.
48        validate(input)?;
49        let mut bytes = MeteredVec::with_capacity(meter, input.len())?;
50        bytes.extend_from_slice(input)?;
51        Ok(Self { bytes })
52    }
53    fn validate(bytes: MeteredVec<u8>, meter: &Arc<Meter>) -> Result<Self, Error> {
54        meter.count_decode(bytes.len() as u64)?;
55        validate(bytes.as_slice())?;
56        Ok(Self { bytes })
57    }
58    #[cfg_attr(
59        not(feature = "vorbis"),
60        allow(dead_code, reason = "used by the optional Vorbis decoder")
61    )]
62    pub(crate) fn get(&self, crc: u32, meter: &Arc<Meter>) -> Result<&[u8], Error> {
63        let mut rest = self
64            .bytes
65            .as_slice()
66            .get(8..)
67            .ok_or(Error::Invalid("Vorbis table"))?;
68        while !rest.is_empty() {
69            meter.count_decode(8)?;
70            let key = word(&mut rest)?;
71            let size = word(&mut rest)? as usize;
72            let packet = take(&mut rest, size)?;
73            if key == crc {
74                return Ok(packet);
75            }
76            if key > crc {
77                break;
78            }
79        }
80        Err(Error::VorbisSetupMissing { crc })
81    }
82}
83fn validate(mut bytes: &[u8]) -> Result<(), Error> {
84    if take(&mut bytes, 4)? != b"VST1" {
85        return Err(Error::Invalid("Vorbis table magic"));
86    }
87    let count = word(&mut bytes)?;
88    if count > 65536 || count as usize > bytes.len() / 15 {
89        return Err(Error::Invalid("Vorbis table count"));
90    }
91    let mut previous = None;
92    for _ in 0..count {
93        let key = word(&mut bytes)?;
94        if previous.is_some_and(|p| key <= p) {
95            return Err(Error::Invalid("Vorbis table key order"));
96        }
97        previous = Some(key);
98        let size = word(&mut bytes)? as usize;
99        if size > 65535 || !take(&mut bytes, size)?.starts_with(b"\x05vorbis") {
100            return Err(Error::Invalid("Vorbis setup packet"));
101        }
102    }
103    if !bytes.is_empty() {
104        return Err(Error::Invalid("Vorbis table trailing bytes"));
105    }
106    Ok(())
107}
108fn word(bytes: &mut &[u8]) -> Result<u32, Error> {
109    Ok(u32::from_le_bytes(
110        take(bytes, 4)?
111            .try_into()
112            .map_err(|_| Error::Invalid("Vorbis table word"))?,
113    ))
114}
115fn take<'a>(bytes: &mut &'a [u8], size: usize) -> Result<&'a [u8], Error> {
116    let (head, tail) = bytes
117        .split_at_checked(size)
118        .ok_or(Error::Invalid("Vorbis table bounds"))?;
119    *bytes = tail;
120    Ok(head)
121}