Skip to main content

zvidlib_vorbis_syntax/
lib.rs

1//! Vorbis configuration records and packet timing, shared by zvidlib's
2//! containers and its Vorbis codecs.
3//!
4//! A Vorbis stream is described by three header packets - identification,
5//! comment and setup - which Matroska and WebM carry Xiph-laced as
6//! `CodecPrivate` and a `WebCodecs` `AudioDecoderConfig.description` takes in
7//! the same form. [`VorbisConfig`] parses and writes them, and reads from the
8//! setup header the one thing a container does not record exactly: how many
9//! samples each audio packet decodes to.
10//!
11//! This is an internal crate of [zvidlib](https://crates.io/crates/zvidlib),
12//! which re-exports its public items under the paths documented there. Depend
13//! on `zvidlib` rather than on this crate directly.
14
15#[allow(unused_imports)]
16use zvidlib_core::*;
17
18use crate::{EncodedAudioSample, Error, ErrorKind, Result, SampleRange};
19
20/// How many packets an [`crate::AudioSampleReader`] must decode ahead of the
21/// first one a request needs: a Vorbis packet's samples are the overlap of its
22/// block with the previous packet's, so the previous packet has to be decoded
23/// first.
24pub const VORBIS_PREROLL_PACKETS: usize = 1;
25
26/// The three Vorbis I header packets and what zvidlib reads from them.
27#[derive(Clone, Debug, Eq, PartialEq)]
28pub struct VorbisConfig {
29    pub channels: u8,
30    pub sample_rate: u32,
31    /// The identification header's maximum, nominal and minimum bit rates,
32    /// in bits a second; zero where the stream does not say.
33    pub bitrate_maximum: i32,
34    pub bitrate_nominal: i32,
35    pub bitrate_minimum: i32,
36    /// The short and long block sizes, in samples.
37    pub block_sizes: (u16, u16),
38    pub identification_header: Vec<u8>,
39    pub comment_header: Vec<u8>,
40    pub setup_header: Vec<u8>,
41    /// Whether each mode the setup header defines codes a long block.
42    mode_block_flags: Vec<bool>,
43}
44
45impl VorbisConfig {
46    /// Validates and parses the three header packets.
47    pub fn from_headers(
48        identification_header: Vec<u8>,
49        comment_header: Vec<u8>,
50        setup_header: Vec<u8>,
51    ) -> Result<Self> {
52        let ident = &identification_header;
53        if ident.len() != 30 || ident[0] != 1 || &ident[1..7] != b"vorbis" {
54            return Err(malformed(
55                "Vorbis identification header is not a 30-byte type 1 packet",
56            ));
57        }
58        if u32::from_le_bytes(ident[7..11].try_into().expect("fixed")) != 0 {
59            return Err(unsupported("only Vorbis I streams are supported"));
60        }
61        let channels = ident[11];
62        let sample_rate = u32::from_le_bytes(ident[12..16].try_into().expect("fixed"));
63        let bitrate = |at: usize| i32::from_le_bytes(ident[at..at + 4].try_into().expect("fixed"));
64        let short_exponent = ident[28] & 0x0f;
65        let long_exponent = ident[28] >> 4;
66        if channels == 0 || sample_rate == 0 {
67            return Err(malformed(
68                "Vorbis identification header has no channels or sample rate",
69            ));
70        }
71        if !(6..=13).contains(&short_exponent)
72            || !(6..=13).contains(&long_exponent)
73            || short_exponent > long_exponent
74        {
75            return Err(malformed(
76                "Vorbis identification header has invalid block sizes",
77            ));
78        }
79        if ident[29] & 1 == 0 {
80            return Err(malformed(
81                "Vorbis identification header framing bit is unset",
82            ));
83        }
84        if comment_header.len() < 7 || comment_header[0] != 3 || &comment_header[1..7] != b"vorbis"
85        {
86            return Err(malformed("Vorbis comment header is not a type 3 packet"));
87        }
88        let mode_block_flags = parse_setup_modes(&setup_header, channels)?;
89        Ok(Self {
90            channels,
91            sample_rate,
92            bitrate_maximum: bitrate(16),
93            bitrate_nominal: bitrate(20),
94            bitrate_minimum: bitrate(24),
95            block_sizes: (1 << short_exponent, 1 << long_exponent),
96            identification_header,
97            comment_header,
98            setup_header,
99            mode_block_flags,
100        })
101    }
102
103    /// Parses the three header packets Xiph-laced, the form Matroska and WebM
104    /// `CodecPrivate` use: a byte holding the packet count less one (two), the
105    /// first two packets' sizes as runs of 255 ending in a smaller byte, then
106    /// the packets.
107    pub fn from_codec_private(codec_private: &[u8]) -> Result<Self> {
108        let (&count, mut rest) = codec_private
109            .split_first()
110            .ok_or_else(|| malformed("Vorbis CodecPrivate is empty"))?;
111        if count != 2 {
112            return Err(malformed(
113                "Vorbis CodecPrivate must lace three header packets",
114            ));
115        }
116        let mut sizes = [0_usize; 2];
117        for size in &mut sizes {
118            loop {
119                let (&byte, tail) = rest
120                    .split_first()
121                    .ok_or_else(|| malformed("Vorbis CodecPrivate lacing is truncated"))?;
122                rest = tail;
123                *size += usize::from(byte);
124                if byte != 255 {
125                    break;
126                }
127            }
128        }
129        if sizes[0] + sizes[1] > rest.len() {
130            return Err(malformed("Vorbis CodecPrivate is shorter than its lacing"));
131        }
132        let (identification, rest) = rest.split_at(sizes[0]);
133        let (comment, setup) = rest.split_at(sizes[1]);
134        Self::from_headers(identification.to_vec(), comment.to_vec(), setup.to_vec())
135    }
136
137    /// Writes the three header packets Xiph-laced, as Matroska and WebM
138    /// `CodecPrivate` and a `WebCodecs` decoder `description` take them.
139    pub fn to_codec_private(&self) -> Vec<u8> {
140        let mut out = vec![2];
141        for size in [self.identification_header.len(), self.comment_header.len()] {
142            out.extend(std::iter::repeat_n(255, size / 255));
143            out.push((size % 255) as u8);
144        }
145        out.extend_from_slice(&self.identification_header);
146        out.extend_from_slice(&self.comment_header);
147        out.extend_from_slice(&self.setup_header);
148        out
149    }
150
151    /// The block size an audio packet codes, read from its mode number.
152    pub fn packet_block_size(&self, packet: &[u8]) -> Result<u16> {
153        let mut bits = BitReader::new(packet);
154        if bits.read(1)? != 0 {
155            return Err(malformed("Vorbis audio packet has a header packet type"));
156        }
157        let mode_bits = ilog(self.mode_block_flags.len() as u32 - 1);
158        let mode = usize::try_from(bits.read(mode_bits)?).expect("at most eight bits");
159        let long = *self
160            .mode_block_flags
161            .get(mode)
162            .ok_or_else(|| malformed("Vorbis audio packet names an undefined mode"))?;
163        Ok(if long {
164            self.block_sizes.1
165        } else {
166            self.block_sizes.0
167        })
168    }
169
170    /// Assigns each audio packet, in stream order, the interval of decoded
171    /// samples it produces: none for the first, and for every later one a
172    /// quarter of its block size plus a quarter of the previous packet's.
173    pub fn encoded_samples(&self, packets: Vec<Vec<u8>>) -> Result<Vec<EncodedAudioSample>> {
174        let block_sizes = packets
175            .iter()
176            .map(|data| self.packet_block_size(data))
177            .collect::<Result<Vec<_>>>()?;
178        packets
179            .into_iter()
180            .zip(Self::decoded_ranges(block_sizes)?)
181            .map(|(data, decoded_range)| {
182                Ok(EncodedAudioSample {
183                    decoded_range,
184                    data,
185                })
186            })
187            .collect()
188    }
189
190    /// The interval of decoded samples each audio packet produces, in stream
191    /// order, from the packets' block sizes alone, as
192    /// [`Self::encoded_samples`] assigns them.
193    ///
194    /// A packet's mode number, and so its block size, is in its first byte:
195    /// the packet type bit and at most six bits of mode. So the intervals of a
196    /// whole stream need only the first byte of each packet, which is how an
197    /// on-demand reader indexes a Vorbis track without reading its packets.
198    pub fn decoded_ranges(block_sizes: impl IntoIterator<Item = u16>) -> Result<Vec<SampleRange>> {
199        let mut previous = None;
200        let mut end = 0_u64;
201        block_sizes
202            .into_iter()
203            .map(|block| {
204                let length = previous.map_or(0, |previous: u16| {
205                    (u64::from(previous) + u64::from(block)) / 4
206                });
207                previous = Some(block);
208                let start = end;
209                end += length;
210                SampleRange::new(start, end)
211            })
212            .collect()
213    }
214}
215
216/// Walks a setup header (Vorbis I specification section 4.2.4) far enough to
217/// validate its structure and read its modes' block flags, which come last.
218fn parse_setup_modes(setup: &[u8], channels: u8) -> Result<Vec<bool>> {
219    if setup.len() < 7 || setup[0] != 5 || &setup[1..7] != b"vorbis" {
220        return Err(malformed("Vorbis setup header is not a type 5 packet"));
221    }
222    let mut bits = BitReader::new(&setup[7..]);
223    let codebooks = bits.read(8)? + 1;
224    for _ in 0..codebooks {
225        skip_codebook(&mut bits)?;
226    }
227    let time_domain_transforms = bits.read(6)? + 1;
228    for _ in 0..time_domain_transforms {
229        if bits.read(16)? != 0 {
230            return Err(malformed(
231                "Vorbis setup header has a nonzero time domain type",
232            ));
233        }
234    }
235    let floors = bits.read(6)? + 1;
236    for _ in 0..floors {
237        skip_floor(&mut bits)?;
238    }
239    let residues = bits.read(6)? + 1;
240    for _ in 0..residues {
241        skip_residue(&mut bits)?;
242    }
243    let mappings = bits.read(6)? + 1;
244    for _ in 0..mappings {
245        skip_mapping(&mut bits, channels)?;
246    }
247    let modes = bits.read(6)? + 1;
248    let mut block_flags = Vec::with_capacity(modes as usize);
249    for _ in 0..modes {
250        block_flags.push(bits.read(1)? == 1);
251        if bits.read(16)? != 0 || bits.read(16)? != 0 {
252            return Err(malformed(
253                "Vorbis setup header mode has a nonzero window or transform type",
254            ));
255        }
256        if bits.read(8)? >= mappings {
257            return Err(malformed(
258                "Vorbis setup header mode names an undefined mapping",
259            ));
260        }
261    }
262    if bits.read(1)? != 1 {
263        return Err(malformed("Vorbis setup header framing bit is unset"));
264    }
265    Ok(block_flags)
266}
267
268fn skip_codebook(bits: &mut BitReader<'_>) -> Result<()> {
269    if bits.read(24)? != 0x56_4342 {
270        return Err(malformed("Vorbis codebook has an invalid sync pattern"));
271    }
272    let dimensions = bits.read(16)?;
273    let entries = bits.read(24)?;
274    if bits.read(1)? == 1 {
275        // Ordered: runs of entries sharing a length.
276        let mut current = 0;
277        bits.read(5)?;
278        while current < entries {
279            current += bits.read(ilog(entries - current))?;
280        }
281        if current > entries {
282            return Err(malformed(
283                "Vorbis codebook length runs overflow its entries",
284            ));
285        }
286    } else {
287        let sparse = bits.read(1)? == 1;
288        for _ in 0..entries {
289            if !sparse || bits.read(1)? == 1 {
290                bits.read(5)?;
291            }
292        }
293    }
294    match bits.read(4)? {
295        0 => {}
296        lookup_type @ (1 | 2) => {
297            bits.read(32)?;
298            bits.read(32)?;
299            let value_bits = bits.read(4)? + 1;
300            bits.read(1)?;
301            let values = if lookup_type == 1 {
302                lookup1_values(entries, dimensions)
303            } else {
304                u64::from(entries) * u64::from(dimensions)
305            };
306            bits.skip(values * u64::from(value_bits))?;
307        }
308        _ => return Err(malformed("Vorbis codebook has an invalid lookup type")),
309    }
310    Ok(())
311}
312
313fn skip_floor(bits: &mut BitReader<'_>) -> Result<()> {
314    match bits.read(16)? {
315        0 => {
316            bits.read(8 + 16 + 16 + 6 + 8)?;
317            let books = bits.read(4)? + 1;
318            bits.skip(u64::from(books) * 8)?;
319        }
320        1 => {
321            let partitions = bits.read(5)?;
322            let mut classes = Vec::with_capacity(partitions as usize);
323            for _ in 0..partitions {
324                classes.push(bits.read(4)?);
325            }
326            let class_count = classes.iter().max().map_or(0, |&max| max + 1);
327            let mut dimensions = Vec::with_capacity(class_count as usize);
328            for _ in 0..class_count {
329                dimensions.push(bits.read(3)? + 1);
330                let subclasses = bits.read(2)?;
331                if subclasses != 0 {
332                    bits.read(8)?;
333                }
334                bits.skip((1_u64 << subclasses) * 8)?;
335            }
336            bits.read(2)?;
337            let range_bits = bits.read(4)?;
338            for class in classes {
339                bits.skip(u64::from(dimensions[class as usize]) * u64::from(range_bits))?;
340            }
341        }
342        _ => return Err(malformed("Vorbis setup header has an invalid floor type")),
343    }
344    Ok(())
345}
346
347fn skip_residue(bits: &mut BitReader<'_>) -> Result<()> {
348    if bits.read(16)? > 2 {
349        return Err(malformed("Vorbis setup header has an invalid residue type"));
350    }
351    bits.read(24)?;
352    bits.read(24)?;
353    bits.read(24)?;
354    let classifications = bits.read(6)? + 1;
355    bits.read(8)?;
356    let mut books = 0;
357    for _ in 0..classifications {
358        let low = bits.read(3)?;
359        let high = if bits.read(1)? == 1 { bits.read(5)? } else { 0 };
360        books += (high << 3 | low).count_ones();
361    }
362    bits.skip(u64::from(books) * 8)
363}
364
365fn skip_mapping(bits: &mut BitReader<'_>, channels: u8) -> Result<()> {
366    if bits.read(16)? != 0 {
367        return Err(malformed("Vorbis setup header has an invalid mapping type"));
368    }
369    let submaps = if bits.read(1)? == 1 {
370        bits.read(4)? + 1
371    } else {
372        1
373    };
374    let channel_bits = ilog(u32::from(channels) - 1);
375    if bits.read(1)? == 1 {
376        let steps = bits.read(8)? + 1;
377        bits.skip(u64::from(steps) * 2 * u64::from(channel_bits))?;
378    }
379    if bits.read(2)? != 0 {
380        return Err(malformed(
381            "Vorbis setup header mapping reserved bits are set",
382        ));
383    }
384    if submaps > 1 {
385        bits.skip(u64::from(channels) * 4)?;
386    }
387    bits.skip(u64::from(submaps) * 24)
388}
389
390/// The number of bits needed to hold `value` (Vorbis I section 9.2.1).
391fn ilog(value: u32) -> u32 {
392    u32::BITS - value.leading_zeros()
393}
394
395/// The greatest integer whose `dimensions`th power is at most `entries`
396/// (Vorbis I section 9.2.3).
397fn lookup1_values(entries: u32, dimensions: u32) -> u64 {
398    if dimensions == 0 {
399        return 0;
400    }
401    let mut value = (f64::from(entries))
402        .powf(1.0 / f64::from(dimensions))
403        .floor() as u64;
404    while (value + 1)
405        .checked_pow(dimensions)
406        .is_some_and(|power| power <= u64::from(entries))
407    {
408        value += 1;
409    }
410    while value > 0
411        && value
412            .checked_pow(dimensions)
413            .is_none_or(|power| power > u64::from(entries))
414    {
415        value -= 1;
416    }
417    value
418}
419
420/// Reads Vorbis's least-significant-bit-first packing.
421struct BitReader<'a> {
422    bytes: &'a [u8],
423    position: u64,
424}
425
426impl<'a> BitReader<'a> {
427    fn new(bytes: &'a [u8]) -> Self {
428        Self { bytes, position: 0 }
429    }
430
431    fn read(&mut self, count: u32) -> Result<u32> {
432        debug_assert!(count <= 32);
433        let end = self.position + u64::from(count);
434        if end > self.bytes.len() as u64 * 8 {
435            return Err(malformed("Vorbis packet is truncated"));
436        }
437        let mut value = 0_u64;
438        for bit in 0..u64::from(count) {
439            let at = self.position + bit;
440            let byte = self.bytes[(at / 8) as usize];
441            value |= u64::from((byte >> (at % 8)) & 1) << bit;
442        }
443        self.position = end;
444        Ok(value as u32)
445    }
446
447    fn skip(&mut self, count: u64) -> Result<()> {
448        let end = self
449            .position
450            .checked_add(count)
451            .filter(|&end| end <= self.bytes.len() as u64 * 8)
452            .ok_or_else(|| malformed("Vorbis packet is truncated"))?;
453        self.position = end;
454        Ok(())
455    }
456}
457
458fn malformed(message: impl Into<String>) -> Error {
459    Error::new(ErrorKind::MalformedMedia, message)
460}
461
462fn unsupported(message: impl Into<String>) -> Error {
463    Error::new(ErrorKind::Unsupported, message)
464}