forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiBfbcc820Tahinli4 hours ago4154 commits

decode.rs1021 lines, 35.1 KiBHistoryRawDownload
1//! FLAC decoding: metadata blocks, frame headers, all four subframe kinds and
2//! the three stereo decorrelations, per RFC 9639.
3//!
4//! Every parse routine takes a borrowed buffer and answers with
5//! [`ec_core::Error`]: truncated input is `NeedMore`, a stream that breaks its
6//! own rules is `Corrupt`. Nothing here panics on input — the only asserts are
7//! in `ec_core::bitio`, and they fire on API misuse (`n > 64`), never on bytes.
8
9use ec_core::bitio::BitReader;
10use ec_core::error::{Error, Result};
11
12use crate::checksum::{crc8, crc16};
13
14/// The four bytes every FLAC stream starts with.
15pub const MAGIC: [u8; 4] = *b"fLaC";
16
17/// Largest block size RFC 9639 can express (16-bit `block_size - 1`).
18pub const MAX_BLOCK_SIZE: usize = 65536;
19
20/// The `STREAMINFO` metadata block: everything a player needs before the first
21/// frame.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct StreamInfo {
24 /// Smallest block size in the stream, in inter-channel samples.
25 pub min_block_size: u16,
26 /// Largest block size in the stream. Equal to `min_block_size` for a
27 /// fixed-block-size stream.
28 pub max_block_size: u16,
29 /// Smallest frame size in bytes; 0 when the encoder did not state it.
30 pub min_frame_size: u32,
31 /// Largest frame size in bytes; 0 when the encoder did not state it.
32 pub max_frame_size: u32,
33 /// Sample rate in Hz. 0 means "non-audio stream" and is refused here.
34 pub sample_rate: u32,
35 /// Channel count, 1..=8.
36 pub channels: u8,
37 /// Bits per sample, 4..=32.
38 pub bits_per_sample: u8,
39 /// Total inter-channel samples, or 0 when unknown.
40 pub total_samples: u64,
41 /// MD5 of the unencoded audio; all zero when the encoder did not compute it.
42 pub md5: [u8; 16],
43}
44
45impl StreamInfo {
46 /// Parse the 34-byte `STREAMINFO` payload.
47 pub fn parse(data: &[u8]) -> Result<StreamInfo> {
48 if data.len() < 34 {
49 return Err(Error::NeedMore);
50 }
51 let mut r = BitReader::new(data);
52 let info = StreamInfo {
53 min_block_size: r.read_bits(16)? as u16,
54 max_block_size: r.read_bits(16)? as u16,
55 min_frame_size: r.read_bits(24)?,
56 max_frame_size: r.read_bits(24)?,
57 sample_rate: r.read_bits(20)?,
58 channels: (r.read_bits(3)? + 1) as u8,
59 bits_per_sample: (r.read_bits(5)? + 1) as u8,
60 total_samples: r.read_bits64(36)?,
61 md5: data[18..34].try_into().expect("18..34 is 16 bytes"),
62 };
63 if info.sample_rate == 0 {
64 return Err(Error::corrupt("STREAMINFO: sample rate 0"));
65 }
66 if info.bits_per_sample < 4 {
67 return Err(Error::corrupt(format!(
68 "STREAMINFO: {} bits per sample",
69 info.bits_per_sample
70 )));
71 }
72 if info.min_block_size < 16 || info.max_block_size < 16 {
73 return Err(Error::corrupt(format!(
74 "STREAMINFO: block sizes {}..{}",
75 info.min_block_size, info.max_block_size
76 )));
77 }
78 Ok(info)
79 }
80
81 /// The 34-byte `STREAMINFO` payload.
82 pub fn to_bytes(&self) -> [u8; 34] {
83 let mut out = [0u8; 34];
84 out[0..2].copy_from_slice(&self.min_block_size.to_be_bytes());
85 out[2..4].copy_from_slice(&self.max_block_size.to_be_bytes());
86 out[4..7].copy_from_slice(&self.min_frame_size.to_be_bytes()[1..]);
87 out[7..10].copy_from_slice(&self.max_frame_size.to_be_bytes()[1..]);
88 let packed = (u64::from(self.sample_rate) << 44)
89 | (u64::from(self.channels - 1) << 41)
90 | (u64::from(self.bits_per_sample - 1) << 36)
91 | (self.total_samples & 0xf_ffff_ffff);
92 out[10..18].copy_from_slice(&packed.to_be_bytes());
93 out[18..34].copy_from_slice(&self.md5);
94 out
95 }
96}
97
98/// One entry of the `SEEKTABLE` block.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub struct SeekPoint {
101 /// First sample of the target frame.
102 pub sample: u64,
103 /// Byte offset of that frame from the first byte of the first frame.
104 pub offset: u64,
105 /// Samples in the target frame.
106 pub frame_samples: u16,
107}
108
109/// How the channels of one frame were decorrelated.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum ChannelAssignment {
112 /// `n` channels, each coded on its own.
113 Independent(u8),
114 /// Channel 0 is left, channel 1 is `left - right`.
115 LeftSide,
116 /// Channel 0 is `left - right`, channel 1 is right.
117 RightSide,
118 /// Channel 0 is `(left + right) >> 1`, channel 1 is `left - right`.
119 MidSide,
120}
121
122impl ChannelAssignment {
123 /// Channels coded in the frame.
124 pub fn channel_count(&self) -> usize {
125 match self {
126 ChannelAssignment::Independent(n) => *n as usize,
127 _ => 2,
128 }
129 }
130}
131
132/// A parsed frame header, with the `STREAMINFO` fallbacks already resolved.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub struct FrameHeader {
135 /// Inter-channel samples in this frame.
136 pub block_size: usize,
137 /// Sample rate in Hz.
138 pub sample_rate: u32,
139 /// Channel coding of this frame.
140 pub channels: ChannelAssignment,
141 /// Bits per sample of the *decoded* audio.
142 pub bits_per_sample: u32,
143 /// Frame number for a fixed-block-size stream, first sample number for a
144 /// variable-block-size one.
145 pub number: u64,
146 /// True when the stream declares variable block sizes.
147 pub variable_block_size: bool,
148}
149
150impl FrameHeader {
151 /// First inter-channel sample of this frame, when it can be known: a
152 /// variable-block-size stream states it, a fixed one implies it from the
153 /// frame number and the block size the stream was written with.
154 pub fn first_sample(&self, stream_block_size: Option<usize>) -> Option<u64> {
155 match self.variable_block_size {
156 true => Some(self.number),
157 false => stream_block_size.map(|bs| self.number * bs as u64),
158 }
159 }
160}
161
162/// A decoded block: one `Vec<i32>` per channel, samples at the frame's own
163/// bit depth (not shifted).
164#[derive(Debug, Clone, Default)]
165pub struct Block {
166 /// The header the samples came from.
167 pub header: Option<FrameHeader>,
168 /// Per-channel samples, already un-decorrelated.
169 pub channels: Vec<Vec<i32>>,
170}
171
172impl Block {
173 /// Samples per channel.
174 pub fn len(&self) -> usize {
175 self.channels.first().map_or(0, Vec::len)
176 }
177
178 /// True when no samples are held.
179 pub fn is_empty(&self) -> bool {
180 self.len() == 0
181 }
182
183 /// The block interleaved into one buffer, samples shifted left so they fill
184 /// a 16- or 32-bit container the way the oracle and every mixer expect
185 /// (`s16` for depths up to 16, `s32` above).
186 pub fn to_interleaved(&self, shift: u32) -> Vec<i32> {
187 let channels = self.channels.len();
188 let len = self.len();
189 let mut out = vec![0i32; len * channels];
190 for (c, plane) in self.channels.iter().enumerate() {
191 for (i, &s) in plane.iter().enumerate() {
192 out[i * channels + c] = s << shift;
193 }
194 }
195 out
196 }
197}
198
199/// Bits the samples of a `bits_per_sample` stream are shifted left by to fill
200/// their PCM container — the convention the oracle's decoder uses, so raw output
201/// compares byte for byte.
202pub fn container_shift(bits_per_sample: u32) -> u32 {
203 match bits_per_sample <= 16 {
204 true => 16 - bits_per_sample,
205 false => 32 - bits_per_sample,
206 }
207}
208
209/// A FLAC stream over a complete in-memory buffer.
210///
211/// Metadata is parsed on construction; frames are decoded one call at a time so
212/// a caller can stop, seek and resume without decoding what it will discard.
213#[derive(Debug)]
214pub struct FlacReader<'a> {
215 data: &'a [u8],
216 stream_info: Option<StreamInfo>,
217 seek_table: Vec<SeekPoint>,
218 first_frame: usize,
219 pos: usize,
220 residual: Vec<i32>,
221}
222
223impl<'a> FlacReader<'a> {
224 /// Open a stream: read the magic and metadata blocks, then stop at the
225 /// first frame.
226 ///
227 /// A buffer that does not start with `fLaC` is scanned for a frame sync
228 /// instead — some tools hand out FLAC that starts mid-stream, and the frame
229 /// headers carry enough to decode without `STREAMINFO`.
230 pub fn new(data: &'a [u8]) -> Result<FlacReader<'a>> {
231 let mut reader = FlacReader {
232 data,
233 stream_info: None,
234 seek_table: Vec::new(),
235 first_frame: 0,
236 pos: 0,
237 residual: Vec::new(),
238 };
239 if data.len() >= 4 && data[..4] == MAGIC {
240 reader.read_metadata(4)?;
241 } else {
242 reader.first_frame = find_frame_sync(data, 0, None)
243 .ok_or_else(|| Error::corrupt("no fLaC magic and no frame sync"))?;
244 reader.pos = reader.first_frame;
245 }
246 Ok(reader)
247 }
248
249 /// A reader over bare frames — what a container hands out, one packet at a
250 /// time, with the `STREAMINFO` it carried in its own headers.
251 pub fn frames(data: &'a [u8], info: Option<StreamInfo>) -> Result<FlacReader<'a>> {
252 let first_frame = find_frame_sync(data, 0, info.as_ref())
253 .ok_or_else(|| Error::corrupt("no FLAC frame sync in this packet"))?;
254 Ok(FlacReader {
255 data,
256 stream_info: info,
257 seek_table: Vec::new(),
258 first_frame,
259 pos: first_frame,
260 residual: Vec::new(),
261 })
262 }
263
264 fn read_metadata(&mut self, mut at: usize) -> Result<()> {
265 let mut first = true;
266 loop {
267 let header = self.data.get(at..at + 4).ok_or(Error::NeedMore)?;
268 let last = header[0] & 0x80 != 0;
269 let kind = header[0] & 0x7f;
270 let len = u32::from_be_bytes([0, header[1], header[2], header[3]]) as usize;
271 let body = self.data.get(at + 4..at + 4 + len).ok_or(Error::NeedMore)?;
272 if first && kind != 0 {
273 return Err(Error::corrupt(format!(
274 "first metadata block is type {kind}, not STREAMINFO"
275 )));
276 }
277 match kind {
278 0 => self.stream_info = Some(StreamInfo::parse(body)?),
279 3 => {
280 self.seek_table = body
281 .as_chunks::<18>()
282 .0
283 .iter()
284 .map(|p| SeekPoint {
285 sample: u64::from_be_bytes(p[0..8].try_into().expect("8 bytes")),
286 offset: u64::from_be_bytes(p[8..16].try_into().expect("8 bytes")),
287 frame_samples: u16::from_be_bytes(
288 p[16..18].try_into().expect("2 bytes"),
289 ),
290 })
291 // A placeholder point (sample == u64::MAX) indexes nothing.
292 .filter(|p| p.sample != u64::MAX)
293 .collect();
294 }
295 127 => return Err(Error::corrupt("metadata block type 127 is invalid")),
296 _ => {}
297 }
298 first = false;
299 at += 4 + len;
300 if last {
301 break;
302 }
303 }
304 self.first_frame = at;
305 self.pos = at;
306 Ok(())
307 }
308
309 /// The `STREAMINFO` block, when the stream had one.
310 pub fn stream_info(&self) -> Option<&StreamInfo> {
311 self.stream_info.as_ref()
312 }
313
314 /// The seek table, empty when the stream carries none.
315 pub fn seek_table(&self) -> &[SeekPoint] {
316 &self.seek_table
317 }
318
319 /// Byte offset of the next frame to be decoded.
320 pub fn position(&self) -> usize {
321 self.pos
322 }
323
324 /// Position the reader at the last indexed frame at or before `sample` and
325 /// answer that frame's first sample; the caller decodes forward and
326 /// discards the difference (`SeekMode::SyncBefore`).
327 ///
328 /// Without a seek table the answer is the start of the stream: FLAC frames
329 /// are not self-indexing, so a blind scan would cost the same as decoding.
330 pub fn seek_to_sample(&mut self, sample: u64) -> u64 {
331 let point = self
332 .seek_table
333 .iter()
334 .filter(|p| p.sample <= sample)
335 .max_by_key(|p| p.sample);
336 // The offset comes from the file: a hostile one must not overflow the sum
337 // or truncate on a 32-bit target, so it is checked as a whole.
338 let target = point.and_then(|p| {
339 let at = usize::try_from(p.offset)
340 .ok()?
341 .checked_add(self.first_frame)?;
342 (at <= self.data.len()).then_some((at, p.sample))
343 });
344 match target {
345 Some((at, sample)) => {
346 self.pos = at;
347 sample
348 }
349 None => {
350 self.pos = self.first_frame;
351 0
352 }
353 }
354 }
355
356 /// Decode the next frame into `block`, reusing its buffers.
357 ///
358 /// Answers `false` at the end of the stream. Trailing bytes that are not a
359 /// frame (an ID3v1 tag, padding a container left) end the stream rather
360 /// than failing it; a frame that starts well and then breaks is `Corrupt`.
361 pub fn next_block(&mut self, block: &mut Block) -> Result<bool> {
362 if self.pos >= self.data.len() {
363 return Ok(false);
364 }
365 let start = match find_frame_sync(self.data, self.pos, self.stream_info.as_ref()) {
366 Some(at) => at,
367 None => {
368 self.pos = self.data.len();
369 return Ok(false);
370 }
371 };
372 self.pos = start;
373 let mut r = BitReader::new(&self.data[start..]);
374 let header = parse_frame_header(&mut r, self.stream_info.as_ref())?;
375 let header_bytes = (r.bit_position() / 8) as usize;
376 let want = crc8(&self.data[start..start + header_bytes - 1]);
377 if want != self.data[start + header_bytes - 1] {
378 return Err(Error::corrupt(format!(
379 "frame at {start}: header CRC-8 {:#04x}, expected {want:#04x}",
380 self.data[start + header_bytes - 1]
381 )));
382 }
383
384 let coded = header.channels.channel_count();
385 block.channels.resize_with(coded, Vec::new);
386 for (c, plane) in block.channels.iter_mut().enumerate() {
387 let side = matches!(
388 (header.channels, c),
389 (ChannelAssignment::LeftSide, 1)
390 | (ChannelAssignment::MidSide, 1)
391 | (ChannelAssignment::RightSide, 0)
392 );
393 let bps = header.bits_per_sample + u32::from(side);
394 decode_subframe(&mut r, bps, header.block_size, plane, &mut self.residual)?;
395 }
396 r.align_to_byte();
397 let frame_bytes = (r.bit_position() / 8) as usize;
398 let stated = r.read_bits(16)? as u16;
399 let want = crc16(&self.data[start..start + frame_bytes]);
400 if stated != want {
401 return Err(Error::corrupt(format!(
402 "frame at {start}: CRC-16 {stated:#06x}, expected {want:#06x}"
403 )));
404 }
405 undecorrelate(header.channels, &mut block.channels)?;
406 block.header = Some(header);
407 self.pos = start + frame_bytes + 2;
408 Ok(true)
409 }
410
411 /// Decode the whole stream into per-channel planes, verifying the
412 /// `STREAMINFO` MD5 when the stream states one.
413 ///
414 /// Convenience over [`FlacReader::next_block`]: it holds the whole decoded
415 /// stream in memory, which is what a fixture test and a waveform pass want
416 /// and what a player does not.
417 pub fn decode_all(&mut self) -> Result<DecodedStream> {
418 let mut block = Block::default();
419 let mut out: Vec<Vec<i32>> = Vec::new();
420 let mut header: Option<FrameHeader> = None;
421 while self.next_block(&mut block)? {
422 let h = block.header.expect("a decoded block has a header");
423 match header {
424 None => {
425 out.resize_with(block.channels.len(), Vec::new);
426 header = Some(h);
427 }
428 Some(prev)
429 if prev.bits_per_sample != h.bits_per_sample
430 || prev.sample_rate != h.sample_rate
431 || prev.channels.channel_count() != h.channels.channel_count() =>
432 {
433 return Err(Error::unsupported(
434 "FLAC stream changing format mid-stream",
435 format!(
436 "{}ch/{}bit/{}Hz became {}ch/{}bit/{}Hz",
437 prev.channels.channel_count(),
438 prev.bits_per_sample,
439 prev.sample_rate,
440 h.channels.channel_count(),
441 h.bits_per_sample,
442 h.sample_rate
443 ),
444 ));
445 }
446 Some(_) => {}
447 }
448 for (dst, src) in out.iter_mut().zip(&block.channels) {
449 dst.extend_from_slice(src);
450 }
451 }
452 let header = header.ok_or(Error::Eof)?;
453 Ok(DecodedStream {
454 bits_per_sample: header.bits_per_sample,
455 sample_rate: header.sample_rate,
456 channels: out,
457 })
458 }
459}
460
461/// The result of [`FlacReader::decode_all`].
462#[derive(Debug, Clone)]
463pub struct DecodedStream {
464 /// Bit depth of the samples.
465 pub bits_per_sample: u32,
466 /// Sample rate in Hz.
467 pub sample_rate: u32,
468 /// One plane per channel, samples at the stream's own bit depth.
469 pub channels: Vec<Vec<i32>>,
470}
471
472impl DecodedStream {
473 /// Samples per channel.
474 pub fn len(&self) -> usize {
475 self.channels.first().map_or(0, Vec::len)
476 }
477
478 /// True when nothing decoded.
479 pub fn is_empty(&self) -> bool {
480 self.len() == 0
481 }
482
483 /// Interleaved samples at the stream's own bit depth.
484 pub fn interleaved(&self) -> Vec<i32> {
485 let channels = self.channels.len();
486 let mut out = vec![0i32; self.len() * channels];
487 for (c, plane) in self.channels.iter().enumerate() {
488 for (i, &s) in plane.iter().enumerate() {
489 out[i * channels + c] = s;
490 }
491 }
492 out
493 }
494
495 /// Interleaved samples shifted into their PCM container, as raw bytes:
496 /// `s16le` for depths up to 16 bits, `s32le` above. This is exactly what
497 /// `the oracle -f s16le/-f s32le` writes for the same file.
498 pub fn to_pcm_bytes(&self) -> Vec<u8> {
499 let shift = container_shift(self.bits_per_sample);
500 let narrow = self.bits_per_sample <= 16;
501 let mut out = Vec::with_capacity(self.len() * self.channels.len() * 4);
502 for i in 0..self.len() {
503 for plane in &self.channels {
504 let v = plane[i] << shift;
505 match narrow {
506 true => out.extend_from_slice(&(v as i16).to_le_bytes()),
507 false => out.extend_from_slice(&v.to_le_bytes()),
508 }
509 }
510 }
511 out
512 }
513}
514
515/// Byte offset of the next plausible frame sync at or after `from`.
516///
517/// "Plausible" is: the 14-bit sync code, a zero reserved bit, and a header that
518/// both parses and matches its own CRC-8. That is what makes resynchronisation
519/// after damage, and opening a buffer that starts mid-stream, safe.
520pub fn find_frame_sync(data: &[u8], from: usize, info: Option<&StreamInfo>) -> Option<usize> {
521 let mut at = from;
522 while at + 2 <= data.len() {
523 if data[at] == 0xff && data[at + 1] & 0xfe == 0xf8 {
524 let mut r = BitReader::new(&data[at..]);
525 if let Ok(_header) = parse_frame_header(&mut r, info) {
526 let n = (r.bit_position() / 8) as usize;
527 if at + n <= data.len() && crc8(&data[at..at + n - 1]) == data[at + n - 1] {
528 return Some(at);
529 }
530 }
531 }
532 at += 1;
533 }
534 None
535}
536
537pub fn next_frame_start(data: &[u8], from: usize, info: Option<&StreamInfo>) -> Option<usize> {
538 let mut at = from;
539 let mut first = None;
540 while let Some(c) = find_frame_sync(data, at, info) {
541 first.get_or_insert(c);
542 if c >= 2 && crc16(&data[..c - 2]) == u16::from_be_bytes([data[c - 2], data[c - 1]]) {
543 return Some(c);
544 }
545 at = c + 1;
546 }
547 first
548}
549
550/// Parse a frame header, resolving the "same as `STREAMINFO`" codes.
551pub fn parse_frame_header(r: &mut BitReader<'_>, info: Option<&StreamInfo>) -> Result<FrameHeader> {
552 if r.read_bits(14)? != 0x3ffe {
553 return Err(Error::corrupt("frame header: bad sync code"));
554 }
555 if r.read_bit()? {
556 return Err(Error::corrupt("frame header: reserved bit set"));
557 }
558 let variable_block_size = r.read_bit()?;
559 let block_size_code = r.read_bits(4)?;
560 let sample_rate_code = r.read_bits(4)?;
561 let channel_code = r.read_bits(4)?;
562 let bps_code = r.read_bits(3)?;
563 if r.read_bit()? {
564 return Err(Error::corrupt("frame header: second reserved bit set"));
565 }
566
567 let number = read_utf8_number(r, if variable_block_size { 36 } else { 31 })?;
568
569 let block_size = match block_size_code {
570 0 => return Err(Error::corrupt("frame header: block size code 0")),
571 1 => 192,
572 2..=5 => 576 << (block_size_code - 2),
573 6 => r.read_bits(8)? as usize + 1,
574 7 => r.read_bits(16)? as usize + 1,
575 _ => 256 << (block_size_code - 8),
576 };
577 let sample_rate = match sample_rate_code {
578 0 => info
579 .map(|i| i.sample_rate)
580 .ok_or_else(|| Error::corrupt("frame header: rate from a missing STREAMINFO"))?,
581 1 => 88200,
582 2 => 176_400,
583 3 => 192_000,
584 4 => 8000,
585 5 => 16000,
586 6 => 22050,
587 7 => 24000,
588 8 => 32000,
589 9 => 44100,
590 10 => 48000,
591 11 => 96000,
592 12 => r.read_bits(8)? * 1000,
593 13 => r.read_bits(16)?,
594 14 => r.read_bits(16)? * 10,
595 _ => return Err(Error::corrupt("frame header: sample rate code 15")),
596 };
597 let channels = match channel_code {
598 0..=7 => ChannelAssignment::Independent(channel_code as u8 + 1),
599 8 => ChannelAssignment::LeftSide,
600 9 => ChannelAssignment::RightSide,
601 10 => ChannelAssignment::MidSide,
602 _ => {
603 return Err(Error::corrupt(format!(
604 "frame header: channel assignment {channel_code}"
605 )));
606 }
607 };
608 let bits_per_sample = match bps_code {
609 0 => info
610 .map(|i| u32::from(i.bits_per_sample))
611 .ok_or_else(|| Error::corrupt("frame header: depth from a missing STREAMINFO"))?,
612 1 => 8,
613 2 => 12,
614 3 => return Err(Error::corrupt("frame header: bit depth code 3 is reserved")),
615 4 => 16,
616 5 => 20,
617 6 => 24,
618 _ => 32,
619 };
620 // The CRC-8 byte closes the header; callers check it against the bytes they
621 // hold, so it is only skipped here.
622 r.skip_bits(8)?;
623 Ok(FrameHeader {
624 block_size,
625 sample_rate,
626 channels,
627 bits_per_sample,
628 number,
629 variable_block_size,
630 })
631}
632
633/// The UTF-8-shaped coded number of a frame header (up to 36 bits, so wider
634/// than real UTF-8).
635pub(crate) fn read_utf8_number(r: &mut BitReader<'_>, max_bits: u32) -> Result<u64> {
636 let first = r.read_bits(8)?;
637 let extra = match first {
638 0x00..=0x7f => 0,
639 0xc0..=0xdf => 1,
640 0xe0..=0xef => 2,
641 0xf0..=0xf7 => 3,
642 0xf8..=0xfb => 4,
643 0xfc..=0xfd => 5,
644 0xfe => 6,
645 _ => return Err(Error::corrupt("frame header: bad coded-number prefix")),
646 };
647 // The lead byte carries `6 - extra` payload bits after its prefix.
648 let mut value = match extra {
649 0 => u64::from(first),
650 _ => u64::from(first & ((1u32 << (6 - extra)) - 1)),
651 };
652 for _ in 0..extra {
653 let byte = r.read_bits(8)?;
654 if byte & 0xc0 != 0x80 {
655 return Err(Error::corrupt(
656 "frame header: bad coded-number continuation",
657 ));
658 }
659 value = (value << 6) | u64::from(byte & 0x3f);
660 }
661 if max_bits < 64 && value >> max_bits != 0 {
662 return Err(Error::corrupt(format!(
663 "frame header: coded number {value} exceeds {max_bits} bits"
664 )));
665 }
666 Ok(value)
667}
668
669fn decode_subframe(
670 r: &mut BitReader<'_>,
671 bps: u32,
672 block_size: usize,
673 out: &mut Vec<i32>,
674 residual: &mut Vec<i32>,
675) -> Result<()> {
676 if r.read_bit()? {
677 return Err(Error::corrupt("subframe: padding bit set"));
678 }
679 let kind = r.read_bits(6)?;
680 let mut wasted = 0u32;
681 if r.read_bit()? {
682 wasted = 1;
683 while !r.read_bit()? {
684 wasted += 1;
685 if wasted >= bps {
686 break;
687 }
688 }
689 }
690 if wasted >= bps {
691 return Err(Error::corrupt(format!(
692 "subframe: {wasted} wasted bits of {bps}"
693 )));
694 }
695 let bps = bps - wasted;
696 if bps > 32 {
697 // Only a 32-bit stream that also decorrelates its stereo pair gets
698 // here: its side channel needs 33 bits, which does not fit the i32
699 // sample planes this decoder (and the oracle's, and the reference encoder's encoder)
700 // works in. Named rather than mangled.
701 return Err(Error::unsupported(
702 "33-bit side subframe",
703 "32-bit stereo decorrelation needs 33-bit sample planes",
704 ));
705 }
706
707 out.clear();
708 out.reserve(block_size);
709 match kind {
710 0 => {
711 let value = r.read_signed(bps)?;
712 out.resize(block_size, value);
713 }
714 1 => {
715 for _ in 0..block_size {
716 out.push(r.read_signed(bps)?);
717 }
718 }
719 8..=12 => decode_fixed(r, (kind - 8) as usize, bps, block_size, out, residual)?,
720 32..=63 => decode_lpc(r, (kind - 31) as usize, bps, block_size, out, residual)?,
721 _ => {
722 return Err(Error::corrupt(format!("subframe: type {kind} is reserved")));
723 }
724 }
725 if wasted > 0 {
726 for s in out.iter_mut() {
727 *s <<= wasted;
728 }
729 }
730 Ok(())
731}
732
733fn decode_fixed(
734 r: &mut BitReader<'_>,
735 order: usize,
736 bps: u32,
737 block_size: usize,
738 out: &mut Vec<i32>,
739 residual: &mut Vec<i32>,
740) -> Result<()> {
741 if order > block_size {
742 return Err(Error::corrupt(format!(
743 "fixed subframe: order {order} over a {block_size}-sample block"
744 )));
745 }
746 for _ in 0..order {
747 out.push(r.read_signed(bps)?);
748 }
749 decode_residual(r, block_size, order, residual)?;
750 for (i, &res) in residual.iter().enumerate() {
751 let n = order + i;
752 let p = &out[n - order..n];
753 // Fixed predictors are the first four differences of the signal.
754 let predicted: i64 = match order {
755 0 => 0,
756 1 => i64::from(p[0]),
757 2 => 2 * i64::from(p[1]) - i64::from(p[0]),
758 3 => 3 * i64::from(p[2]) - 3 * i64::from(p[1]) + i64::from(p[0]),
759 _ => 4 * i64::from(p[3]) - 6 * i64::from(p[2]) + 4 * i64::from(p[1]) - i64::from(p[0]),
760 };
761 out.push((predicted as i32).wrapping_add(res));
762 }
763 Ok(())
764}
765
766fn decode_lpc(
767 r: &mut BitReader<'_>,
768 order: usize,
769 bps: u32,
770 block_size: usize,
771 out: &mut Vec<i32>,
772 residual: &mut Vec<i32>,
773) -> Result<()> {
774 if order > block_size {
775 return Err(Error::corrupt(format!(
776 "LPC subframe: order {order} over a {block_size}-sample block"
777 )));
778 }
779 for _ in 0..order {
780 out.push(r.read_signed(bps)?);
781 }
782 let precision = r.read_bits(4)? + 1;
783 if precision == 16 {
784 return Err(Error::corrupt("LPC subframe: coefficient precision 15+1"));
785 }
786 let shift = r.read_signed(5)?;
787 if shift < 0 {
788 return Err(Error::corrupt(format!(
789 "LPC subframe: negative shift {shift}"
790 )));
791 }
792 let mut coefs = [0i64; 32];
793 for c in coefs.iter_mut().take(order) {
794 *c = i64::from(r.read_signed(precision)?);
795 }
796 decode_residual(r, block_size, order, residual)?;
797 let coefs = &coefs[..order];
798 for (i, &res) in residual.iter().enumerate() {
799 let n = order + i;
800 let history = &out[n - order..n];
801 // 64-bit accumulation: 32-bit samples with 15-bit coefficients at order
802 // 32 need 52 bits, and the "predictor overflow" streams exist to catch
803 // a decoder that accumulates narrower.
804 let mut sum = 0i64;
805 for (c, &s) in coefs.iter().zip(history.iter().rev()) {
806 sum += c * i64::from(s);
807 }
808 out.push(((sum >> shift) as i32).wrapping_add(res));
809 }
810 Ok(())
811}
812
813fn decode_residual(
814 r: &mut BitReader<'_>,
815 block_size: usize,
816 order: usize,
817 out: &mut Vec<i32>,
818) -> Result<()> {
819 let method = r.read_bits(2)?;
820 let param_bits = match method {
821 0 => 4,
822 1 => 5,
823 _ => {
824 return Err(Error::corrupt(format!(
825 "residual: coding method {method} is reserved"
826 )));
827 }
828 };
829 let escape = (1u32 << param_bits) - 1;
830 let partition_order = r.read_bits(4)?;
831 let partitions = 1usize << partition_order;
832 if !block_size.is_multiple_of(partitions) {
833 return Err(Error::corrupt(format!(
834 "residual: {partitions} partitions over a {block_size}-sample block"
835 )));
836 }
837 let partition_len = block_size / partitions;
838 if partition_len < order {
839 return Err(Error::corrupt(format!(
840 "residual: order {order} over {partition_len}-sample partitions"
841 )));
842 }
843 out.clear();
844 out.reserve(block_size - order);
845 for p in 0..partitions {
846 let count = partition_len - if p == 0 { order } else { 0 };
847 let param = r.read_bits(param_bits)?;
848 if param == escape {
849 let raw = r.read_bits(5)?;
850 for _ in 0..count {
851 out.push(match raw {
852 0 => 0,
853 n => r.read_signed(n)?,
854 });
855 }
856 } else {
857 for _ in 0..count {
858 out.push(read_rice(r, param)?);
859 }
860 }
861 }
862 Ok(())
863}
864
865/// One Rice-coded, zig-zag folded residual.
866fn read_rice(r: &mut BitReader<'_>, param: u32) -> Result<i32> {
867 let mut quotient = 0u32;
868 while !r.read_bit()? {
869 quotient += 1;
870 // A quotient wider than the sample container is damage, not data; the
871 // cap is what keeps a fuzzed stream from spinning to the end of the
872 // buffer one bit at a time.
873 if quotient > 1 << 20 {
874 return Err(Error::corrupt("residual: Rice quotient over 2^20"));
875 }
876 }
877 let folded = match param {
878 0 => quotient,
879 n => (quotient << n) | r.read_bits(n)?,
880 };
881 Ok(((folded >> 1) as i32) ^ -((folded & 1) as i32))
882}
883
884fn undecorrelate(assignment: ChannelAssignment, channels: &mut [Vec<i32>]) -> Result<()> {
885 if matches!(assignment, ChannelAssignment::Independent(_)) {
886 return Ok(());
887 }
888 let (a, b) = channels.split_at_mut(1);
889 let (a, b) = (&mut a[0], &mut b[0]);
890 if a.len() != b.len() {
891 return Err(Error::corrupt("stereo decorrelation over unequal channels"));
892 }
893 match assignment {
894 ChannelAssignment::LeftSide => {
895 // a = left, b = left - right.
896 for (l, s) in a.iter().zip(b.iter_mut()) {
897 *s = l.wrapping_sub(*s);
898 }
899 }
900 ChannelAssignment::RightSide => {
901 // a = left - right, b = right.
902 for (s, r) in a.iter_mut().zip(b.iter()) {
903 *s = s.wrapping_add(*r);
904 }
905 }
906 ChannelAssignment::MidSide => {
907 for (m, s) in a.iter_mut().zip(b.iter_mut()) {
908 // The low bit of the difference is carried in the mid channel.
909 let mid = (*m << 1) | (*s & 1);
910 let side = *s;
911 *m = mid.wrapping_add(side) >> 1;
912 *s = mid.wrapping_sub(side) >> 1;
913 }
914 }
915 ChannelAssignment::Independent(_) => unreachable!("returned above"),
916 }
917 Ok(())
918}
919
920#[cfg(test)]
921mod tests {
922 use super::*;
923
924 #[test]
925 fn stream_info_round_trips() {
926 let info = StreamInfo {
927 min_block_size: 4096,
928 max_block_size: 4096,
929 min_frame_size: 14,
930 max_frame_size: 16384,
931 sample_rate: 44100,
932 channels: 2,
933 bits_per_sample: 16,
934 total_samples: 1_234_567,
935 md5: [7; 16],
936 };
937 assert_eq!(StreamInfo::parse(&info.to_bytes()).unwrap(), info);
938 }
939
940 #[test]
941 fn truncated_input_is_need_more_not_a_panic() {
942 let info = StreamInfo {
943 min_block_size: 16,
944 max_block_size: 16,
945 min_frame_size: 0,
946 max_frame_size: 0,
947 sample_rate: 8000,
948 channels: 1,
949 bits_per_sample: 8,
950 total_samples: 0,
951 md5: [0; 16],
952 };
953 let bytes = info.to_bytes();
954 for n in 0..34 {
955 assert!(StreamInfo::parse(&bytes[..n]).unwrap_err().is_need_more());
956 }
957 }
958
959 #[test]
960 fn garbage_never_panics_and_never_opens() {
961 for seed in 0..64u32 {
962 let junk: Vec<u8> = (0..512).map(|i| (i * 37 + seed * 11) as u8).collect();
963 let _ = FlacReader::new(&junk).map(|mut r| {
964 let mut b = Block::default();
965 let _ = r.next_block(&mut b);
966 });
967 }
968 }
969
970 #[test]
971 fn mid_side_inverts_the_encoder_transform() {
972 let left: Vec<i32> = (-8..8).collect();
973 let right: Vec<i32> = (0..16).map(|i| i * 3 - 20).collect();
974 let mid: Vec<i32> = left.iter().zip(&right).map(|(l, r)| (l + r) >> 1).collect();
975 let side: Vec<i32> = left.iter().zip(&right).map(|(l, r)| l - r).collect();
976 let mut planes = vec![mid, side];
977 undecorrelate(ChannelAssignment::MidSide, &mut planes).unwrap();
978 assert_eq!(planes[0], left);
979 assert_eq!(planes[1], right);
980 }
981
982 #[test]
983 fn container_shift_matches_reference_layout() {
984 assert_eq!(container_shift(8), 8);
985 assert_eq!(container_shift(12), 4);
986 assert_eq!(container_shift(16), 0);
987 assert_eq!(container_shift(20), 12);
988 assert_eq!(container_shift(24), 8);
989 assert_eq!(container_shift(32), 0);
990 }
991
992 /// Fuzzer find (parse_metadata): a seek-table offset of u64::MAX overflowed
993 /// `first_frame + offset`. It must now be treated as "no such point".
994 #[test]
995 fn seek_table_offset_overflow_does_not_panic() {
996 let info = StreamInfo {
997 min_block_size: 4096,
998 max_block_size: 4096,
999 min_frame_size: 0,
1000 max_frame_size: 0,
1001 sample_rate: 44_100,
1002 channels: 2,
1003 bits_per_sample: 16,
1004 total_samples: 0,
1005 md5: [0; 16],
1006 };
1007 let mut data = MAGIC.to_vec();
1008 data.extend_from_slice(&[0x00, 0x00, 0x00, 34]);
1009 data.extend_from_slice(&info.to_bytes());
1010 // SEEKTABLE, last block: one point at sample 0, offset u64::MAX.
1011 data.extend_from_slice(&[0x83, 0x00, 0x00, 18]);
1012 data.extend_from_slice(&0u64.to_be_bytes());
1013 data.extend_from_slice(&u64::MAX.to_be_bytes());
1014 data.extend_from_slice(&16u16.to_be_bytes());
1015
1016 let mut reader = FlacReader::new(&data).expect("open");
1017 assert_eq!(reader.seek_table().len(), 1);
1018 assert_eq!(reader.seek_to_sample(0), 0);
1019 assert_eq!(reader.position(), reader.first_frame);
1020 }
1021}