forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiB6c331afTahinli11 hours ago4261 commits

decode.rs1024 lines, 34.9 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 + 1;
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.ok_or(Error::NeedMore)?;
423 match header {
424 None => {
425 out.resize_with(block.channels.len(), Vec::new);
426 header = Some(h);
427 }
428 Some(prev) => check_same_format(&prev, &h)?,
429 }
430 for (dst, src) in out.iter_mut().zip(&block.channels) {
431 dst.extend_from_slice(src);
432 }
433 }
434 let header = header.ok_or(Error::Eof)?;
435 Ok(DecodedStream {
436 bits_per_sample: header.bits_per_sample,
437 sample_rate: header.sample_rate,
438 channels: out,
439 })
440 }
441}
442
443pub(crate) fn check_same_format(prev: &FrameHeader, next: &FrameHeader) -> Result<()> {
444 if prev.bits_per_sample == next.bits_per_sample
445 && prev.sample_rate == next.sample_rate
446 && prev.channels.channel_count() == next.channels.channel_count()
447 {
448 return Ok(());
449 }
450 Err(Error::unsupported(
451 "FLAC stream changing format mid-stream",
452 format!(
453 "{}ch/{}bit/{}Hz became {}ch/{}bit/{}Hz",
454 prev.channels.channel_count(),
455 prev.bits_per_sample,
456 prev.sample_rate,
457 next.channels.channel_count(),
458 next.bits_per_sample,
459 next.sample_rate
460 ),
461 ))
462}
463
464/// The result of [`FlacReader::decode_all`].
465#[derive(Debug, Clone)]
466pub struct DecodedStream {
467 /// Bit depth of the samples.
468 pub bits_per_sample: u32,
469 /// Sample rate in Hz.
470 pub sample_rate: u32,
471 /// One plane per channel, samples at the stream's own bit depth.
472 pub channels: Vec<Vec<i32>>,
473}
474
475impl DecodedStream {
476 /// Samples per channel.
477 pub fn len(&self) -> usize {
478 self.channels.first().map_or(0, Vec::len)
479 }
480
481 /// True when nothing decoded.
482 pub fn is_empty(&self) -> bool {
483 self.len() == 0
484 }
485
486 /// Interleaved samples at the stream's own bit depth.
487 pub fn interleaved(&self) -> Vec<i32> {
488 let channels = self.channels.len();
489 let mut out = vec![0i32; self.len() * channels];
490 for (c, plane) in self.channels.iter().enumerate() {
491 for (i, &s) in plane.iter().enumerate() {
492 out[i * channels + c] = s;
493 }
494 }
495 out
496 }
497
498 /// Interleaved samples shifted into their PCM container, as raw bytes:
499 /// `s16le` for depths up to 16 bits, `s32le` above. This is exactly what
500 /// `the oracle -f s16le/-f s32le` writes for the same file.
501 pub fn to_pcm_bytes(&self) -> Vec<u8> {
502 let shift = container_shift(self.bits_per_sample);
503 let narrow = self.bits_per_sample <= 16;
504 let mut out = Vec::with_capacity(self.len() * self.channels.len() * 4);
505 for i in 0..self.len() {
506 for plane in &self.channels {
507 let v = plane[i] << shift;
508 match narrow {
509 true => out.extend_from_slice(&(v as i16).to_le_bytes()),
510 false => out.extend_from_slice(&v.to_le_bytes()),
511 }
512 }
513 }
514 out
515 }
516}
517
518/// Byte offset of the next plausible frame sync at or after `from`.
519///
520/// "Plausible" is: the 14-bit sync code, a zero reserved bit, and a header that
521/// both parses and matches its own CRC-8. That is what makes resynchronisation
522/// after damage, and opening a buffer that starts mid-stream, safe.
523pub fn find_frame_sync(data: &[u8], from: usize, info: Option<&StreamInfo>) -> Option<usize> {
524 let mut at = from;
525 while at + 2 <= data.len() {
526 if data[at] == 0xff && data[at + 1] & 0xfe == 0xf8 {
527 let mut r = BitReader::new(&data[at..]);
528 if let Ok(_header) = parse_frame_header(&mut r, info) {
529 let n = (r.bit_position() / 8) as usize;
530 if at + n <= data.len() && crc8(&data[at..at + n - 1]) == data[at + n - 1] {
531 return Some(at);
532 }
533 }
534 }
535 at += 1;
536 }
537 None
538}
539
540pub fn next_frame_start(data: &[u8], from: usize, info: Option<&StreamInfo>) -> Option<usize> {
541 let mut at = from;
542 let mut first = None;
543 while let Some(c) = find_frame_sync(data, at, info) {
544 first.get_or_insert(c);
545 if c >= 2 && crc16(&data[..c - 2]) == u16::from_be_bytes([data[c - 2], data[c - 1]]) {
546 return Some(c);
547 }
548 at = c + 1;
549 }
550 first
551}
552
553/// Parse a frame header, resolving the "same as `STREAMINFO`" codes.
554pub fn parse_frame_header(r: &mut BitReader<'_>, info: Option<&StreamInfo>) -> Result<FrameHeader> {
555 if r.read_bits(14)? != 0x3ffe {
556 return Err(Error::corrupt("frame header: bad sync code"));
557 }
558 if r.read_bit()? {
559 return Err(Error::corrupt("frame header: reserved bit set"));
560 }
561 let variable_block_size = r.read_bit()?;
562 let block_size_code = r.read_bits(4)?;
563 let sample_rate_code = r.read_bits(4)?;
564 let channel_code = r.read_bits(4)?;
565 let bps_code = r.read_bits(3)?;
566 if r.read_bit()? {
567 return Err(Error::corrupt("frame header: second reserved bit set"));
568 }
569
570 let number = read_utf8_number(r, if variable_block_size { 36 } else { 31 })?;
571
572 let block_size = match block_size_code {
573 0 => return Err(Error::corrupt("frame header: block size code 0")),
574 1 => 192,
575 2..=5 => 576 << (block_size_code - 2),
576 6 => r.read_bits(8)? as usize + 1,
577 7 => r.read_bits(16)? as usize + 1,
578 _ => 256 << (block_size_code - 8),
579 };
580 let sample_rate = match sample_rate_code {
581 0 => info
582 .map(|i| i.sample_rate)
583 .ok_or_else(|| Error::corrupt("frame header: rate from a missing STREAMINFO"))?,
584 1 => 88200,
585 2 => 176_400,
586 3 => 192_000,
587 4 => 8000,
588 5 => 16000,
589 6 => 22050,
590 7 => 24000,
591 8 => 32000,
592 9 => 44100,
593 10 => 48000,
594 11 => 96000,
595 12 => r.read_bits(8)? * 1000,
596 13 => r.read_bits(16)?,
597 14 => r.read_bits(16)? * 10,
598 _ => return Err(Error::corrupt("frame header: sample rate code 15")),
599 };
600 let channels = match channel_code {
601 0..=7 => ChannelAssignment::Independent(channel_code as u8 + 1),
602 8 => ChannelAssignment::LeftSide,
603 9 => ChannelAssignment::RightSide,
604 10 => ChannelAssignment::MidSide,
605 _ => {
606 return Err(Error::corrupt(format!(
607 "frame header: channel assignment {channel_code}"
608 )));
609 }
610 };
611 let bits_per_sample = match bps_code {
612 0 => info
613 .map(|i| u32::from(i.bits_per_sample))
614 .ok_or_else(|| Error::corrupt("frame header: depth from a missing STREAMINFO"))?,
615 1 => 8,
616 2 => 12,
617 3 => return Err(Error::corrupt("frame header: bit depth code 3 is reserved")),
618 4 => 16,
619 5 => 20,
620 6 => 24,
621 _ => 32,
622 };
623 // The CRC-8 byte closes the header; callers check it against the bytes they
624 // hold, so it is only skipped here.
625 r.skip_bits(8)?;
626 Ok(FrameHeader {
627 block_size,
628 sample_rate,
629 channels,
630 bits_per_sample,
631 number,
632 variable_block_size,
633 })
634}
635
636/// The UTF-8-shaped coded number of a frame header (up to 36 bits, so wider
637/// than real UTF-8).
638pub(crate) fn read_utf8_number(r: &mut BitReader<'_>, max_bits: u32) -> Result<u64> {
639 let first = r.read_bits(8)?;
640 let extra = match first {
641 0x00..=0x7f => 0,
642 0xc0..=0xdf => 1,
643 0xe0..=0xef => 2,
644 0xf0..=0xf7 => 3,
645 0xf8..=0xfb => 4,
646 0xfc..=0xfd => 5,
647 0xfe => 6,
648 _ => return Err(Error::corrupt("frame header: bad coded-number prefix")),
649 };
650 // The lead byte carries `6 - extra` payload bits after its prefix.
651 let mut value = match extra {
652 0 => u64::from(first),
653 _ => u64::from(first & ((1u32 << (6 - extra)) - 1)),
654 };
655 for _ in 0..extra {
656 let byte = r.read_bits(8)?;
657 if byte & 0xc0 != 0x80 {
658 return Err(Error::corrupt(
659 "frame header: bad coded-number continuation",
660 ));
661 }
662 value = (value << 6) | u64::from(byte & 0x3f);
663 }
664 if max_bits < 64 && value >> max_bits != 0 {
665 return Err(Error::corrupt(format!(
666 "frame header: coded number {value} exceeds {max_bits} bits"
667 )));
668 }
669 Ok(value)
670}
671
672fn decode_subframe(
673 r: &mut BitReader<'_>,
674 bps: u32,
675 block_size: usize,
676 out: &mut Vec<i32>,
677 residual: &mut Vec<i32>,
678) -> Result<()> {
679 if r.read_bit()? {
680 return Err(Error::corrupt("subframe: padding bit set"));
681 }
682 let kind = r.read_bits(6)?;
683 let mut wasted = 0u32;
684 if r.read_bit()? {
685 wasted = 1;
686 while !r.read_bit()? {
687 wasted += 1;
688 if wasted >= bps {
689 break;
690 }
691 }
692 }
693 if wasted >= bps {
694 return Err(Error::corrupt(format!(
695 "subframe: {wasted} wasted bits of {bps}"
696 )));
697 }
698 let bps = bps - wasted;
699 if bps > 32 {
700 // Only a 32-bit stream that also decorrelates its stereo pair gets
701 // here: its side channel needs 33 bits, which does not fit the i32
702 // sample planes this decoder (and the oracle's, and the reference encoder's encoder)
703 // works in. Named rather than mangled.
704 return Err(Error::unsupported(
705 "33-bit side subframe",
706 "32-bit stereo decorrelation needs 33-bit sample planes",
707 ));
708 }
709
710 out.clear();
711 out.reserve(block_size);
712 match kind {
713 0 => {
714 let value = r.read_signed(bps)?;
715 out.resize(block_size, value);
716 }
717 1 => {
718 for _ in 0..block_size {
719 out.push(r.read_signed(bps)?);
720 }
721 }
722 8..=12 => decode_fixed(r, (kind - 8) as usize, bps, block_size, out, residual)?,
723 32..=63 => decode_lpc(r, (kind - 31) as usize, bps, block_size, out, residual)?,
724 _ => {
725 return Err(Error::corrupt(format!("subframe: type {kind} is reserved")));
726 }
727 }
728 if wasted > 0 {
729 for s in out.iter_mut() {
730 *s <<= wasted;
731 }
732 }
733 Ok(())
734}
735
736fn decode_fixed(
737 r: &mut BitReader<'_>,
738 order: usize,
739 bps: u32,
740 block_size: usize,
741 out: &mut Vec<i32>,
742 residual: &mut Vec<i32>,
743) -> Result<()> {
744 if order > block_size {
745 return Err(Error::corrupt(format!(
746 "fixed subframe: order {order} over a {block_size}-sample block"
747 )));
748 }
749 for _ in 0..order {
750 out.push(r.read_signed(bps)?);
751 }
752 decode_residual(r, block_size, order, residual)?;
753 for (i, &res) in residual.iter().enumerate() {
754 let n = order + i;
755 let p = &out[n - order..n];
756 // Fixed predictors are the first four differences of the signal.
757 let predicted: i64 = match order {
758 0 => 0,
759 1 => i64::from(p[0]),
760 2 => 2 * i64::from(p[1]) - i64::from(p[0]),
761 3 => 3 * i64::from(p[2]) - 3 * i64::from(p[1]) + i64::from(p[0]),
762 _ => 4 * i64::from(p[3]) - 6 * i64::from(p[2]) + 4 * i64::from(p[1]) - i64::from(p[0]),
763 };
764 out.push((predicted as i32).wrapping_add(res));
765 }
766 Ok(())
767}
768
769fn decode_lpc(
770 r: &mut BitReader<'_>,
771 order: usize,
772 bps: u32,
773 block_size: usize,
774 out: &mut Vec<i32>,
775 residual: &mut Vec<i32>,
776) -> Result<()> {
777 if order > block_size {
778 return Err(Error::corrupt(format!(
779 "LPC subframe: order {order} over a {block_size}-sample block"
780 )));
781 }
782 for _ in 0..order {
783 out.push(r.read_signed(bps)?);
784 }
785 let precision = r.read_bits(4)? + 1;
786 if precision == 16 {
787 return Err(Error::corrupt("LPC subframe: coefficient precision 15+1"));
788 }
789 let shift = r.read_signed(5)?;
790 if shift < 0 {
791 return Err(Error::corrupt(format!(
792 "LPC subframe: negative shift {shift}"
793 )));
794 }
795 let mut coefs = [0i64; 32];
796 for c in coefs.iter_mut().take(order) {
797 *c = i64::from(r.read_signed(precision)?);
798 }
799 decode_residual(r, block_size, order, residual)?;
800 let coefs = &coefs[..order];
801 for (i, &res) in residual.iter().enumerate() {
802 let n = order + i;
803 let history = &out[n - order..n];
804 // 64-bit accumulation: 32-bit samples with 15-bit coefficients at order
805 // 32 need 52 bits, and the "predictor overflow" streams exist to catch
806 // a decoder that accumulates narrower.
807 let mut sum = 0i64;
808 for (c, &s) in coefs.iter().zip(history.iter().rev()) {
809 sum += c * i64::from(s);
810 }
811 out.push(((sum >> shift) as i32).wrapping_add(res));
812 }
813 Ok(())
814}
815
816fn decode_residual(
817 r: &mut BitReader<'_>,
818 block_size: usize,
819 order: usize,
820 out: &mut Vec<i32>,
821) -> Result<()> {
822 let method = r.read_bits(2)?;
823 let param_bits = match method {
824 0 => 4,
825 1 => 5,
826 _ => {
827 return Err(Error::corrupt(format!(
828 "residual: coding method {method} is reserved"
829 )));
830 }
831 };
832 let escape = (1u32 << param_bits) - 1;
833 let partition_order = r.read_bits(4)?;
834 let partitions = 1usize << partition_order;
835 if !block_size.is_multiple_of(partitions) {
836 return Err(Error::corrupt(format!(
837 "residual: {partitions} partitions over a {block_size}-sample block"
838 )));
839 }
840 let partition_len = block_size / partitions;
841 if partition_len < order {
842 return Err(Error::corrupt(format!(
843 "residual: order {order} over {partition_len}-sample partitions"
844 )));
845 }
846 out.clear();
847 out.reserve(block_size - order);
848 for p in 0..partitions {
849 let count = partition_len - if p == 0 { order } else { 0 };
850 let param = r.read_bits(param_bits)?;
851 if param == escape {
852 let raw = r.read_bits(5)?;
853 for _ in 0..count {
854 out.push(match raw {
855 0 => 0,
856 n => r.read_signed(n)?,
857 });
858 }
859 } else {
860 for _ in 0..count {
861 out.push(read_rice(r, param)?);
862 }
863 }
864 }
865 Ok(())
866}
867
868/// One Rice-coded, zig-zag folded residual.
869fn read_rice(r: &mut BitReader<'_>, param: u32) -> Result<i32> {
870 let mut quotient = 0u32;
871 while !r.read_bit()? {
872 quotient += 1;
873 // A quotient wider than the sample container is damage, not data; the
874 // cap is what keeps a fuzzed stream from spinning to the end of the
875 // buffer one bit at a time.
876 if quotient > 1 << 20 {
877 return Err(Error::corrupt("residual: Rice quotient over 2^20"));
878 }
879 }
880 let folded = match param {
881 0 => quotient,
882 n => (quotient << n) | r.read_bits(n)?,
883 };
884 Ok(((folded >> 1) as i32) ^ -((folded & 1) as i32))
885}
886
887fn undecorrelate(assignment: ChannelAssignment, channels: &mut [Vec<i32>]) -> Result<()> {
888 if matches!(assignment, ChannelAssignment::Independent(_)) {
889 return Ok(());
890 }
891 let (a, b) = channels.split_at_mut(1);
892 let (a, b) = (&mut a[0], &mut b[0]);
893 if a.len() != b.len() {
894 return Err(Error::corrupt("stereo decorrelation over unequal channels"));
895 }
896 match assignment {
897 ChannelAssignment::LeftSide => {
898 // a = left, b = left - right.
899 for (l, s) in a.iter().zip(b.iter_mut()) {
900 *s = l.wrapping_sub(*s);
901 }
902 }
903 ChannelAssignment::RightSide => {
904 // a = left - right, b = right.
905 for (s, r) in a.iter_mut().zip(b.iter()) {
906 *s = s.wrapping_add(*r);
907 }
908 }
909 ChannelAssignment::MidSide => {
910 for (m, s) in a.iter_mut().zip(b.iter_mut()) {
911 // The low bit of the difference is carried in the mid channel.
912 let mid = (*m << 1) | (*s & 1);
913 let side = *s;
914 *m = mid.wrapping_add(side) >> 1;
915 *s = mid.wrapping_sub(side) >> 1;
916 }
917 }
918 ChannelAssignment::Independent(_) => unreachable!("returned above"),
919 }
920 Ok(())
921}
922
923#[cfg(test)]
924mod tests {
925 use super::*;
926
927 #[test]
928 fn stream_info_round_trips() {
929 let info = StreamInfo {
930 min_block_size: 4096,
931 max_block_size: 4096,
932 min_frame_size: 14,
933 max_frame_size: 16384,
934 sample_rate: 44100,
935 channels: 2,
936 bits_per_sample: 16,
937 total_samples: 1_234_567,
938 md5: [7; 16],
939 };
940 assert_eq!(StreamInfo::parse(&info.to_bytes()).unwrap(), info);
941 }
942
943 #[test]
944 fn truncated_input_is_need_more_not_a_panic() {
945 let info = StreamInfo {
946 min_block_size: 16,
947 max_block_size: 16,
948 min_frame_size: 0,
949 max_frame_size: 0,
950 sample_rate: 8000,
951 channels: 1,
952 bits_per_sample: 8,
953 total_samples: 0,
954 md5: [0; 16],
955 };
956 let bytes = info.to_bytes();
957 for n in 0..34 {
958 assert!(StreamInfo::parse(&bytes[..n]).unwrap_err().is_need_more());
959 }
960 }
961
962 #[test]
963 fn garbage_never_panics_and_never_opens() {
964 for seed in 0..64u32 {
965 let junk: Vec<u8> = (0..512).map(|i| (i * 37 + seed * 11) as u8).collect();
966 let _ = FlacReader::new(&junk).map(|mut r| {
967 let mut b = Block::default();
968 let _ = r.next_block(&mut b);
969 });
970 }
971 }
972
973 #[test]
974 fn mid_side_inverts_the_encoder_transform() {
975 let left: Vec<i32> = (-8..8).collect();
976 let right: Vec<i32> = (0..16).map(|i| i * 3 - 20).collect();
977 let mid: Vec<i32> = left.iter().zip(&right).map(|(l, r)| (l + r) >> 1).collect();
978 let side: Vec<i32> = left.iter().zip(&right).map(|(l, r)| l - r).collect();
979 let mut planes = vec![mid, side];
980 undecorrelate(ChannelAssignment::MidSide, &mut planes).unwrap();
981 assert_eq!(planes[0], left);
982 assert_eq!(planes[1], right);
983 }
984
985 #[test]
986 fn container_shift_matches_reference_layout() {
987 assert_eq!(container_shift(8), 8);
988 assert_eq!(container_shift(12), 4);
989 assert_eq!(container_shift(16), 0);
990 assert_eq!(container_shift(20), 12);
991 assert_eq!(container_shift(24), 8);
992 assert_eq!(container_shift(32), 0);
993 }
994
995 /// Fuzzer find (parse_metadata): a seek-table offset of u64::MAX overflowed
996 /// `first_frame + offset`. It must now be treated as "no such point".
997 #[test]
998 fn seek_table_offset_overflow_does_not_panic() {
999 let info = StreamInfo {
1000 min_block_size: 4096,
1001 max_block_size: 4096,
1002 min_frame_size: 0,
1003 max_frame_size: 0,
1004 sample_rate: 44_100,
1005 channels: 2,
1006 bits_per_sample: 16,
1007 total_samples: 0,
1008 md5: [0; 16],
1009 };
1010 let mut data = MAGIC.to_vec();
1011 data.extend_from_slice(&[0x00, 0x00, 0x00, 34]);
1012 data.extend_from_slice(&info.to_bytes());
1013 // SEEKTABLE, last block: one point at sample 0, offset u64::MAX.
1014 data.extend_from_slice(&[0x83, 0x00, 0x00, 18]);
1015 data.extend_from_slice(&0u64.to_be_bytes());
1016 data.extend_from_slice(&u64::MAX.to_be_bytes());
1017 data.extend_from_slice(&16u16.to_be_bytes());
1018
1019 let mut reader = FlacReader::new(&data).expect("open");
1020 assert_eq!(reader.seek_table().len(), 1);
1021 assert_eq!(reader.seek_to_sample(0), 0);
1022 assert_eq!(reader.position(), reader.first_frame);
1023 }
1024}