forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a5feaaTahinli2 months ago3162 commits

setup.rs595 lines, 20.5 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/// Everything the setup header configures.
203#[derive(Debug, Clone)]
204pub struct Setup {
205 /// Codebooks, indexed by number.
206 pub codebooks: Vec<Codebook>,
207 /// Floor configurations.
208 pub floors: Vec<FloorConfig>,
209 /// Residue configurations.
210 pub residues: Vec<ResidueConfig>,
211 /// Mapping configurations.
212 pub mappings: Vec<MappingConfig>,
213 /// Modes; an audio packet's first field is an index into this.
214 pub modes: Vec<Mode>,
215}
216
217impl Setup {
218 /// Parse the setup packet, header byte included.
219 pub fn parse(data: &[u8], ident: &Identification) -> Result<Setup> {
220 let mut bits = Bits::new(header_body(data, 5)?);
221 let channels = usize::from(ident.channels);
222
223 let codebook_count = bits.read(8) as usize + 1;
224 let mut codebooks = Vec::with_capacity(codebook_count);
225 for _ in 0..codebook_count {
226 codebooks.push(Codebook::parse(&mut bits)?);
227 }
228
229 // Time-domain transforms: a placeholder in Vorbis I, but the field is
230 // there and must read zero.
231 let time_count = bits.read(6) + 1;
232 for _ in 0..time_count {
233 if bits.read(16) != 0 {
234 return Err(Error::corrupt("time domain transform is not zero"));
235 }
236 }
237
238 let floor_count = bits.read(6) as usize + 1;
239 let mut floors = Vec::with_capacity(floor_count);
240 for _ in 0..floor_count {
241 floors.push(parse_floor(&mut bits, &codebooks, ident)?);
242 }
243
244 let residue_count = bits.read(6) as usize + 1;
245 let mut residues = Vec::with_capacity(residue_count);
246 for _ in 0..residue_count {
247 residues.push(parse_residue(&mut bits, codebooks.len())?);
248 }
249
250 let mapping_count = bits.read(6) as usize + 1;
251 let mut mappings = Vec::with_capacity(mapping_count);
252 for _ in 0..mapping_count {
253 mappings.push(parse_mapping(
254 &mut bits,
255 channels,
256 floors.len(),
257 residues.len(),
258 )?);
259 }
260
261 let mode_count = bits.read(6) as usize + 1;
262 let mut modes = Vec::with_capacity(mode_count);
263 for _ in 0..mode_count {
264 let block_flag = bits.bit();
265 let window_type = bits.read(16);
266 let transform_type = bits.read(16);
267 let mapping = bits.read(8) as usize;
268 if window_type != 0 || transform_type != 0 {
269 return Err(Error::corrupt("mode states an undefined transform"));
270 }
271 if mapping >= mappings.len() {
272 return Err(Error::corrupt("mode names a mapping that is not there"));
273 }
274 modes.push(Mode {
275 block_flag,
276 mapping,
277 });
278 }
279
280 if !bits.bit() || bits.eop() {
281 return Err(Error::corrupt("setup header framing"));
282 }
283
284 Ok(Setup {
285 codebooks,
286 floors,
287 residues,
288 mappings,
289 modes,
290 })
291 }
292}
293
294/// Strip and check the `type, "vorbis"` prefix every header carries.
295fn header_body(data: &[u8], kind: u8) -> Result<&[u8]> {
296 if data.len() < 7 || data[0] != kind || &data[1..7] != b"vorbis" {
297 return Err(Error::corrupt(format!(
298 "not a Vorbis header of type {kind}"
299 )));
300 }
301 Ok(&data[7..])
302}
303
304fn parse_floor(
305 bits: &mut Bits,
306 codebooks: &[Codebook],
307 ident: &Identification,
308) -> Result<FloorConfig> {
309 match bits.read(16) {
310 0 => {
311 let order = bits.read(8) as usize;
312 let rate = bits.read(16);
313 let bark_map_size = bits.read(16) as usize;
314 let amplitude_bits = bits.read(6);
315 let amplitude_offset = bits.read(8) as f32;
316 let book_count = bits.read(4) as usize + 1;
317 let mut books = Vec::with_capacity(book_count);
318 for _ in 0..book_count {
319 let book = bits.read(8) as usize;
320 if book >= codebooks.len() {
321 return Err(Error::corrupt("floor 0 names a book that is not there"));
322 }
323 books.push(book);
324 }
325 if bits.eop() || order == 0 || bark_map_size == 0 || amplitude_bits > 32 {
326 return Err(Error::corrupt("floor 0 configuration"));
327 }
328 Ok(FloorConfig::Zero(Floor0 {
329 order,
330 rate,
331 bark_map_size,
332 amplitude_bits,
333 amplitude_offset,
334 books,
335 }))
336 }
337 1 => {
338 let partitions = bits.read(5) as usize;
339 let mut partition_classes = Vec::with_capacity(partitions);
340 let mut max_class = 0usize;
341 for _ in 0..partitions {
342 let class = bits.read(4) as usize;
343 max_class = max_class.max(class);
344 partition_classes.push(class);
345 }
346 let class_count = if partitions == 0 { 0 } else { max_class + 1 };
347 let mut class_dimensions = Vec::with_capacity(class_count);
348 let mut class_subclasses = Vec::with_capacity(class_count);
349 let mut class_masterbooks = Vec::with_capacity(class_count);
350 let mut subclass_books = Vec::with_capacity(class_count);
351 for _ in 0..class_count {
352 let dimensions = bits.read(3) as usize + 1;
353 let subclasses = bits.read(2);
354 let masterbook = if subclasses > 0 {
355 let book = bits.read(8) as usize;
356 if book >= codebooks.len() {
357 return Err(Error::corrupt(
358 "floor 1 names a masterbook that is not there",
359 ));
360 }
361 book
362 } else {
363 0
364 };
365 let mut books = Vec::with_capacity(1 << subclasses);
366 for _ in 0..(1u32 << subclasses) {
367 let book = bits.read(8) as i32 - 1;
368 if book >= codebooks.len() as i32 {
369 return Err(Error::corrupt("floor 1 names a book that is not there"));
370 }
371 books.push(book);
372 }
373 class_dimensions.push(dimensions);
374 class_subclasses.push(subclasses);
375 class_masterbooks.push(masterbook);
376 subclass_books.push(books);
377 }
378 let multiplier = bits.read(2) as i32 + 1;
379 let range_bits = bits.read(4);
380 let mut x_list = vec![0u32, 1u32 << range_bits];
381 for &class in &partition_classes {
382 for _ in 0..class_dimensions[class] {
383 x_list.push(bits.read(range_bits));
384 }
385 }
386 if bits.eop() {
387 return Err(Error::corrupt("floor 1 configuration truncated"));
388 }
389 if x_list.len() > 65 {
390 return Err(Error::corrupt("floor 1 states more than 65 values"));
391 }
392 // The X list must be distinct or the curve has two heights at one
393 // place; a stream that says so is corrupt, not a rendering choice.
394 let mut seen = x_list.clone();
395 seen.sort_unstable();
396 if seen.windows(2).any(|w| w[0] == w[1]) {
397 return Err(Error::corrupt("floor 1 repeats an X coordinate"));
398 }
399 if *seen.last().unwrap_or(&0) as usize > ident.blocksize_1 / 2 {
400 return Err(Error::corrupt("floor 1 X coordinate past the block"));
401 }
402 let mut sorted: Vec<usize> = (0..x_list.len()).collect();
403 sorted.sort_by_key(|&i| x_list[i]);
404 let neighbours = (0..x_list.len())
405 .map(|i| (low_neighbour(&x_list, i), high_neighbour(&x_list, i)))
406 .collect();
407 Ok(FloorConfig::One(Floor1 {
408 partition_classes,
409 class_dimensions,
410 class_subclasses,
411 class_masterbooks,
412 subclass_books,
413 multiplier,
414 x_list,
415 sorted,
416 neighbours,
417 }))
418 }
419 other => Err(Error::unsupported(
420 format!("floor type {other}"),
421 "Vorbis I defines floor 0 and floor 1",
422 )),
423 }
424}
425
426/// Coding-order index of the largest X below `x_list[i]` among values already
427/// coded (§7.2.2 `low_neighbor`).
428fn low_neighbour(x_list: &[u32], i: usize) -> usize {
429 let mut best = 0usize;
430 let mut best_x = None;
431 for (j, &x) in x_list.iter().enumerate().take(i) {
432 if x < x_list[i] && best_x.is_none_or(|b| x > b) {
433 best = j;
434 best_x = Some(x);
435 }
436 }
437 best
438}
439
440/// The mirror of [`low_neighbour`].
441fn high_neighbour(x_list: &[u32], i: usize) -> usize {
442 let mut best = 0usize;
443 let mut best_x = None;
444 for (j, &x) in x_list.iter().enumerate().take(i) {
445 if x > x_list[i] && best_x.is_none_or(|b| x < b) {
446 best = j;
447 best_x = Some(x);
448 }
449 }
450 best
451}
452
453fn parse_residue(bits: &mut Bits, codebook_count: usize) -> Result<ResidueConfig> {
454 let kind = bits.read(16);
455 if kind > 2 {
456 return Err(Error::unsupported(
457 format!("residue type {kind}"),
458 "Vorbis I defines 0, 1 and 2",
459 ));
460 }
461 let begin = bits.read(24) as usize;
462 let end = bits.read(24) as usize;
463 let partition_size = bits.read(24) as usize + 1;
464 let classifications = bits.read(6) as usize + 1;
465 let classbook = bits.read(8) as usize;
466 if bits.eop() || classbook >= codebook_count || end < begin {
467 return Err(Error::corrupt("residue configuration"));
468 }
469 let mut cascade = Vec::with_capacity(classifications);
470 for _ in 0..classifications {
471 let low = bits.read(3);
472 let high = if bits.bit() { bits.read(5) } else { 0 };
473 cascade.push((high << 3) | low);
474 }
475 let mut books = Vec::with_capacity(classifications);
476 for &cascade in &cascade {
477 let mut row = [-1i32; 8];
478 for (pass, slot) in row.iter_mut().enumerate() {
479 if cascade & (1 << pass) != 0 {
480 let book = bits.read(8) as usize;
481 if book >= codebook_count {
482 return Err(Error::corrupt("residue names a book that is not there"));
483 }
484 *slot = book as i32;
485 }
486 }
487 books.push(row);
488 }
489 if bits.eop() {
490 return Err(Error::corrupt("residue configuration truncated"));
491 }
492 Ok(ResidueConfig {
493 kind: kind as u8,
494 begin,
495 end,
496 partition_size,
497 classifications,
498 classbook,
499 books,
500 })
501}
502
503fn parse_mapping(
504 bits: &mut Bits,
505 channels: usize,
506 floor_count: usize,
507 residue_count: usize,
508) -> Result<MappingConfig> {
509 if bits.read(16) != 0 {
510 return Err(Error::unsupported(
511 "mapping type other than 0",
512 "Vorbis I defines mapping type 0 only",
513 ));
514 }
515 let submap_count = if bits.bit() {
516 bits.read(4) as usize + 1
517 } else {
518 1
519 };
520 let mut coupling = Vec::new();
521 if bits.bit() {
522 let steps = bits.read(8) as usize + 1;
523 let field = ilog((channels - 1) as u32);
524 for _ in 0..steps {
525 let magnitude = bits.read(field) as usize;
526 let angle = bits.read(field) as usize;
527 if magnitude == angle || magnitude >= channels || angle >= channels {
528 return Err(Error::corrupt("coupling step names an impossible pair"));
529 }
530 coupling.push((magnitude, angle));
531 }
532 }
533 if bits.read(2) != 0 {
534 return Err(Error::corrupt("mapping reserved bits are not zero"));
535 }
536 let mux = match submap_count > 1 {
537 true => (0..channels)
538 .map(|_| {
539 let submap = bits.read(4) as usize;
540 match submap < submap_count {
541 true => Ok(submap),
542 false => Err(Error::corrupt("channel names a submap that is not there")),
543 }
544 })
545 .collect::<Result<Vec<_>>>()?,
546 false => vec![0; channels],
547 };
548 let mut submaps = Vec::with_capacity(submap_count);
549 for _ in 0..submap_count {
550 let _unused = bits.read(8);
551 let floor = bits.read(8) as usize;
552 let residue = bits.read(8) as usize;
553 if floor >= floor_count || residue >= residue_count {
554 return Err(Error::corrupt(
555 "submap names a floor or residue that is not there",
556 ));
557 }
558 submaps.push((floor, residue));
559 }
560 if bits.eop() {
561 return Err(Error::corrupt("mapping truncated"));
562 }
563 Ok(MappingConfig {
564 coupling,
565 mux,
566 submaps,
567 })
568}
569
570#[cfg(test)]
571mod tests {
572 use super::*;
573
574 #[test]
575 fn identification_refuses_what_it_cannot_decode() {
576 assert!(Identification::parse(b"garbage").is_err());
577 // Type 1 header, blocksizes 256/2048, 2 channels, 44100 Hz.
578 let mut header = vec![1u8];
579 header.extend_from_slice(b"vorbis");
580 header.extend_from_slice(&0u32.to_le_bytes());
581 header.push(2);
582 header.extend_from_slice(&44_100u32.to_le_bytes());
583 header.extend_from_slice(&0i32.to_le_bytes());
584 header.extend_from_slice(&128_000i32.to_le_bytes());
585 header.extend_from_slice(&0i32.to_le_bytes());
586 header.push(0xb8); // blocksize_0 = 2^8, blocksize_1 = 2^11
587 header.push(0x01); // framing
588 let ident = Identification::parse(&header).expect("identification");
589 assert_eq!(ident.channels, 2);
590 assert_eq!(ident.rate, 44_100);
591 assert_eq!(ident.blocksize_0, 256);
592 assert_eq!(ident.blocksize_1, 2048);
593 assert_eq!(ident.bitrate_nominal, 128_000);
594 }
595}