forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

setup.rs600 lines, 20.7 KiBHistoryRawDownload
1//! The three header packets: identification, comment, setup.
2//!
3//! Everything a Vorbis stream needs before its first audio packet lives here —
4//! the blocksizes, the codebooks, and the floor/residue/mapping/mode
5//! configurations that audio packets index by number. The setup header is
6//! parsed once; audio decode after that is pure lookup.
7
8use ec_core::{Error, Result};
9
10use crate::bits::Bits;
11use crate::codebook::{Codebook, ilog};
12
13/// Identification header (§4.2.2).
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct Identification {
16 /// Channel count, in Vorbis channel order.
17 pub channels: u8,
18 /// Sample rate in Hz.
19 pub rate: u32,
20 /// Nominal bitrate the encoder stated, 0 when it stated none.
21 pub bitrate_nominal: i32,
22 /// Short block size in samples.
23 pub blocksize_0: usize,
24 /// Long block size in samples.
25 pub blocksize_1: usize,
26}
27
28impl Identification {
29 /// Parse the identification packet, header byte included.
30 pub fn parse(data: &[u8]) -> Result<Identification> {
31 let mut bits = Bits::new(header_body(data, 1)?);
32 let version = bits.read(32);
33 if version != 0 {
34 return Err(Error::unsupported(
35 format!("Vorbis bitstream version {version}"),
36 "only version 0 (Vorbis I) is defined",
37 ));
38 }
39 let channels = bits.read(8) as u8;
40 let rate = bits.read(32);
41 let _bitrate_maximum = bits.read(32) as i32;
42 let bitrate_nominal = bits.read(32) as i32;
43 let _bitrate_minimum = bits.read(32) as i32;
44 let blocksize_0 = 1usize << bits.read(4);
45 let blocksize_1 = 1usize << bits.read(4);
46 let framing = bits.bit();
47 if bits.eop() || !framing {
48 return Err(Error::corrupt("identification header truncated"));
49 }
50 if channels == 0 || rate == 0 {
51 return Err(Error::corrupt("identification header states no audio"));
52 }
53 let legal = |n: usize| n.is_power_of_two() && (64..=8192).contains(&n);
54 if !legal(blocksize_0) || !legal(blocksize_1) || blocksize_0 > blocksize_1 {
55 return Err(Error::corrupt(format!(
56 "blocksizes {blocksize_0}/{blocksize_1}"
57 )));
58 }
59 Ok(Identification {
60 channels,
61 rate,
62 bitrate_nominal,
63 blocksize_0,
64 blocksize_1,
65 })
66 }
67}
68
69/// Comment header (§5): the vendor string and the tag list.
70#[derive(Debug, Clone, Default, PartialEq, Eq)]
71pub struct Comments {
72 /// Encoder identification.
73 pub vendor: String,
74 /// `NAME=value` tags, in file order, with the name upper-cased.
75 pub tags: Vec<(String, String)>,
76}
77
78impl Comments {
79 /// Parse the comment packet, header byte included.
80 ///
81 /// A malformed tag is skipped rather than fatal: metadata never stops
82 /// audio from playing.
83 pub fn parse(data: &[u8]) -> Result<Comments> {
84 let body = header_body(data, 3)?;
85 let mut pos = 0usize;
86 let take = |pos: &mut usize| -> Option<String> {
87 let len = u32::from_le_bytes(body.get(*pos..*pos + 4)?.try_into().ok()?) as usize;
88 *pos += 4;
89 let text = body.get(*pos..pos.checked_add(len)?)?;
90 *pos += len;
91 Some(String::from_utf8_lossy(text).into_owned())
92 };
93 let vendor = take(&mut pos).ok_or_else(|| Error::corrupt("comment vendor string"))?;
94 let count = u32::from_le_bytes(
95 body.get(pos..pos + 4)
96 .ok_or_else(|| Error::corrupt("comment count"))?
97 .try_into()
98 .map_err(|_| Error::corrupt("comment count"))?,
99 );
100 pos += 4;
101 let mut tags = Vec::new();
102 for _ in 0..count {
103 let Some(entry) = take(&mut pos) else { break };
104 if let Some((name, value)) = entry.split_once('=') {
105 tags.push((name.to_ascii_uppercase(), value.to_string()));
106 }
107 }
108 Ok(Comments { vendor, tags })
109 }
110}
111
112/// Floor type 0: an LSP curve (§6.2).
113#[derive(Debug, Clone)]
114pub struct Floor0 {
115 /// LSP order.
116 pub order: usize,
117 /// Rate the bark map is built against.
118 pub rate: u32,
119 /// Bark map resolution.
120 pub bark_map_size: usize,
121 /// Bits the amplitude is stated in.
122 pub amplitude_bits: u32,
123 /// dB offset applied to the amplitude.
124 pub amplitude_offset: f32,
125 /// Books the coefficient vector may be coded with.
126 pub books: Vec<usize>,
127}
128
129/// Floor type 1: a piecewise-linear curve in dB (§7.2).
130#[derive(Debug, Clone)]
131pub struct Floor1 {
132 /// Class of each partition, in order.
133 pub partition_classes: Vec<usize>,
134 /// Values per class.
135 pub class_dimensions: Vec<usize>,
136 /// Subclass bits per class.
137 pub class_subclasses: Vec<u32>,
138 /// Book naming the subclass, per class; unused when `class_subclasses` is 0.
139 pub class_masterbooks: Vec<usize>,
140 /// Book per subclass, `-1` for "this subclass codes nothing".
141 pub subclass_books: Vec<Vec<i32>>,
142 /// dB step per Y unit.
143 pub multiplier: i32,
144 /// X coordinate of every value, in coding order.
145 pub x_list: Vec<u32>,
146 /// Indices of `x_list` sorted by X, the order the curve is rendered in.
147 pub sorted: Vec<usize>,
148 /// Per value, the coding-order index of the nearest lower/higher X already
149 /// coded, precomputed because the decode loop needs it per packet.
150 pub neighbours: Vec<(usize, usize)>,
151}
152
153/// One floor configuration.
154#[derive(Debug, Clone)]
155pub enum FloorConfig {
156 /// LSP floor.
157 Zero(Floor0),
158 /// Piecewise-linear floor.
159 One(Floor1),
160}
161
162/// Residue configuration (§8).
163#[derive(Debug, Clone)]
164pub struct ResidueConfig {
165 /// 0, 1 or 2 — how a partition's values are laid out.
166 pub kind: u8,
167 /// First coefficient coded.
168 pub begin: usize,
169 /// One past the last coefficient coded.
170 pub end: usize,
171 /// Coefficients per partition.
172 pub partition_size: usize,
173 /// Number of classes.
174 pub classifications: usize,
175 /// Book the class words are coded with.
176 pub classbook: usize,
177 /// Book per (class, pass), `-1` where the pass codes nothing.
178 pub books: Vec<[i32; 8]>,
179}
180
181/// Mapping configuration (§4.2.4): which floor and residue serve which channel,
182/// and which channel pairs are coupled.
183#[derive(Debug, Clone)]
184pub struct MappingConfig {
185 /// `(magnitude, angle)` channel per coupling step.
186 pub coupling: Vec<(usize, usize)>,
187 /// Submap per channel.
188 pub mux: Vec<usize>,
189 /// `(floor, residue)` per submap.
190 pub submaps: Vec<(usize, usize)>,
191}
192
193/// One mode (§4.2.4): a block size and a mapping.
194#[derive(Debug, Clone, Copy)]
195pub struct Mode {
196 /// False for a short block, true for a long one.
197 pub block_flag: bool,
198 /// Mapping this mode decodes with.
199 pub mapping: usize,
200}
201
202/// Expanded codebook values one setup header may allocate, across all its books: 4M floats,
203/// 16 MiB. A real encoder's books come to a few hundred thousand.
204const CODEBOOK_VALUE_BUDGET: usize = 1 << 22;
205
206/// Everything the setup header configures.
207#[derive(Debug, Clone)]
208pub struct Setup {
209 /// Codebooks, indexed by number.
210 pub codebooks: Vec<Codebook>,
211 /// Floor configurations.
212 pub floors: Vec<FloorConfig>,
213 /// Residue configurations.
214 pub residues: Vec<ResidueConfig>,
215 /// Mapping configurations.
216 pub mappings: Vec<MappingConfig>,
217 /// Modes; an audio packet's first field is an index into this.
218 pub modes: Vec<Mode>,
219}
220
221impl Setup {
222 /// Parse the setup packet, header byte included.
223 pub fn parse(data: &[u8], ident: &Identification) -> Result<Setup> {
224 let mut bits = Bits::new(header_body(data, 5)?);
225 let channels = usize::from(ident.channels);
226
227 let codebook_count = bits.read(8) as usize + 1;
228 let mut codebooks = Vec::with_capacity(codebook_count);
229 let mut value_budget = CODEBOOK_VALUE_BUDGET;
230 for _ in 0..codebook_count {
231 codebooks.push(Codebook::parse(&mut bits, &mut value_budget)?);
232 }
233
234 // Time-domain transforms: a placeholder in Vorbis I, but the field is
235 // there and must read zero.
236 let time_count = bits.read(6) + 1;
237 for _ in 0..time_count {
238 if bits.read(16) != 0 {
239 return Err(Error::corrupt("time domain transform is not zero"));
240 }
241 }
242
243 let floor_count = bits.read(6) as usize + 1;
244 let mut floors = Vec::with_capacity(floor_count);
245 for _ in 0..floor_count {
246 floors.push(parse_floor(&mut bits, &codebooks, ident)?);
247 }
248
249 let residue_count = bits.read(6) as usize + 1;
250 let mut residues = Vec::with_capacity(residue_count);
251 for _ in 0..residue_count {
252 residues.push(parse_residue(&mut bits, codebooks.len())?);
253 }
254
255 let mapping_count = bits.read(6) as usize + 1;
256 let mut mappings = Vec::with_capacity(mapping_count);
257 for _ in 0..mapping_count {
258 mappings.push(parse_mapping(
259 &mut bits,
260 channels,
261 floors.len(),
262 residues.len(),
263 )?);
264 }
265
266 let mode_count = bits.read(6) as usize + 1;
267 let mut modes = Vec::with_capacity(mode_count);
268 for _ in 0..mode_count {
269 let block_flag = bits.bit();
270 let window_type = bits.read(16);
271 let transform_type = bits.read(16);
272 let mapping = bits.read(8) as usize;
273 if window_type != 0 || transform_type != 0 {
274 return Err(Error::corrupt("mode states an undefined transform"));
275 }
276 if mapping >= mappings.len() {
277 return Err(Error::corrupt("mode names a mapping that is not there"));
278 }
279 modes.push(Mode {
280 block_flag,
281 mapping,
282 });
283 }
284
285 if !bits.bit() || bits.eop() {
286 return Err(Error::corrupt("setup header framing"));
287 }
288
289 Ok(Setup {
290 codebooks,
291 floors,
292 residues,
293 mappings,
294 modes,
295 })
296 }
297}
298
299/// Strip and check the `type, "vorbis"` prefix every header carries.
300fn header_body(data: &[u8], kind: u8) -> Result<&[u8]> {
301 if data.len() < 7 || data[0] != kind || &data[1..7] != b"vorbis" {
302 return Err(Error::corrupt(format!(
303 "not a Vorbis header of type {kind}"
304 )));
305 }
306 Ok(&data[7..])
307}
308
309fn parse_floor(
310 bits: &mut Bits,
311 codebooks: &[Codebook],
312 ident: &Identification,
313) -> Result<FloorConfig> {
314 match bits.read(16) {
315 0 => {
316 let order = bits.read(8) as usize;
317 let rate = bits.read(16);
318 let bark_map_size = bits.read(16) as usize;
319 let amplitude_bits = bits.read(6);
320 let amplitude_offset = bits.read(8) as f32;
321 let book_count = bits.read(4) as usize + 1;
322 let mut books = Vec::with_capacity(book_count);
323 for _ in 0..book_count {
324 let book = bits.read(8) as usize;
325 if book >= codebooks.len() {
326 return Err(Error::corrupt("floor 0 names a book that is not there"));
327 }
328 books.push(book);
329 }
330 if bits.eop() || order == 0 || bark_map_size == 0 || amplitude_bits > 32 {
331 return Err(Error::corrupt("floor 0 configuration"));
332 }
333 Ok(FloorConfig::Zero(Floor0 {
334 order,
335 rate,
336 bark_map_size,
337 amplitude_bits,
338 amplitude_offset,
339 books,
340 }))
341 }
342 1 => {
343 let partitions = bits.read(5) as usize;
344 let mut partition_classes = Vec::with_capacity(partitions);
345 let mut max_class = 0usize;
346 for _ in 0..partitions {
347 let class = bits.read(4) as usize;
348 max_class = max_class.max(class);
349 partition_classes.push(class);
350 }
351 let class_count = if partitions == 0 { 0 } else { max_class + 1 };
352 let mut class_dimensions = Vec::with_capacity(class_count);
353 let mut class_subclasses = Vec::with_capacity(class_count);
354 let mut class_masterbooks = Vec::with_capacity(class_count);
355 let mut subclass_books = Vec::with_capacity(class_count);
356 for _ in 0..class_count {
357 let dimensions = bits.read(3) as usize + 1;
358 let subclasses = bits.read(2);
359 let masterbook = if subclasses > 0 {
360 let book = bits.read(8) as usize;
361 if book >= codebooks.len() {
362 return Err(Error::corrupt(
363 "floor 1 names a masterbook that is not there",
364 ));
365 }
366 book
367 } else {
368 0
369 };
370 let mut books = Vec::with_capacity(1 << subclasses);
371 for _ in 0..(1u32 << subclasses) {
372 let book = bits.read(8) as i32 - 1;
373 if book >= codebooks.len() as i32 {
374 return Err(Error::corrupt("floor 1 names a book that is not there"));
375 }
376 books.push(book);
377 }
378 class_dimensions.push(dimensions);
379 class_subclasses.push(subclasses);
380 class_masterbooks.push(masterbook);
381 subclass_books.push(books);
382 }
383 let multiplier = bits.read(2) as i32 + 1;
384 let range_bits = bits.read(4);
385 let mut x_list = vec![0u32, 1u32 << range_bits];
386 for &class in &partition_classes {
387 for _ in 0..class_dimensions[class] {
388 x_list.push(bits.read(range_bits));
389 }
390 }
391 if bits.eop() {
392 return Err(Error::corrupt("floor 1 configuration truncated"));
393 }
394 if x_list.len() > 65 {
395 return Err(Error::corrupt("floor 1 states more than 65 values"));
396 }
397 // The X list must be distinct or the curve has two heights at one
398 // place; a stream that says so is corrupt, not a rendering choice.
399 let mut seen = x_list.clone();
400 seen.sort_unstable();
401 if seen.windows(2).any(|w| w[0] == w[1]) {
402 return Err(Error::corrupt("floor 1 repeats an X coordinate"));
403 }
404 if *seen.last().unwrap_or(&0) as usize > ident.blocksize_1 / 2 {
405 return Err(Error::corrupt("floor 1 X coordinate past the block"));
406 }
407 let mut sorted: Vec<usize> = (0..x_list.len()).collect();
408 sorted.sort_by_key(|&i| x_list[i]);
409 let neighbours = (0..x_list.len())
410 .map(|i| (low_neighbour(&x_list, i), high_neighbour(&x_list, i)))
411 .collect();
412 Ok(FloorConfig::One(Floor1 {
413 partition_classes,
414 class_dimensions,
415 class_subclasses,
416 class_masterbooks,
417 subclass_books,
418 multiplier,
419 x_list,
420 sorted,
421 neighbours,
422 }))
423 }
424 other => Err(Error::unsupported(
425 format!("floor type {other}"),
426 "Vorbis I defines floor 0 and floor 1",
427 )),
428 }
429}
430
431/// Coding-order index of the largest X below `x_list[i]` among values already
432/// coded (§7.2.2 `low_neighbor`).
433fn low_neighbour(x_list: &[u32], i: usize) -> usize {
434 let mut best = 0usize;
435 let mut best_x = None;
436 for (j, &x) in x_list.iter().enumerate().take(i) {
437 if x < x_list[i] && best_x.is_none_or(|b| x > b) {
438 best = j;
439 best_x = Some(x);
440 }
441 }
442 best
443}
444
445/// The mirror of [`low_neighbour`].
446fn high_neighbour(x_list: &[u32], i: usize) -> usize {
447 let mut best = 0usize;
448 let mut best_x = None;
449 for (j, &x) in x_list.iter().enumerate().take(i) {
450 if x > x_list[i] && best_x.is_none_or(|b| x < b) {
451 best = j;
452 best_x = Some(x);
453 }
454 }
455 best
456}
457
458fn parse_residue(bits: &mut Bits, codebook_count: usize) -> Result<ResidueConfig> {
459 let kind = bits.read(16);
460 if kind > 2 {
461 return Err(Error::unsupported(
462 format!("residue type {kind}"),
463 "Vorbis I defines 0, 1 and 2",
464 ));
465 }
466 let begin = bits.read(24) as usize;
467 let end = bits.read(24) as usize;
468 let partition_size = bits.read(24) as usize + 1;
469 let classifications = bits.read(6) as usize + 1;
470 let classbook = bits.read(8) as usize;
471 if bits.eop() || classbook >= codebook_count || end < begin {
472 return Err(Error::corrupt("residue configuration"));
473 }
474 let mut cascade = Vec::with_capacity(classifications);
475 for _ in 0..classifications {
476 let low = bits.read(3);
477 let high = if bits.bit() { bits.read(5) } else { 0 };
478 cascade.push((high << 3) | low);
479 }
480 let mut books = Vec::with_capacity(classifications);
481 for &cascade in &cascade {
482 let mut row = [-1i32; 8];
483 for (pass, slot) in row.iter_mut().enumerate() {
484 if cascade & (1 << pass) != 0 {
485 let book = bits.read(8) as usize;
486 if book >= codebook_count {
487 return Err(Error::corrupt("residue names a book that is not there"));
488 }
489 *slot = book as i32;
490 }
491 }
492 books.push(row);
493 }
494 if bits.eop() {
495 return Err(Error::corrupt("residue configuration truncated"));
496 }
497 Ok(ResidueConfig {
498 kind: kind as u8,
499 begin,
500 end,
501 partition_size,
502 classifications,
503 classbook,
504 books,
505 })
506}
507
508fn parse_mapping(
509 bits: &mut Bits,
510 channels: usize,
511 floor_count: usize,
512 residue_count: usize,
513) -> Result<MappingConfig> {
514 if bits.read(16) != 0 {
515 return Err(Error::unsupported(
516 "mapping type other than 0",
517 "Vorbis I defines mapping type 0 only",
518 ));
519 }
520 let submap_count = if bits.bit() {
521 bits.read(4) as usize + 1
522 } else {
523 1
524 };
525 let mut coupling = Vec::new();
526 if bits.bit() {
527 let steps = bits.read(8) as usize + 1;
528 let field = ilog((channels - 1) as u32);
529 for _ in 0..steps {
530 let magnitude = bits.read(field) as usize;
531 let angle = bits.read(field) as usize;
532 if magnitude == angle || magnitude >= channels || angle >= channels {
533 return Err(Error::corrupt("coupling step names an impossible pair"));
534 }
535 coupling.push((magnitude, angle));
536 }
537 }
538 if bits.read(2) != 0 {
539 return Err(Error::corrupt("mapping reserved bits are not zero"));
540 }
541 let mux = match submap_count > 1 {
542 true => (0..channels)
543 .map(|_| {
544 let submap = bits.read(4) as usize;
545 match submap < submap_count {
546 true => Ok(submap),
547 false => Err(Error::corrupt("channel names a submap that is not there")),
548 }
549 })
550 .collect::<Result<Vec<_>>>()?,
551 false => vec![0; channels],
552 };
553 let mut submaps = Vec::with_capacity(submap_count);
554 for _ in 0..submap_count {
555 let _unused = bits.read(8);
556 let floor = bits.read(8) as usize;
557 let residue = bits.read(8) as usize;
558 if floor >= floor_count || residue >= residue_count {
559 return Err(Error::corrupt(
560 "submap names a floor or residue that is not there",
561 ));
562 }
563 submaps.push((floor, residue));
564 }
565 if bits.eop() {
566 return Err(Error::corrupt("mapping truncated"));
567 }
568 Ok(MappingConfig {
569 coupling,
570 mux,
571 submaps,
572 })
573}
574
575#[cfg(test)]
576mod tests {
577 use super::*;
578
579 #[test]
580 fn identification_refuses_what_it_cannot_decode() {
581 assert!(Identification::parse(b"garbage").is_err());
582 // Type 1 header, blocksizes 256/2048, 2 channels, 44100 Hz.
583 let mut header = vec![1u8];
584 header.extend_from_slice(b"vorbis");
585 header.extend_from_slice(&0u32.to_le_bytes());
586 header.push(2);
587 header.extend_from_slice(&44_100u32.to_le_bytes());
588 header.extend_from_slice(&0i32.to_le_bytes());
589 header.extend_from_slice(&128_000i32.to_le_bytes());
590 header.extend_from_slice(&0i32.to_le_bytes());
591 header.push(0xb8); // blocksize_0 = 2^8, blocksize_1 = 2^11
592 header.push(0x01); // framing
593 let ident = Identification::parse(&header).expect("identification");
594 assert_eq!(ident.channels, 2);
595 assert_eq!(ident.rate, 44_100);
596 assert_eq!(ident.blocksize_0, 256);
597 assert_eq!(ident.blocksize_1, 2048);
598 assert_eq!(ident.bitrate_nominal, 128_000);
599 }
600}