flac_codec/decode.rs
1// Copyright 2025 Brian Langenberger
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! For decoding FLAC files to PCM samples
10
11use crate::Error;
12use crate::audio::Frame;
13use crate::metadata::{BlockList, ChannelMask, SeekTable};
14use bitstream_io::{BitRead, SignedBitCount};
15use std::collections::VecDeque;
16use std::fs::File;
17use std::io::BufReader;
18use std::num::NonZero;
19use std::path::Path;
20
21pub use crate::metadata::Metadata;
22
23trait SignedInteger:
24 bitstream_io::SignedInteger + Into<i64> + std::ops::AddAssign + std::ops::Neg<Output = Self>
25{
26 fn from_i64(i: i64) -> Self;
27
28 fn from_u32(u: u32) -> Self;
29}
30
31impl SignedInteger for i32 {
32 #[inline(always)]
33 fn from_i64(i: i64) -> i32 {
34 i as i32
35 }
36
37 #[inline(always)]
38 fn from_u32(u: u32) -> i32 {
39 u as i32
40 }
41}
42
43impl SignedInteger for i64 {
44 #[inline(always)]
45 fn from_i64(i: i64) -> i64 {
46 i
47 }
48
49 #[inline(always)]
50 fn from_u32(u: u32) -> i64 {
51 u as i64
52 }
53}
54
55/// A FLAC reader which outputs PCM samples as bytes
56///
57/// # Example
58///
59/// ```
60/// use flac_codec::{
61/// byteorder::LittleEndian,
62/// encode::{FlacByteWriter, Options},
63/// decode::{FlacByteReader, Metadata},
64/// };
65/// use std::io::{Cursor, Read, Seek, Write};
66///
67/// let mut flac = Cursor::new(vec![]); // a FLAC file in memory
68///
69/// let mut writer = FlacByteWriter::endian(
70/// &mut flac, // our wrapped writer
71/// LittleEndian, // .wav-style byte order
72/// Options::default(), // default encoding options
73/// 44100, // sample rate
74/// 16, // bits-per-sample
75/// 1, // channel count
76/// Some(2000), // total bytes
77/// ).unwrap();
78///
79/// // write 1000 samples as 16-bit, signed, little-endian bytes (2000 bytes total)
80/// let written_bytes = (0..1000).map(i16::to_le_bytes).flatten().collect::<Vec<u8>>();
81/// assert!(writer.write_all(&written_bytes).is_ok());
82///
83/// // finalize writing file
84/// assert!(writer.finalize().is_ok());
85///
86/// flac.rewind().unwrap();
87///
88/// // open reader around written FLAC file
89/// let mut reader = FlacByteReader::endian(flac, LittleEndian).unwrap();
90///
91/// // read 2000 bytes
92/// let mut read_bytes = vec![];
93/// assert!(reader.read_to_end(&mut read_bytes).is_ok());
94///
95/// // ensure MD5 sum of signed, little-endian samples matches hash in file
96/// let mut md5 = md5::Context::new();
97/// md5.consume(&read_bytes);
98/// assert_eq!(&md5.compute().0, reader.md5().unwrap());
99///
100/// // ensure input and output matches
101/// assert_eq!(read_bytes, written_bytes);
102/// ```
103#[derive(Clone)]
104pub struct FlacByteReader<R, E> {
105 // the wrapped decoder
106 decoder: Decoder<R>,
107 // decoded byte buffer
108 buf: VecDeque<u8>,
109 // the endianness of the bytes in our byte buffer
110 endianness: std::marker::PhantomData<E>,
111 // offset start of frames, if known
112 frames_start: Option<u64>,
113}
114
115impl<R: std::io::Read, E: crate::byteorder::Endianness> FlacByteReader<R, E> {
116 /// Opens new FLAC reader which wraps the given reader
117 ///
118 /// The reader must be positioned at the start of the
119 /// FLAC stream. If the file has non-FLAC data
120 /// at the beginning (such as ID3v2 tags), one
121 /// should skip such data before initializing a `FlacByteReader`.
122 #[inline]
123 pub fn new(mut reader: R) -> Result<Self, Error> {
124 let blocklist = BlockList::read(reader.by_ref())?;
125
126 Ok(Self {
127 decoder: Decoder::new(reader, blocklist),
128 buf: VecDeque::default(),
129 endianness: std::marker::PhantomData,
130 frames_start: None,
131 })
132 }
133
134 /// Opens new FLAC reader in the given endianness
135 ///
136 /// The reader must be positioned at the start of the
137 /// FLAC stream. If the file has non-FLAC data
138 /// at the beginning (such as ID3v2 tags), one
139 /// should skip such data before initializing a `FlacByteReader`.
140 #[inline]
141 pub fn endian(reader: R, _endian: E) -> Result<Self, Error> {
142 Self::new(reader)
143 }
144
145 /// Returns FLAC metadata blocks
146 #[inline]
147 pub fn metadata(&self) -> &BlockList {
148 self.decoder.metadata()
149 }
150}
151
152impl<R: std::io::Read + std::io::Seek, E: crate::byteorder::Endianness> FlacByteReader<R, E> {
153 /// Opens a new seekable FLAC reader which wraps the given reader
154 ///
155 /// If a stream is both readable and seekable,
156 /// it's vital to use this method to open it if one
157 /// also wishes to seek within the FLAC stream.
158 /// Otherwise, an I/O error will result when attempting to seek.
159 ///
160 /// [`FlacByteReader::open`] calls this method to ensure
161 /// all `File`-based streams are also seekable.
162 ///
163 /// The reader must be positioned at the start of the
164 /// FLAC stream. If the file has non-FLAC data
165 /// at the beginning (such as ID3v2 tags), one
166 /// should skip such data before initializing a `FlacByteReader`.
167 ///
168 /// # Example
169 ///
170 /// ```
171 /// use flac_codec::{
172 /// byteorder::LittleEndian,
173 /// encode::{FlacByteWriter, Options},
174 /// decode::FlacByteReader,
175 /// };
176 /// use std::io::{Cursor, Read, Seek, SeekFrom, Write};
177 ///
178 /// let mut flac = Cursor::new(vec![]); // a FLAC file in memory
179 ///
180 /// let mut writer = FlacByteWriter::endian(
181 /// &mut flac, // our wrapped writer
182 /// LittleEndian, // .wav-style byte order
183 /// Options::default(), // default encoding options
184 /// 44100, // sample rate
185 /// 16, // bits-per-sample
186 /// 1, // channel count
187 /// Some(2000), // total bytes
188 /// ).unwrap();
189 ///
190 /// // write 1000 samples as 16-bit, signed, little-endian bytes (2000 bytes total)
191 /// let written_bytes = (0..1000).map(i16::to_le_bytes).flatten().collect::<Vec<u8>>();
192 /// assert!(writer.write_all(&written_bytes).is_ok());
193 ///
194 /// // finalize writing file
195 /// assert!(writer.finalize().is_ok());
196 ///
197 /// flac.rewind().unwrap();
198 ///
199 /// // open reader around written FLAC file
200 /// let mut reader: FlacByteReader<_, LittleEndian> =
201 /// FlacByteReader::new_seekable(flac).unwrap();
202 ///
203 /// // read 2000 bytes
204 /// let mut read_bytes_1 = vec![];
205 /// assert!(reader.read_to_end(&mut read_bytes_1).is_ok());
206 ///
207 /// // ensure input and output matches
208 /// assert_eq!(read_bytes_1, written_bytes);
209 ///
210 /// // rewind reader to halfway through file
211 /// assert!(reader.seek(SeekFrom::Start(1000)).is_ok());
212 ///
213 /// // read 1000 bytes
214 /// let mut read_bytes_2 = vec![];
215 /// assert!(reader.read_to_end(&mut read_bytes_2).is_ok());
216 ///
217 /// // ensure output matches back half of input
218 /// assert_eq!(read_bytes_2.len(), 1000);
219 /// assert!(written_bytes.ends_with(&read_bytes_2));
220 /// ```
221 pub fn new_seekable(mut reader: R) -> Result<Self, Error> {
222 let blocklist = BlockList::read(reader.by_ref())?;
223 let frames_start = reader.stream_position()?;
224
225 Ok(Self {
226 decoder: Decoder::new(reader, blocklist),
227 buf: VecDeque::default(),
228 endianness: std::marker::PhantomData,
229 frames_start: Some(frames_start),
230 })
231 }
232}
233
234impl<R: std::io::Read, E: crate::byteorder::Endianness> Metadata for FlacByteReader<R, E> {
235 #[inline]
236 fn channel_count(&self) -> u8 {
237 self.decoder.channel_count().get()
238 }
239
240 #[inline]
241 fn channel_mask(&self) -> ChannelMask {
242 self.decoder.channel_mask()
243 }
244
245 #[inline]
246 fn sample_rate(&self) -> u32 {
247 self.decoder.sample_rate()
248 }
249
250 #[inline]
251 fn bits_per_sample(&self) -> u32 {
252 self.decoder.bits_per_sample()
253 }
254
255 #[inline]
256 fn total_samples(&self) -> Option<u64> {
257 self.decoder.total_samples().map(|s| s.get())
258 }
259
260 #[inline]
261 fn md5(&self) -> Option<&[u8; 16]> {
262 self.decoder.md5()
263 }
264}
265
266impl<E: crate::byteorder::Endianness> FlacByteReader<BufReader<File>, E> {
267 /// Opens FLAC file from the given path
268 #[inline]
269 pub fn open<P: AsRef<Path>>(path: P, _endianness: E) -> Result<Self, Error> {
270 FlacByteReader::new_seekable(BufReader::new(File::open(path.as_ref())?))
271 }
272}
273
274impl<R: std::io::Read, E: crate::byteorder::Endianness> std::io::Read for FlacByteReader<R, E> {
275 /// Reads samples to the given buffer as bytes in our stream's endianness
276 ///
277 /// Returned samples are interleaved by channel, like:
278 /// [left₀ , right₀ , left₁ , right₁ , left₂ , right₂ , …]
279 ///
280 /// This is the same format used by common PCM container
281 /// formats like WAVE and AIFF
282 ///
283 /// # Errors
284 ///
285 /// Returns any error that occurs when reading the stream,
286 /// converted to an I/O error.
287 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
288 if self.buf.is_empty() {
289 match self.decoder.read_frame()? {
290 Some(frame) => {
291 self.buf.resize(frame.bytes_len(), 0);
292 frame.to_buf::<E>(self.buf.make_contiguous());
293 self.buf.read(buf)
294 }
295 None => Ok(0),
296 }
297 } else {
298 self.buf.read(buf)
299 }
300 }
301}
302
303impl<R: std::io::Read, E: crate::byteorder::Endianness> std::io::BufRead for FlacByteReader<R, E> {
304 /// Reads samples to the given buffer as bytes in our stream's endianness
305 ///
306 /// Returned samples are interleaved by channel, like:
307 /// [left₀ , right₀ , left₁ , right₁ , left₂ , right₂ , …]
308 ///
309 /// # Errors
310 ///
311 /// Returns any error that occurs when reading the stream,
312 /// converted to an I/O error.
313 fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
314 if self.buf.is_empty() {
315 match self.decoder.read_frame()? {
316 Some(frame) => {
317 self.buf.resize(frame.bytes_len(), 0);
318 frame.to_buf::<E>(self.buf.make_contiguous());
319 self.buf.fill_buf()
320 }
321 None => Ok(&[]),
322 }
323 } else {
324 self.buf.fill_buf()
325 }
326 }
327
328 fn consume(&mut self, amt: usize) {
329 self.buf.consume(amt)
330 }
331}
332
333/// A FLAC reader which outputs PCM samples as signed integers
334///
335/// # Example
336///
337/// ```
338/// use flac_codec::{
339/// encode::{FlacSampleWriter, Options},
340/// decode::FlacSampleReader,
341/// };
342/// use std::io::{Cursor, Seek};
343///
344/// let mut flac = Cursor::new(vec![]); // a FLAC file in memory
345///
346/// let mut writer = FlacSampleWriter::new(
347/// &mut flac, // our wrapped writer
348/// Options::default(), // default encoding options
349/// 44100, // sample rate
350/// 16, // bits-per-sample
351/// 1, // channel count
352/// Some(1000), // total samples
353/// ).unwrap();
354///
355/// // write 1000 samples
356/// let written_samples = (0..1000).collect::<Vec<i32>>();
357/// assert!(writer.write(&written_samples).is_ok());
358///
359/// // finalize writing file
360/// assert!(writer.finalize().is_ok());
361///
362/// flac.rewind().unwrap();
363///
364/// // open reader around written FLAC file
365/// let mut reader = FlacSampleReader::new(flac).unwrap();
366///
367/// // read 1000 samples
368/// let mut read_samples = vec![0; 1000];
369/// assert!(matches!(reader.read(&mut read_samples), Ok(1000)));
370///
371/// // ensure they match
372/// assert_eq!(read_samples, written_samples);
373/// ```
374#[derive(Clone)]
375pub struct FlacSampleReader<R> {
376 // the wrapped decoder
377 decoder: Decoder<R>,
378 // decoded sample buffer
379 buf: VecDeque<i32>,
380 // start of FLAC frames
381 frames_start: Option<u64>,
382}
383
384impl<R: std::io::Read> FlacSampleReader<R> {
385 /// Opens new FLAC reader which wraps the given reader
386 ///
387 /// The reader must be positioned at the start of the
388 /// FLAC stream. If the file has non-FLAC data
389 /// at the beginning (such as ID3v2 tags), one
390 /// should skip such data before initializing a `FlacByteReader`.
391 #[inline]
392 pub fn new(mut reader: R) -> Result<Self, Error> {
393 let blocklist = BlockList::read(reader.by_ref())?;
394
395 Ok(Self {
396 decoder: Decoder::new(reader, blocklist),
397 buf: VecDeque::default(),
398 frames_start: None,
399 })
400 }
401
402 /// Returns FLAC metadata blocks
403 #[inline]
404 pub fn metadata(&self) -> &BlockList {
405 self.decoder.metadata()
406 }
407
408 /// Attempts to fill the buffer with samples and returns quantity read
409 ///
410 /// Returned samples are interleaved by channel, like:
411 /// [left₀ , right₀ , left₁ , right₁ , left₂ , right₂ , …]
412 ///
413 /// # Errors
414 ///
415 /// Returns error if some error occurs reading FLAC file
416 #[inline]
417 pub fn read(&mut self, samples: &mut [i32]) -> Result<usize, Error> {
418 if self.buf.is_empty() {
419 match self.decoder.read_frame()? {
420 Some(frame) => {
421 self.buf.extend(frame.iter());
422 }
423 None => return Ok(0),
424 }
425 }
426
427 let to_consume = samples.len().min(self.buf.len());
428 for (i, o) in samples.iter_mut().zip(self.buf.drain(0..to_consume)) {
429 *i = o;
430 }
431 Ok(to_consume)
432 }
433
434 /// Reads all samples from source FLAC, placing them in `buf`
435 ///
436 /// If successful, returns the total number of samples read
437 pub fn read_to_end(&mut self, buf: &mut Vec<i32>) -> Result<usize, Error> {
438 let mut amt_read = 0;
439 loop {
440 match self.fill_buf()? {
441 [] => break Ok(amt_read),
442 decoded => {
443 let decoded_len = decoded.len();
444 buf.extend_from_slice(decoded);
445 amt_read += decoded_len;
446 self.consume(decoded_len);
447 }
448 }
449 }
450 }
451
452 /// Returns complete buffer of all read samples
453 ///
454 /// Analogous to [`std::io::BufRead::fill_buf`], this should
455 /// be paired with [`FlacSampleReader::consume`] to
456 /// consume samples in the filled buffer once used.
457 ///
458 /// Returned samples are interleaved by channel, like:
459 /// [left₀ , right₀ , left₁ , right₁ , left₂ , right₂ , …]
460 ///
461 /// # Errors
462 ///
463 /// Returns error if some error occurs reading FLAC file
464 /// to fill buffer.
465 #[inline]
466 pub fn fill_buf(&mut self) -> Result<&[i32], Error> {
467 if self.buf.is_empty() {
468 match self.decoder.read_frame()? {
469 Some(frame) => {
470 self.buf.extend(frame.iter());
471 }
472 None => return Ok(&[]),
473 }
474 }
475
476 Ok(self.buf.make_contiguous())
477 }
478
479 /// Informs the reader that `amt` samples have been consumed.
480 ///
481 /// Analagous to [`std::io::BufRead::consume`], which marks
482 /// samples as having been read.
483 ///
484 /// May panic if attempting to consume more bytes
485 /// than are available in the buffer.
486 #[inline]
487 pub fn consume(&mut self, amt: usize) {
488 self.buf.drain(0..amt);
489 }
490}
491
492impl<R: std::io::Read + std::io::Seek> FlacSampleReader<R> {
493 /// Opens a new seekable FLAC reader which wraps the given reader
494 ///
495 /// If a stream is both readable and seekable,
496 /// it's vital to use this method to open it if one
497 /// also wishes to seek within the FLAC stream.
498 /// Otherwise, an I/O error will result when attempting to seek.
499 ///
500 /// [`FlacSampleReader::open`] calls this method to ensure
501 /// all `File`-based streams are also seekable.
502 ///
503 /// The reader must be positioned at the start of the
504 /// FLAC stream. If the file has non-FLAC data
505 /// at the beginning (such as ID3v2 tags), one
506 /// should skip such data before initializing a `FlacSampleReader`.
507 ///
508 /// # Example
509 ///
510 /// ```
511 /// use flac_codec::{
512 /// encode::{FlacSampleWriter, Options},
513 /// decode::FlacSampleReader,
514 /// };
515 /// use std::io::{Cursor, Seek};
516 ///
517 /// let mut flac = Cursor::new(vec![]); // a FLAC file in memory
518 ///
519 /// let mut writer = FlacSampleWriter::new(
520 /// &mut flac, // our wrapped writer
521 /// Options::default(), // default encoding options
522 /// 44100, // sample rate
523 /// 16, // bits-per-sample
524 /// 1, // channel count
525 /// Some(1000), // total samples
526 /// ).unwrap();
527 ///
528 /// // write 1000 samples
529 /// let written_samples = (0..1000).collect::<Vec<i32>>();
530 /// assert!(writer.write(&written_samples).is_ok());
531 ///
532 /// // finalize writing file
533 /// assert!(writer.finalize().is_ok());
534 ///
535 /// flac.rewind().unwrap();
536 ///
537 /// // open reader around written FLAC file
538 /// let mut reader = FlacSampleReader::new_seekable(flac).unwrap();
539 ///
540 /// // read 1000 samples
541 /// let mut read_samples_1 = vec![0; 1000];
542 /// assert!(matches!(reader.read(&mut read_samples_1), Ok(1000)));
543 ///
544 /// // ensure they match
545 /// assert_eq!(read_samples_1, written_samples);
546 ///
547 /// // rewind reader to halfway through file
548 /// assert!(reader.seek(500).is_ok());
549 ///
550 /// // read 500 samples
551 /// let mut read_samples_2 = vec![0; 500];
552 /// assert!(matches!(reader.read(&mut read_samples_2), Ok(500)));
553 ///
554 /// // ensure output matches back half of input
555 /// assert_eq!(read_samples_2.len(), 500);
556 /// assert!(written_samples.ends_with(&read_samples_2));
557 /// ```
558 pub fn new_seekable(mut reader: R) -> Result<Self, Error> {
559 let blocklist = BlockList::read(reader.by_ref())?;
560 let frames_start = reader.stream_position()?;
561
562 Ok(Self {
563 decoder: Decoder::new(reader, blocklist),
564 buf: VecDeque::default(),
565 frames_start: Some(frames_start),
566 })
567 }
568}
569
570impl FlacSampleReader<BufReader<File>> {
571 /// Opens FLAC file from the given path
572 #[inline]
573 pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
574 FlacSampleReader::new_seekable(BufReader::new(File::open(path.as_ref())?))
575 }
576}
577
578impl<R: std::io::Read> Metadata for FlacSampleReader<R> {
579 #[inline]
580 fn channel_count(&self) -> u8 {
581 self.decoder.channel_count().get()
582 }
583
584 #[inline]
585 fn channel_mask(&self) -> ChannelMask {
586 self.decoder.channel_mask()
587 }
588
589 #[inline]
590 fn sample_rate(&self) -> u32 {
591 self.decoder.sample_rate()
592 }
593
594 #[inline]
595 fn bits_per_sample(&self) -> u32 {
596 self.decoder.bits_per_sample()
597 }
598
599 #[inline]
600 fn total_samples(&self) -> Option<u64> {
601 self.decoder.total_samples().map(|s| s.get())
602 }
603
604 #[inline]
605 fn md5(&self) -> Option<&[u8; 16]> {
606 self.decoder.md5()
607 }
608}
609
610impl<R: std::io::Read> IntoIterator for FlacSampleReader<R> {
611 type IntoIter = FlacSampleIterator<R>;
612 type Item = Result<i32, Error>;
613
614 fn into_iter(self) -> FlacSampleIterator<R> {
615 FlacSampleIterator { reader: self }
616 }
617}
618
619/// A FLAC reader which iterates over decoded samples as signed integers
620///
621/// # Example
622///
623/// ```
624/// use flac_codec::{
625/// encode::{FlacSampleWriter, Options},
626/// decode::FlacSampleReader,
627/// };
628/// use std::io::{Cursor, Seek};
629///
630/// let mut flac = Cursor::new(vec![]); // a FLAC file in memory
631///
632/// let mut writer = FlacSampleWriter::new(
633/// &mut flac, // our wrapped writer
634/// Options::default(), // default encoding options
635/// 44100, // sample rate
636/// 16, // bits-per-sample
637/// 1, // channel count
638/// Some(10), // total samples
639/// ).unwrap();
640///
641/// // write 10 samples
642/// let written_samples = (0..10).collect::<Vec<i32>>();
643/// assert!(writer.write(&written_samples).is_ok());
644///
645/// // finalize writing file
646/// assert!(writer.finalize().is_ok());
647///
648/// flac.rewind().unwrap();
649///
650/// // open reader around written FLAC file
651/// let reader = FlacSampleReader::new(flac).unwrap();
652///
653/// // convert reader to iterator
654/// let mut iter = reader.into_iter();
655///
656/// // read all its samples
657/// let read_samples = iter.collect::<Result<Vec<_>, _>>().unwrap();
658///
659/// // ensure they match
660/// assert_eq!(read_samples, written_samples);
661/// assert_eq!(read_samples, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
662/// ```
663#[derive(Clone)]
664pub struct FlacSampleIterator<R> {
665 reader: FlacSampleReader<R>,
666}
667
668impl<R: std::io::Read> Metadata for FlacSampleIterator<R> {
669 fn channel_count(&self) -> u8 {
670 self.reader.channel_count()
671 }
672
673 fn sample_rate(&self) -> u32 {
674 self.reader.sample_rate()
675 }
676
677 fn bits_per_sample(&self) -> u32 {
678 self.reader.bits_per_sample()
679 }
680
681 fn total_samples(&self) -> Option<u64> {
682 self.reader.total_samples()
683 }
684
685 fn md5(&self) -> Option<&[u8; 16]> {
686 self.reader.md5()
687 }
688}
689
690impl<R: std::io::Read> Iterator for FlacSampleIterator<R> {
691 type Item = Result<i32, Error>;
692
693 #[inline]
694 fn next(&mut self) -> Option<Result<i32, Error>> {
695 match self.reader.buf.pop_front() {
696 Some(sample) => Some(Ok(sample)),
697 None => match self.reader.decoder.read_frame() {
698 Ok(Some(frame)) => {
699 self.reader.buf.extend(frame.iter());
700 self.reader.buf.pop_front().map(Ok)
701 }
702 Err(e) => Some(Err(e)),
703 Ok(None) => None,
704 },
705 }
706 }
707}
708
709impl<R: std::io::Read + std::io::Seek, E: crate::byteorder::Endianness> std::io::Seek
710 for FlacByteReader<R, E>
711{
712 fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
713 use std::cmp::Ordering;
714
715 let Self { decoder, buf, .. } = self;
716
717 let streaminfo = decoder.blocks.streaminfo();
718
719 let bytes_per_pcm_frame: u64 = (u32::from(streaminfo.bits_per_sample).div_ceil(8)
720 * u32::from(streaminfo.channels.get()))
721 .into();
722
723 // the desired absolute position in the stream, in bytes
724 let desired_pos: u64 = match pos {
725 std::io::SeekFrom::Start(pos) => pos,
726 std::io::SeekFrom::Current(pos) => {
727 // current position in bytes is current position in samples
728 // converted to bytes *minus* the un-consumed space in the buffer
729 // since the sample position is running ahead of the byte position
730 let original_pos: u64 =
731 (decoder.current_sample * bytes_per_pcm_frame) - (buf.len() as u64);
732
733 match pos.cmp(&0) {
734 Ordering::Less => {
735 original_pos
736 .checked_sub(pos.unsigned_abs())
737 .ok_or(std::io::Error::new(
738 std::io::ErrorKind::InvalidInput,
739 "cannot seek below byte 0",
740 ))?
741 }
742 Ordering::Equal => return Ok(original_pos),
743 Ordering::Greater => {
744 original_pos
745 .checked_add(pos.unsigned_abs())
746 .ok_or(std::io::Error::new(
747 std::io::ErrorKind::InvalidInput,
748 "seek offset too large",
749 ))?
750 }
751 }
752 }
753 std::io::SeekFrom::End(pos) => {
754 // if the total samples is unknown in streaminfo,
755 // we have no way to know where the file's end is
756 // (this is a very unusual case)
757 let max_pos: u64 = decoder.total_samples().map(|s| s.get()).ok_or_else(|| {
758 std::io::Error::new(std::io::ErrorKind::NotSeekable, "total samples not known")
759 })?;
760
761 match pos.cmp(&0) {
762 Ordering::Less => max_pos.checked_sub(pos.unsigned_abs()).ok_or_else(|| {
763 std::io::Error::new(
764 std::io::ErrorKind::InvalidInput,
765 "cannot seek below byte 0",
766 )
767 })?,
768 Ordering::Equal => max_pos,
769 Ordering::Greater => {
770 return Err(std::io::Error::new(
771 std::io::ErrorKind::InvalidInput,
772 "cannot seek beyond end of file",
773 ));
774 }
775 }
776 }
777 };
778
779 // perform seek in stream to the desired sample
780 // (this will usually be some position prior to the desired sample)
781 let mut new_pos = decoder.seek(
782 self.frames_start
783 .ok_or(std::io::Error::from(std::io::ErrorKind::NotSeekable))?,
784 desired_pos / bytes_per_pcm_frame,
785 )? * bytes_per_pcm_frame;
786
787 // seeking invalidates current buffer
788 buf.clear();
789
790 // skip bytes to reach desired sample
791 while new_pos < desired_pos {
792 use std::io::BufRead;
793
794 let buf = self.fill_buf()?;
795
796 if !buf.is_empty() {
797 let to_skip = (usize::try_from(desired_pos - new_pos).unwrap()).min(buf.len());
798 self.consume(to_skip);
799 new_pos += to_skip as u64;
800 } else {
801 // attempting to seek beyond the end of the FLAC file
802 return Err(std::io::Error::new(
803 std::io::ErrorKind::UnexpectedEof,
804 "stream exhausted before sample reached",
805 ));
806 }
807 }
808
809 Ok(desired_pos)
810 }
811}
812
813impl<R: std::io::Read + std::io::Seek> FlacSampleReader<R> {
814 /// Seeks to the given channel-independent sample
815 ///
816 /// The sample is relative to the beginning of the stream
817 pub fn seek(&mut self, sample: u64) -> Result<(), Error> {
818 let channels: u8 = self.channel_count();
819
820 // actual position, in channel-independent samples
821 let mut pos = self.decoder.seek(
822 self.frames_start
823 .ok_or(std::io::Error::from(std::io::ErrorKind::NotSeekable))?,
824 sample,
825 )?;
826
827 // seeking invalidates the current buffer
828 self.buf.clear();
829
830 // needed channel-independent samples
831 while sample > pos {
832 let buf = self.fill_buf()?;
833
834 // size of buf in channel-independent samples
835 match buf.len() / usize::from(channels) {
836 0 => {
837 // read beyond end of stream
838 return Err(Error::InvalidSeek);
839 }
840 buf_samples => {
841 // amount of channel-independent samples to consume
842 let to_consume = buf_samples.min((sample - pos).try_into().unwrap());
843
844 // mark samples in buffer as consumed
845 self.consume(to_consume * usize::from(channels));
846
847 // advance current actual position
848 pos += to_consume as u64;
849 }
850 }
851 }
852
853 Ok(())
854 }
855}
856
857/// A FLAC reader which operates on streamed input
858///
859/// Streamed FLAC files are simply a collection of raw
860/// FLAC frames with no accompanying metadata,
861/// like might be delivered over a multicast stream.
862///
863/// Because this reader needs to scan the stream for
864/// valid frame sync codes before playback,
865/// it requires [`std::io::BufRead`] instead of [`std::io::Read`].
866///
867/// # Example
868///
869/// ```
870/// use flac_codec::{
871/// decode::{FlacStreamReader, FrameBuf},
872/// encode::{FlacStreamWriter, Options},
873/// };
874/// use std::io::{Cursor, Seek};
875/// use std::num::NonZero;
876/// use bitstream_io::SignedBitCount;
877///
878/// let mut flac = Cursor::new(vec![]);
879///
880/// let samples = (0..100).collect::<Vec<i32>>();
881///
882/// let mut w = FlacStreamWriter::new(&mut flac, Options::default());
883///
884/// // write a single FLAC frame with some samples
885/// w.write(
886/// 44100, // sample rate
887/// 1, // channels
888/// 16, // bits-per-sample
889/// &samples,
890/// ).unwrap();
891///
892/// flac.rewind().unwrap();
893///
894/// let mut r = FlacStreamReader::new(&mut flac);
895///
896/// // read a single FLAC frame with some samples
897/// assert_eq!(
898/// r.read().unwrap(),
899/// FrameBuf {
900/// samples: &samples,
901/// sample_rate: 44100,
902/// channels: 1,
903/// bits_per_sample: 16,
904/// },
905/// );
906/// ```
907pub struct FlacStreamReader<R> {
908 // the wrapped reader
909 reader: R,
910 // raw decoded frame samples
911 buf: Frame,
912 // interlaced frame samples
913 samples: Vec<i32>,
914}
915
916impl<R: std::io::BufRead> FlacStreamReader<R> {
917 /// Opens new FLAC stream reader which wraps the given reader
918 #[inline]
919 pub fn new(reader: R) -> Self {
920 Self {
921 reader,
922 buf: Frame::default(),
923 samples: Vec::default(),
924 }
925 }
926
927 /// Returns the next decoded FLAC frame and its parameters
928 ///
929 /// # Errors
930 ///
931 /// Returns an I/O error from the stream or if any
932 /// other error occurs when reading the file.
933 pub fn read(&mut self) -> Result<FrameBuf<'_>, Error> {
934 use crate::crc::{Checksum, Crc16, CrcReader};
935 use crate::stream::FrameHeader;
936 use bitstream_io::{BigEndian, BitReader};
937 use std::io::Read;
938
939 // Finding the next frame header in a BufRead is
940 // tougher than it seems because fill_buf might
941 // slice a frame sync code in half, which needs
942 // to be accounted for.
943
944 let (header, mut crc16_reader) = loop {
945 // scan for the first byte of the frame sync
946 self.reader.skip_until(0b11111111)?;
947
948 // either gotten the first half of the frame sync,
949 // or have reached EOF
950
951 // check that the next byte is the other half of a frame sync
952 match self.reader.fill_buf() {
953 Ok([]) => {
954 return Err(std::io::Error::new(
955 std::io::ErrorKind::UnexpectedEof,
956 "eof looking for frame sync",
957 )
958 .into());
959 }
960 Ok([byte, ..]) if byte >> 1 == 0b1111100 => {
961 // got a whole frame sync
962 // so try to parse a whole frame header
963 let mut crc_reader: CrcReader<_, Crc16> = CrcReader::new(
964 std::slice::from_ref(&0b11111111).chain(self.reader.by_ref()),
965 );
966
967 if let Ok(header) = FrameHeader::read_subset(&mut crc_reader) {
968 break (header, crc_reader);
969 }
970 }
971 Ok(_) => continue,
972 // didn't get the other half of frame sync,
973 // so continue without consuming anything
974 Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
975 Err(e) => return Err(e.into()),
976 }
977 };
978
979 read_subframes(
980 BitReader::endian(crc16_reader.by_ref(), BigEndian),
981 &header,
982 &mut self.buf,
983 )?;
984
985 if crc16_reader.into_checksum().valid() {
986 self.samples.clear();
987 self.samples.extend(self.buf.iter());
988
989 Ok(FrameBuf {
990 samples: self.samples.as_slice(),
991 sample_rate: header.sample_rate.into(),
992 channels: header.channel_assignment.count(),
993 bits_per_sample: header.bits_per_sample.into(),
994 })
995 } else {
996 Err(Error::Crc16Mismatch)
997 }
998 }
999}
1000
1001/// A buffer of samples read from a [`FlacStreamReader`]
1002///
1003/// In a conventional FLAC reader, the stream's metadata
1004/// is known in advance from the required STREAMINFO metadata block
1005/// and is an error for it to change mid-file.
1006///
1007/// In a streamed reader, that metadata isn't known in advance
1008/// and can change from frame to frame. This buffer contains
1009/// all the metadata fields in the frame for decoding/playback.
1010#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1011pub struct FrameBuf<'s> {
1012 /// Decoded samples
1013 ///
1014 /// Samples are interleaved by channel, like:
1015 /// [left₀ , right₀ , left₁ , right₁ , left₂ , right₂ , …]
1016 pub samples: &'s [i32],
1017
1018 /// The sample rate, in Hz
1019 pub sample_rate: u32,
1020
1021 /// Channel count, from 1 to 8
1022 pub channels: u8,
1023
1024 /// Bits-per-sample, from 4 to 32
1025 pub bits_per_sample: u32,
1026}
1027
1028/// The results of FLAC file verification
1029#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
1030pub enum Verified {
1031 /// FLAC file has MD5 hash and decoded contents match that hash
1032 MD5Match,
1033 /// FLAC file has MD5 hash, but decoded contents do not match
1034 MD5Mismatch,
1035 /// FLAC file has no MD5 hash, but decodes successfully
1036 NoMD5,
1037}
1038
1039/// Verifies FLAC file for correctness
1040pub fn verify<P: AsRef<Path>>(p: P) -> Result<Verified, Error> {
1041 File::open(p.as_ref())
1042 .map_err(Error::Io)
1043 .and_then(|r| verify_reader(BufReader::new(r)))
1044}
1045
1046/// Verifies FLAC stream for correctness
1047///
1048/// The stream must be set to the start of the FLAC data
1049pub fn verify_reader<R: std::io::Read>(r: R) -> Result<Verified, Error> {
1050 use crate::byteorder::LittleEndian;
1051
1052 let mut r = FlacByteReader::endian(r, LittleEndian)?;
1053 match r.md5().cloned() {
1054 Some(flac_md5) => {
1055 let mut output_md5 = md5::Context::new();
1056 std::io::copy(&mut r, &mut output_md5)?;
1057 Ok(if flac_md5 == output_md5.compute().0 {
1058 Verified::MD5Match
1059 } else {
1060 Verified::MD5Mismatch
1061 })
1062 }
1063 None => std::io::copy(&mut r, &mut std::io::sink())
1064 .map(|_| Verified::NoMD5)
1065 .map_err(Error::Io),
1066 }
1067}
1068
1069/// A FLAC decoder
1070#[derive(Clone)]
1071struct Decoder<R> {
1072 reader: R,
1073 // all metadata blocks
1074 blocks: BlockList,
1075 // // the size of everything before the first frame, in bytes
1076 // frames_start: u64,
1077 // the current sample, in channel-independent samples
1078 current_sample: u64,
1079 // raw decoded frame samples
1080 buf: Frame,
1081}
1082
1083impl<R: std::io::Read> Decoder<R> {
1084 /// Builds a new FLAC decoder from the given stream
1085 ///
1086 /// This assumes the stream is positioned at the start
1087 /// of the file.
1088 ///
1089 /// # Errors
1090 ///
1091 /// Returns an error of the initial FLAC metadata
1092 /// is invalid or an I/O error occurs reading
1093 /// the initial metadata.
1094 fn new(reader: R, blocks: BlockList) -> Self {
1095 Self {
1096 reader,
1097 blocks,
1098 current_sample: 0,
1099 buf: Frame::default(),
1100 }
1101 }
1102
1103 /// Returns channel count
1104 ///
1105 /// From 1 to 8
1106 fn channel_count(&self) -> NonZero<u8> {
1107 self.blocks.streaminfo().channels
1108 }
1109
1110 fn channel_mask(&self) -> ChannelMask {
1111 self.blocks.channel_mask()
1112 }
1113
1114 /// Returns sample rate, in Hz
1115 fn sample_rate(&self) -> u32 {
1116 self.blocks.streaminfo().sample_rate
1117 }
1118
1119 /// Returns decoder's bits-per-sample
1120 ///
1121 /// From 1 to 32
1122 fn bits_per_sample(&self) -> u32 {
1123 self.blocks.streaminfo().bits_per_sample.into()
1124 }
1125
1126 /// Returns total number of channel-independent samples, if known
1127 fn total_samples(&self) -> Option<NonZero<u64>> {
1128 self.blocks.streaminfo().total_samples
1129 }
1130
1131 /// Returns MD5 of entire stream, if known
1132 fn md5(&self) -> Option<&[u8; 16]> {
1133 self.blocks.streaminfo().md5.as_ref()
1134 }
1135
1136 /// Returns FLAC metadata
1137 fn metadata(&self) -> &BlockList {
1138 &self.blocks
1139 }
1140
1141 /// Returns decoded frame, if any.
1142 ///
1143 /// # Errors
1144 ///
1145 /// Returns any decoding error from the stream.
1146 fn read_frame(&mut self) -> Result<Option<&Frame>, Error> {
1147 use crate::crc::{Checksum, Crc16, CrcReader};
1148 use crate::stream::FrameHeader;
1149 use bitstream_io::{BigEndian, BitReader};
1150 use std::io::Read;
1151
1152 let mut crc16_reader: CrcReader<_, Crc16> = CrcReader::new(self.reader.by_ref());
1153
1154 let header = match self
1155 .blocks
1156 .streaminfo()
1157 .total_samples
1158 .map(|total| total.get() - self.current_sample)
1159 {
1160 Some(0) => return Ok(None),
1161 Some(remaining) => FrameHeader::read(crc16_reader.by_ref(), self.blocks.streaminfo())
1162 .and_then(|header| {
1163 // only the last block in a stream may contain <= 14 samples
1164 let block_size = u16::from(header.block_size);
1165 (u64::from(block_size) == remaining || block_size > 14)
1166 .then_some(header)
1167 .ok_or(Error::ShortBlock)
1168 })?,
1169 // if total number of remaining samples isn't known,
1170 // treat an EOF error as the end of stream
1171 // (this is an uncommon case)
1172 None => match FrameHeader::read(crc16_reader.by_ref(), self.blocks.streaminfo()) {
1173 Ok(header) => header,
1174 Err(Error::Io(err)) if err.kind() == std::io::ErrorKind::UnexpectedEof => {
1175 return Ok(None);
1176 }
1177 Err(err) => return Err(err),
1178 },
1179 };
1180
1181 read_subframes(
1182 BitReader::endian(crc16_reader.by_ref(), BigEndian),
1183 &header,
1184 &mut self.buf,
1185 )?;
1186
1187 if !crc16_reader.into_checksum().valid() {
1188 return Err(Error::Crc16Mismatch);
1189 }
1190
1191 self.current_sample += u64::from(u16::from(header.block_size));
1192
1193 Ok(Some(&self.buf))
1194 }
1195}
1196
1197impl<R: std::io::Seek> Decoder<R> {
1198 /// Attempts to seek to desired sample number
1199 ///
1200 /// Sample number is indicated in channel-independent samples.
1201 ///
1202 /// Upon success, returns the actual sample number
1203 /// the stream is positioned to, in channel-independent samples,
1204 /// which may be less than the desired sample.
1205 ///
1206 /// # Errors
1207 ///
1208 /// Passes along an I/O error that occurs when seeking
1209 /// within the file.
1210 fn seek(&mut self, frames_start: u64, sample: u64) -> Result<u64, Error> {
1211 use crate::metadata::SeekPoint;
1212 use std::io::SeekFrom;
1213
1214 match self.blocks.get() {
1215 Some(SeekTable { points: seektable }) => {
1216 match seektable
1217 .iter()
1218 .filter(|point| {
1219 point
1220 .sample_offset()
1221 .map(|offset| offset <= sample)
1222 .unwrap_or(false)
1223 })
1224 .next_back()
1225 {
1226 Some(SeekPoint::Defined {
1227 sample_offset,
1228 byte_offset,
1229 ..
1230 }) => {
1231 assert!(*sample_offset <= sample);
1232 self.reader
1233 .seek(SeekFrom::Start(frames_start + byte_offset))?;
1234 self.current_sample = *sample_offset;
1235 Ok(*sample_offset)
1236 }
1237 _ => {
1238 // empty seektable so rewind to start of stream
1239 self.reader.seek(SeekFrom::Start(frames_start))?;
1240 self.current_sample = 0;
1241 Ok(0)
1242 }
1243 }
1244 }
1245 None => {
1246 // no seektable
1247 // all we can do is rewind data to start of stream
1248 self.reader.seek(SeekFrom::Start(frames_start))?;
1249 self.current_sample = 0;
1250 Ok(0)
1251 }
1252 }
1253 }
1254}
1255
1256fn read_subframes<R: BitRead>(
1257 mut reader: R,
1258 header: &crate::stream::FrameHeader,
1259 buf: &mut Frame,
1260) -> Result<(), Error> {
1261 use crate::stream::ChannelAssignment;
1262
1263 match header.channel_assignment {
1264 ChannelAssignment::Independent(total_channels) => {
1265 buf.resized_channels(
1266 header.bits_per_sample.into(),
1267 total_channels.into(),
1268 u16::from(header.block_size).into(),
1269 )
1270 .try_for_each(|channel| {
1271 read_subframe(&mut reader, header.bits_per_sample.into(), channel)
1272 })?;
1273 }
1274 ChannelAssignment::LeftSide => {
1275 let (left, side) = buf.resized_stereo(
1276 header.bits_per_sample.into(),
1277 u16::from(header.block_size).into(),
1278 );
1279
1280 read_subframe(&mut reader, header.bits_per_sample.into(), left)?;
1281
1282 match header.bits_per_sample.checked_add(1) {
1283 Some(side_bps) => {
1284 read_subframe(&mut reader, side_bps, side)?;
1285
1286 left.iter().zip(side.iter_mut()).for_each(|(left, side)| {
1287 *side = *left - *side;
1288 });
1289 }
1290 None => {
1291 // the very rare case of 32-bps streams
1292 // accompanied by side channels
1293 let mut side_i64 = vec![0; side.len()];
1294
1295 read_subframe::<33, R, i64>(
1296 &mut reader,
1297 SignedBitCount::from(header.bits_per_sample)
1298 .checked_add(1)
1299 .expect("excessive bps for substream"),
1300 &mut side_i64,
1301 )?;
1302
1303 left.iter().zip(side_i64).zip(side.iter_mut()).for_each(
1304 |((left, side_i64), side)| {
1305 *side = (*left as i64 - side_i64) as i32;
1306 },
1307 );
1308 }
1309 }
1310 }
1311 ChannelAssignment::SideRight => {
1312 let (side, right) = buf.resized_stereo(
1313 header.bits_per_sample.into(),
1314 u16::from(header.block_size).into(),
1315 );
1316
1317 match header.bits_per_sample.checked_add(1) {
1318 Some(side_bps) => {
1319 read_subframe(&mut reader, side_bps, side)?;
1320 read_subframe(&mut reader, header.bits_per_sample.into(), right)?;
1321
1322 side.iter_mut().zip(right.iter()).for_each(|(side, right)| {
1323 *side += *right;
1324 });
1325 }
1326 None => {
1327 // the very rare case of 32-bps streams
1328 // accompanied by side channels
1329 let mut side_i64 = vec![0; side.len()];
1330
1331 read_subframe::<33, R, i64>(
1332 &mut reader,
1333 SignedBitCount::from(header.bits_per_sample)
1334 .checked_add(1)
1335 .expect("excessive bps for substream"),
1336 &mut side_i64,
1337 )?;
1338 read_subframe(&mut reader, header.bits_per_sample.into(), right)?;
1339
1340 side.iter_mut().zip(side_i64).zip(right.iter()).for_each(
1341 |((side, side_64), right)| {
1342 *side = (side_64 + *right as i64) as i32;
1343 },
1344 );
1345 }
1346 }
1347 }
1348 ChannelAssignment::MidSide => {
1349 let (mid, side) = buf.resized_stereo(
1350 header.bits_per_sample.into(),
1351 u16::from(header.block_size).into(),
1352 );
1353
1354 read_subframe(&mut reader, header.bits_per_sample.into(), mid)?;
1355
1356 match header.bits_per_sample.checked_add(1) {
1357 Some(side_bps) => {
1358 read_subframe(&mut reader, side_bps, side)?;
1359
1360 mid.iter_mut().zip(side.iter_mut()).for_each(|(mid, side)| {
1361 let sum = *mid * 2 + side.abs() % 2;
1362 *mid = (sum + *side) >> 1;
1363 *side = (sum - *side) >> 1;
1364 });
1365 }
1366 None => {
1367 // the very rare case of 32-bps streams
1368 // accompanied by side channels
1369 let mut side_i64 = vec![0; side.len()];
1370
1371 read_subframe::<33, R, i64>(
1372 &mut reader,
1373 SignedBitCount::from(header.bits_per_sample)
1374 .checked_add(1)
1375 .expect("excessive bps for substream"),
1376 &mut side_i64,
1377 )?;
1378
1379 mid.iter_mut().zip(side.iter_mut()).zip(side_i64).for_each(
1380 |((mid, side), side_i64)| {
1381 let sum = *mid as i64 * 2 + (side_i64.abs() % 2);
1382 *mid = ((sum + side_i64) >> 1) as i32;
1383 *side = ((sum - side_i64) >> 1) as i32;
1384 },
1385 );
1386 }
1387 }
1388 }
1389 }
1390
1391 reader.byte_align();
1392 reader.skip(16)?; // CRC-16 checksum
1393
1394 Ok(())
1395}
1396
1397fn read_subframe<const MAX: u32, R: BitRead, I: SignedInteger>(
1398 reader: &mut R,
1399 bits_per_sample: SignedBitCount<MAX>,
1400 channel: &mut [I],
1401) -> Result<(), Error> {
1402 use crate::stream::{SubframeHeader, SubframeHeaderType};
1403
1404 let header = reader.parse::<SubframeHeader>()?;
1405
1406 let effective_bps = bits_per_sample
1407 .checked_sub::<MAX>(header.wasted_bps)
1408 .ok_or(Error::ExcessiveWastedBits)?;
1409
1410 match header.type_ {
1411 SubframeHeaderType::Constant => {
1412 channel.fill(reader.read_signed_counted(effective_bps)?);
1413 }
1414 SubframeHeaderType::Verbatim => {
1415 channel.iter_mut().try_for_each(|i| {
1416 *i = reader.read_signed_counted(effective_bps)?;
1417 Ok::<(), Error>(())
1418 })?;
1419 }
1420 SubframeHeaderType::Fixed { order } => {
1421 read_fixed_subframe(
1422 reader,
1423 effective_bps,
1424 SubframeHeaderType::FIXED_COEFFS[order as usize],
1425 channel,
1426 )?;
1427 }
1428 SubframeHeaderType::Lpc { order } => {
1429 read_lpc_subframe(reader, effective_bps, order, channel)?;
1430 }
1431 }
1432
1433 if header.wasted_bps > 0 {
1434 channel.iter_mut().for_each(|i| *i <<= header.wasted_bps);
1435 }
1436
1437 Ok(())
1438}
1439
1440fn read_fixed_subframe<const MAX: u32, R: BitRead, I: SignedInteger>(
1441 reader: &mut R,
1442 bits_per_sample: SignedBitCount<MAX>,
1443 coefficients: &[i64],
1444 channel: &mut [I],
1445) -> Result<(), Error> {
1446 let (warm_up, residuals) = channel
1447 .split_at_mut_checked(coefficients.len())
1448 .ok_or(Error::InvalidFixedOrder)?;
1449
1450 warm_up.iter_mut().try_for_each(|s| {
1451 *s = reader.read_signed_counted(bits_per_sample)?;
1452 Ok::<_, std::io::Error>(())
1453 })?;
1454
1455 read_residuals(reader, coefficients.len(), residuals)?;
1456 predict(coefficients, 0, channel);
1457 Ok(())
1458}
1459
1460fn read_lpc_subframe<const MAX: u32, R: BitRead, I: SignedInteger>(
1461 reader: &mut R,
1462 bits_per_sample: SignedBitCount<MAX>,
1463 predictor_order: NonZero<u8>,
1464 channel: &mut [I],
1465) -> Result<(), Error> {
1466 let mut coefficients: [i64; 32] = [0; 32];
1467
1468 let (warm_up, residuals) = channel
1469 .split_at_mut_checked(predictor_order.get().into())
1470 .ok_or(Error::InvalidLpcOrder)?;
1471
1472 warm_up.iter_mut().try_for_each(|s| {
1473 *s = reader.read_signed_counted(bits_per_sample)?;
1474 Ok::<_, std::io::Error>(())
1475 })?;
1476
1477 let qlp_precision: SignedBitCount<15> = reader
1478 .read_count::<0b1111>()?
1479 .checked_add(1)
1480 .and_then(|c| c.signed_count())
1481 .ok_or(Error::InvalidQlpPrecision)?;
1482
1483 let qlp_shift: u32 = reader
1484 .read::<5, i32>()?
1485 .try_into()
1486 .map_err(|_| Error::NegativeLpcShift)?;
1487
1488 let coefficients = &mut coefficients[0..predictor_order.get().into()];
1489
1490 coefficients.iter_mut().try_for_each(|c| {
1491 *c = reader.read_signed_counted(qlp_precision)?;
1492 Ok::<_, std::io::Error>(())
1493 })?;
1494
1495 read_residuals(reader, coefficients.len(), residuals)?;
1496 predict(coefficients, qlp_shift, channel);
1497 Ok(())
1498}
1499
1500fn predict<I: SignedInteger>(coefficients: &[i64], qlp_shift: u32, channel: &mut [I]) {
1501 for split in coefficients.len()..channel.len() {
1502 let (predicted, residuals) = channel.split_at_mut(split);
1503
1504 residuals[0] += I::from_i64(
1505 predicted
1506 .iter()
1507 .rev()
1508 .zip(coefficients)
1509 .map(|(x, y)| (*x).into() * y)
1510 .sum::<i64>()
1511 >> qlp_shift,
1512 );
1513 }
1514}
1515
1516#[test]
1517fn verify_prediction() {
1518 let mut coefficients = [-75, 166, 121, -269, -75, -399, 1042];
1519 let mut buffer = [
1520 -796, -547, -285, -32, 199, 443, 670, -2, -23, 14, 6, 3, -4, 12, -2, 10,
1521 ];
1522 coefficients.reverse();
1523 predict(&coefficients, 9, &mut buffer);
1524 assert_eq!(
1525 &buffer,
1526 &[
1527 -796, -547, -285, -32, 199, 443, 670, 875, 1046, 1208, 1343, 1454, 1541, 1616, 1663,
1528 1701
1529 ]
1530 );
1531
1532 let mut coefficients = [119, -255, 555, -836, 879, -1199, 1757];
1533 let mut buffer = [-21363, -21951, -22649, -24364, -27297, -26870, -30017, 3157];
1534 coefficients.reverse();
1535 predict(&coefficients, 10, &mut buffer);
1536 assert_eq!(
1537 &buffer,
1538 &[
1539 -21363, -21951, -22649, -24364, -27297, -26870, -30017, -29718
1540 ]
1541 );
1542
1543 let mut coefficients = [
1544 709, -2589, 4600, -4612, 1350, 4220, -9743, 12671, -12129, 8586, -3775, -645, 3904, -5543,
1545 4373, 182, -6873, 13265, -15417, 11550,
1546 ];
1547 let mut buffer = [
1548 213238, 210830, 234493, 209515, 235139, 201836, 208151, 186277, 157720, 148176, 115037,
1549 104836, 60794, 54523, 412, 17943, -6025, -3713, 8373, 11764, 30094,
1550 ];
1551 coefficients.reverse();
1552 predict(&coefficients, 12, &mut buffer);
1553 assert_eq!(
1554 &buffer,
1555 &[
1556 213238, 210830, 234493, 209515, 235139, 201836, 208151, 186277, 157720, 148176, 115037,
1557 104836, 60794, 54523, 412, 17943, -6025, -3713, 8373, 11764, 33931,
1558 ]
1559 );
1560}
1561
1562fn read_residuals<R: BitRead, I: SignedInteger>(
1563 reader: &mut R,
1564 predictor_order: usize,
1565 residuals: &mut [I],
1566) -> Result<(), Error> {
1567 fn read_block<const RICE_MAX: u32, R: BitRead, I: SignedInteger>(
1568 reader: &mut R,
1569 predictor_order: usize,
1570 mut residuals: &mut [I],
1571 ) -> Result<(), Error> {
1572 use crate::stream::ResidualPartitionHeader;
1573
1574 let block_size = predictor_order + residuals.len();
1575 let partition_order = reader.read::<4, u32>()?;
1576 let partition_count = 1 << partition_order;
1577
1578 for p in 0..partition_count {
1579 let (partition, next) = residuals
1580 .split_at_mut_checked(
1581 (block_size / partition_count)
1582 .checked_sub(if p == 0 { predictor_order } else { 0 })
1583 .ok_or(Error::InvalidPartitionOrder)?,
1584 )
1585 .ok_or(Error::InvalidPartitionOrder)?;
1586
1587 match reader.parse()? {
1588 ResidualPartitionHeader::Standard { rice } => {
1589 partition.iter_mut().try_for_each(|s| {
1590 let msb = reader.read_unary::<1>()?;
1591 let lsb = reader.read_counted::<RICE_MAX, u32>(rice)?;
1592 let unsigned = (msb << u32::from(rice)) | lsb;
1593 *s = if (unsigned & 1) == 1 {
1594 -(I::from_u32(unsigned >> 1)) - I::ONE
1595 } else {
1596 I::from_u32(unsigned >> 1)
1597 };
1598 Ok::<(), std::io::Error>(())
1599 })?;
1600 }
1601 ResidualPartitionHeader::Escaped { escape_size } => {
1602 partition.iter_mut().try_for_each(|s| {
1603 *s = reader.read_signed_counted(escape_size)?;
1604 Ok::<(), std::io::Error>(())
1605 })?;
1606 }
1607 ResidualPartitionHeader::Constant => {
1608 partition.fill(I::ZERO);
1609 }
1610 }
1611
1612 residuals = next;
1613 }
1614
1615 Ok(())
1616 }
1617
1618 match reader.read::<2, u8>()? {
1619 0 => read_block::<0b1111, R, I>(reader, predictor_order, residuals),
1620 1 => read_block::<0b11111, R, I>(reader, predictor_order, residuals),
1621 _ => Err(Error::InvalidCodingMethod),
1622 }
1623}