forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

page.rs258 lines, 9.6 KiBHistoryRawDownload
1//! The page: Ogg's only structural unit (RFC 3533 §6).
2//!
3//! A page is a 27-byte fixed header, a segment table of 1..=255 lacing values,
4//! and a body whose length is the sum of those values. Packets are cut into
5//! 255-byte segments; a segment shorter than 255 ends its packet, which is why
6//! a packet whose length is an exact multiple of 255 needs a trailing zero-length
7//! segment — the single most-missed rule in the format, and the one that makes a
8//! decoder wait forever for a packet that already ended.
9
10use ec_core::{Error, Result};
11
12use crate::crc;
13
14/// Capture pattern every page starts with.
15pub const CAPTURE: [u8; 4] = *b"OggS";
16/// Bytes before the segment table.
17pub const HEADER_LEN: usize = 27;
18/// Most lacing values one page can carry.
19pub const MAX_SEGMENTS: usize = 255;
20/// Granule position meaning "no packet ends on this page" (RFC 3533 §6.1).
21pub const NO_GRANULE: i64 = -1;
22
23/// `header_type` bits.
24const FLAG_CONTINUED: u8 = 0x01;
25const FLAG_BOS: u8 = 0x02;
26const FLAG_EOS: u8 = 0x04;
27
28/// A page header, decoded.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct PageHeader {
31 /// The first segment continues a packet started on an earlier page.
32 pub continued: bool,
33 /// Beginning of stream: this page carries the stream's first packet.
34 pub bos: bool,
35 /// End of stream: the last page of this logical stream.
36 pub eos: bool,
37 /// Position of the last packet *completed* on this page, in the mapping's
38 /// own units, or [`NO_GRANULE`] when no packet ends here.
39 pub granule: i64,
40 /// Which logical stream this page belongs to.
41 pub serial: u32,
42 /// Page counter within the logical stream, from zero.
43 pub sequence: u32,
44 /// Lacing values, in order.
45 pub segments: Vec<u8>,
46}
47
48impl PageHeader {
49 /// Total body length: the sum of the lacing values.
50 pub fn body_len(&self) -> usize {
51 self.segments.iter().map(|&s| usize::from(s)).sum()
52 }
53
54 /// Decode the fixed part of a header. `buf` must hold at least
55 /// [`HEADER_LEN`] bytes; the segment table is read by the caller, which
56 /// knows how much more input it can supply.
57 ///
58 /// Returns the header with an empty segment table plus the segment count.
59 pub fn parse_fixed(buf: &[u8]) -> Result<(PageHeader, usize)> {
60 if buf.len() < HEADER_LEN {
61 return Err(Error::NeedMore);
62 }
63 if buf[..4] != CAPTURE {
64 return Err(Error::corrupt("Ogg page: no OggS capture pattern"));
65 }
66 if buf[4] != 0 {
67 return Err(Error::unsupported(
68 format!("Ogg stream structure version {}", buf[4]),
69 "only version 0 is defined",
70 ));
71 }
72 let flags = buf[5];
73 let header = PageHeader {
74 continued: flags & FLAG_CONTINUED != 0,
75 bos: flags & FLAG_BOS != 0,
76 eos: flags & FLAG_EOS != 0,
77 granule: i64::from_le_bytes(buf[6..14].try_into().unwrap()),
78 serial: u32::from_le_bytes(buf[14..18].try_into().unwrap()),
79 sequence: u32::from_le_bytes(buf[18..22].try_into().unwrap()),
80 segments: Vec::new(),
81 };
82 Ok((header, usize::from(buf[26])))
83 }
84
85 /// The checksum stored in a fixed header.
86 pub fn stored_crc(buf: &[u8]) -> u32 {
87 u32::from_le_bytes(buf[22..26].try_into().unwrap())
88 }
89
90 /// Serialize header and segment table, checksum included, and append the
91 /// body — the exact bytes of one page.
92 pub fn write_page(&self, body: &[u8], out: &mut Vec<u8>) {
93 debug_assert_eq!(self.body_len(), body.len());
94 debug_assert!(!self.segments.is_empty() && self.segments.len() <= MAX_SEGMENTS);
95 let start = out.len();
96 out.extend_from_slice(&CAPTURE);
97 out.push(0);
98 let mut flags = 0u8;
99 if self.continued {
100 flags |= FLAG_CONTINUED;
101 }
102 if self.bos {
103 flags |= FLAG_BOS;
104 }
105 if self.eos {
106 flags |= FLAG_EOS;
107 }
108 out.push(flags);
109 out.extend_from_slice(&self.granule.to_le_bytes());
110 out.extend_from_slice(&self.serial.to_le_bytes());
111 out.extend_from_slice(&self.sequence.to_le_bytes());
112 out.extend_from_slice(&[0; 4]); // checksum, filled in below
113 out.push(self.segments.len() as u8);
114 out.extend_from_slice(&self.segments);
115 out.extend_from_slice(body);
116 // The checksum covers the whole page with its own field read as zero.
117 let sum = crc::crc32(&[&out[start..]]);
118 out[start + 22..start + 26].copy_from_slice(&sum.to_le_bytes());
119 }
120}
121
122/// The lacing values a packet of `len` bytes becomes: `len / 255` values of 255
123/// then the remainder — including the explicit zero that terminates a packet
124/// whose length is a multiple of 255.
125pub fn lacing(len: usize) -> impl Iterator<Item = u8> {
126 let full = len / 255;
127 (0..=full).map(move |i| match i < full {
128 true => 255,
129 false => (len % 255) as u8,
130 })
131}
132
133/// The three Xiph header packets, laced the way `CodecParameters::extradata`
134/// carries them: two length prefixes in the 255-plus-remainder form, then the
135/// packets back to back, all behind a leading count of `2`.
136///
137/// This is the shape the oracle calls "Xiph extradata" and the one Vorbis, Theora
138/// and Speex setup data travels in outside of Ogg. [`None`] when a header is
139/// too long to describe (the format has no escape beyond a 255 run) or when the
140/// packet count is not the two-prefixed-plus-one this layout can express.
141pub fn xiph_lace(packets: &[&[u8]]) -> Option<Vec<u8>> {
142 if packets.len() < 2 || packets.len() > 256 {
143 return None;
144 }
145 let mut out = vec![(packets.len() - 1) as u8];
146 for packet in &packets[..packets.len() - 1] {
147 out.extend(lacing(packet.len()));
148 }
149 for packet in packets {
150 out.extend_from_slice(packet);
151 }
152 Some(out)
153}
154
155/// The inverse of [`xiph_lace`]: split laced extradata back into packets.
156pub fn xiph_unlace(data: &[u8]) -> Result<Vec<&[u8]>> {
157 let short = || Error::corrupt("Xiph extradata: truncated lacing");
158 let count = usize::from(*data.first().ok_or_else(short)?) + 1;
159 let mut at = 1;
160 let mut lengths = Vec::with_capacity(count);
161 for _ in 0..count - 1 {
162 let mut len = 0usize;
163 loop {
164 let lace = usize::from(*data.get(at).ok_or_else(short)?);
165 at += 1;
166 len += lace;
167 if lace < 255 {
168 break;
169 }
170 }
171 lengths.push(len);
172 }
173 let mut out = Vec::with_capacity(count);
174 for len in lengths {
175 let end = at.checked_add(len).ok_or_else(short)?;
176 out.push(data.get(at..end).ok_or_else(short)?);
177 at = end;
178 }
179 // The last packet runs to the end: its length is the one the layout does
180 // not store.
181 out.push(&data[at..]);
182 Ok(out)
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn lacing_terminates_multiples_of_255() {
191 assert_eq!(lacing(0).collect::<Vec<_>>(), vec![0]);
192 assert_eq!(lacing(1).collect::<Vec<_>>(), vec![1]);
193 assert_eq!(lacing(254).collect::<Vec<_>>(), vec![254]);
194 // The rule that matters: 255 is *not* one segment of 255, it is a 255
195 // and a 0, or the packet never ends.
196 assert_eq!(lacing(255).collect::<Vec<_>>(), vec![255, 0]);
197 assert_eq!(lacing(256).collect::<Vec<_>>(), vec![255, 1]);
198 assert_eq!(lacing(510).collect::<Vec<_>>(), vec![255, 255, 0]);
199 for len in [0, 1, 255, 256, 700, 65_535] {
200 let sum: usize = lacing(len).map(usize::from).sum();
201 assert_eq!(sum, len, "lacing must sum back to the packet length");
202 }
203 }
204
205 #[test]
206 fn page_round_trips_through_its_own_checksum() {
207 let body: Vec<u8> = (0..600u32).map(|i| (i % 251) as u8).collect();
208 let header = PageHeader {
209 continued: true,
210 bos: false,
211 eos: true,
212 granule: 123_456,
213 serial: 0xdead_beef,
214 sequence: 7,
215 segments: lacing(body.len()).collect(),
216 };
217 let mut bytes = Vec::new();
218 header.write_page(&body, &mut bytes);
219
220 let (parsed, nsegs) = PageHeader::parse_fixed(&bytes).unwrap();
221 let segments = bytes[HEADER_LEN..HEADER_LEN + nsegs].to_vec();
222 let parsed = PageHeader { segments, ..parsed };
223 assert_eq!(parsed, header);
224 assert_eq!(parsed.body_len(), body.len());
225
226 // The stored checksum verifies with its own field zeroed.
227 let stored = PageHeader::stored_crc(&bytes);
228 let mut zeroed = bytes.clone();
229 zeroed[22..26].fill(0);
230 assert_eq!(crc::crc32(&[&zeroed]), stored);
231 // ...and a single flipped body byte breaks it.
232 let mut damaged = zeroed.clone();
233 let last = damaged.len() - 1;
234 damaged[last] ^= 0x01;
235 assert_ne!(crc::crc32(&[&damaged]), stored);
236
237 assert!(PageHeader::parse_fixed(&bytes[..10]).is_err());
238 assert!(PageHeader::parse_fixed(b"NotAnOggPageHeaderAtAll....").is_err());
239 }
240
241 #[test]
242 fn xiph_lacing_round_trips() {
243 let ident = [1u8; 30];
244 let comment = [2u8; 300];
245 let setup = [3u8; 4000];
246 let packets = [&ident[..], &comment[..], &setup[..]];
247 let laced = xiph_lace(&packets).unwrap();
248 assert_eq!(laced[0], 2, "count byte is packets - 1");
249 let back = xiph_unlace(&laced).unwrap();
250 assert_eq!(back.len(), 3);
251 assert_eq!(back[0], &ident[..]);
252 assert_eq!(back[1], &comment[..]);
253 assert_eq!(back[2], &setup[..]);
254 assert!(xiph_lace(&[&ident[..]]).is_none());
255 assert!(xiph_unlace(&[]).is_err());
256 assert!(xiph_unlace(&[2, 255]).is_err());
257 }
258}