forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBe12d32fTahinli6 days ago3982 commits

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