Skip to main content

threers_codec/
ogg.rs

1//! Ogg pages and packets as libogg delivers them: packets reassembled
2//! across pages, each tagged with the page's granule position when it is
3//! the last packet completed on that page (`-1` otherwise), a running packet
4//! number, and the end-of-stream flag on the final packet of an EOS page.
5//! Only the first logical stream (the first BOS page's serial) is followed.
6
7/// One reassembled Ogg packet.
8#[derive(Debug, Clone)]
9pub struct Packet {
10    /// The packet's bytes.
11    pub data: Vec<u8>,
12    /// The page's granule position if this packet completed last on it, else `-1`.
13    pub granulepos: i64,
14    /// Running packet number, from 0.
15    pub packetno: i64,
16    /// The last packet of the stream.
17    pub eos: bool,
18    /// Index of the page this packet completed on.
19    pub page: usize,
20}
21
22/// All packets of the first logical stream, plus the last page's granule.
23pub fn packets(data: &[u8]) -> Result<(Vec<Packet>, i64), String> {
24    let mut out = Vec::new();
25    let mut partial: Vec<u8> = Vec::new();
26    let mut serial: Option<u32> = None;
27    let mut off = 0;
28    let mut page_no = 0;
29    let mut last_granule = -1;
30    let mut packetno = 0i64;
31    while off + 27 <= data.len() {
32        if &data[off..off + 4] != b"OggS" {
33            // Resync on the next capture pattern.
34            match data[off + 1..].windows(4).position(|w| w == b"OggS") {
35                Some(p) => {
36                    off += 1 + p;
37                    continue;
38                }
39                None => break,
40            }
41        }
42        let flags = data[off + 5];
43        let granule = i64::from_le_bytes(data[off + 6..off + 14].try_into().unwrap());
44        let ser = u32::from_le_bytes(data[off + 14..off + 18].try_into().unwrap());
45        let nseg = data[off + 26] as usize;
46        let lacing = data
47            .get(off + 27..off + 27 + nseg)
48            .ok_or("truncated Ogg page")?;
49        let body_len: usize = lacing.iter().map(|&l| l as usize).sum();
50        let body_start = off + 27 + nseg;
51        let body = data
52            .get(body_start..body_start + body_len)
53            .ok_or("truncated Ogg page")?;
54        let next = body_start + body_len;
55        if serial.is_none() {
56            serial = Some(ser);
57        }
58        if Some(ser) != serial {
59            off = next;
60            continue;
61        }
62        if flags & 1 == 0 {
63            // A fresh page drops any unterminated packet only when the
64            // continuation flag says the page does not continue it.
65            partial.clear();
66        }
67        let eos_page = flags & 4 != 0;
68        // Index of the last segment that ends a packet.
69        let last_end = lacing.iter().rposition(|&l| l < 255);
70        let mut at = 0;
71        for (i, &l) in lacing.iter().enumerate() {
72            partial.extend_from_slice(&body[at..at + l as usize]);
73            at += l as usize;
74            if l < 255 {
75                let is_last = Some(i) == last_end;
76                out.push(Packet {
77                    data: std::mem::take(&mut partial),
78                    granulepos: if is_last { granule } else { -1 },
79                    packetno,
80                    eos: eos_page && is_last,
81                    page: page_no,
82                });
83                packetno += 1;
84            }
85        }
86        if granule != -1 {
87            last_granule = granule;
88        }
89        page_no += 1;
90        off = next;
91        if eos_page {
92            break;
93        }
94    }
95    Ok((out, last_granule))
96}
97
98/// FLAC in Ogg (`\x7fFLAC` mapping): STREAMINFO from the first packet, one
99/// frame per audio packet.
100pub fn decode_flac(data: &[u8]) -> Result<super::flac::Flac, String> {
101    let (pk, _) = packets(data)?;
102    let first = pk.first().ok_or("empty Ogg stream")?;
103    if !first.data.starts_with(b"\x7fFLAC") || first.data.len() < 13 + 4 + 34 {
104        return Err("not FLAC in Ogg".into());
105    }
106    let info = super::flac::parse_streaminfo(&first.data[13 + 4..])?;
107    let mut channels = vec![Vec::new(); info.channels as usize];
108    // Metadata packets follow (their count may be 0 = unknown); audio
109    // packets start with the frame sync.
110    for p in pk.iter().skip(1) {
111        if p.data.len() >= 2 && p.data[0] == 0xff && p.data[1] & 0xfe == 0xf8 {
112            super::flac::decode_frames(&p.data, &info, &mut channels)?;
113        }
114    }
115    Ok(super::flac::Flac { info, channels })
116}