Skip to main content

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: Vec<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: Vec::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.as_mut_slice())
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: Vec::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 {
616            decoder: self.decoder,
617            buf: self.buf.into(),
618        }
619    }
620}
621
622/// A FLAC reader which iterates over decoded samples as signed integers
623///
624/// # Example
625///
626/// ```
627/// use flac_codec::{
628///     encode::{FlacSampleWriter, Options},
629///     decode::FlacSampleReader,
630/// };
631/// use std::io::{Cursor, Seek};
632///
633/// let mut flac = Cursor::new(vec![]);  // a FLAC file in memory
634///
635/// let mut writer = FlacSampleWriter::new(
636///     &mut flac,           // our wrapped writer
637///     Options::default(),  // default encoding options
638///     44100,               // sample rate
639///     16,                  // bits-per-sample
640///     1,                   // channel count
641///     Some(10),            // total samples
642/// ).unwrap();
643///
644/// // write 10 samples
645/// let written_samples = (0..10).collect::<Vec<i32>>();
646/// assert!(writer.write(&written_samples).is_ok());
647///
648/// // finalize writing file
649/// assert!(writer.finalize().is_ok());
650///
651/// flac.rewind().unwrap();
652///
653/// // open reader around written FLAC file
654/// let reader = FlacSampleReader::new(flac).unwrap();
655///
656/// // convert reader to iterator
657/// let mut iter = reader.into_iter();
658///
659/// // read all its samples
660/// let read_samples = iter.collect::<Result<Vec<_>, _>>().unwrap();
661///
662/// // ensure they match
663/// assert_eq!(read_samples, written_samples);
664/// assert_eq!(read_samples, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
665/// ```
666#[derive(Clone)]
667pub struct FlacSampleIterator<R> {
668    // the wrapped decoder
669    decoder: Decoder<R>,
670    // decoded sample buffer
671    buf: VecDeque<i32>,
672}
673
674impl<R: std::io::Read> Metadata for FlacSampleIterator<R> {
675    fn channel_count(&self) -> u8 {
676        self.decoder.channel_count().get()
677    }
678
679    fn sample_rate(&self) -> u32 {
680        self.decoder.sample_rate()
681    }
682
683    fn bits_per_sample(&self) -> u32 {
684        self.decoder.bits_per_sample()
685    }
686
687    fn total_samples(&self) -> Option<u64> {
688        self.decoder.total_samples().map(|s| s.get())
689    }
690
691    fn md5(&self) -> Option<&[u8; 16]> {
692        self.decoder.md5()
693    }
694}
695
696impl<R: std::io::Read> Iterator for FlacSampleIterator<R> {
697    type Item = Result<i32, Error>;
698
699    #[inline]
700    fn next(&mut self) -> Option<Result<i32, Error>> {
701        self.buf.pop_front().map_or_else(
702            || match self.decoder.read_frame() {
703                Ok(Some(frame)) => {
704                    self.buf.extend(frame.iter());
705                    self.buf.pop_front().map(Ok)
706                }
707                Err(e) => Some(Err(e)),
708                Ok(None) => None,
709            },
710            |i| Some(Ok(i)),
711        )
712    }
713}
714
715impl<R: std::io::Read + std::io::Seek, E: crate::byteorder::Endianness> std::io::Seek
716    for FlacByteReader<R, E>
717{
718    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
719        use std::cmp::Ordering;
720
721        let Self { decoder, buf, .. } = self;
722
723        let streaminfo = decoder.blocks.streaminfo();
724
725        let bytes_per_pcm_frame: u64 = (u32::from(streaminfo.bits_per_sample).div_ceil(8)
726            * u32::from(streaminfo.channels.get()))
727        .into();
728
729        // the desired absolute position in the stream, in bytes
730        let desired_pos: u64 = match pos {
731            std::io::SeekFrom::Start(pos) => pos,
732            std::io::SeekFrom::Current(pos) => {
733                // current position in bytes is current position in samples
734                // converted to bytes *minus* the un-consumed space in the buffer
735                // since the sample position is running ahead of the byte position
736                let original_pos: u64 =
737                    (decoder.current_sample * bytes_per_pcm_frame) - (buf.len() as u64);
738
739                match pos.cmp(&0) {
740                    Ordering::Less => {
741                        original_pos
742                            .checked_sub(pos.unsigned_abs())
743                            .ok_or(std::io::Error::new(
744                                std::io::ErrorKind::InvalidInput,
745                                "cannot seek below byte 0",
746                            ))?
747                    }
748                    Ordering::Equal => return Ok(original_pos),
749                    Ordering::Greater => {
750                        original_pos
751                            .checked_add(pos.unsigned_abs())
752                            .ok_or(std::io::Error::new(
753                                std::io::ErrorKind::InvalidInput,
754                                "seek offset too large",
755                            ))?
756                    }
757                }
758            }
759            std::io::SeekFrom::End(pos) => {
760                // if the total samples is unknown in streaminfo,
761                // we have no way to know where the file's end is
762                // (this is a very unusual case)
763                let max_pos: u64 = decoder.total_samples().map(|s| s.get()).ok_or_else(|| {
764                    std::io::Error::new(std::io::ErrorKind::NotSeekable, "total samples not known")
765                })?;
766
767                match pos.cmp(&0) {
768                    Ordering::Less => max_pos.checked_sub(pos.unsigned_abs()).ok_or_else(|| {
769                        std::io::Error::new(
770                            std::io::ErrorKind::InvalidInput,
771                            "cannot seek below byte 0",
772                        )
773                    })?,
774                    Ordering::Equal => max_pos,
775                    Ordering::Greater => {
776                        return Err(std::io::Error::new(
777                            std::io::ErrorKind::InvalidInput,
778                            "cannot seek beyond end of file",
779                        ));
780                    }
781                }
782            }
783        };
784
785        // perform seek in stream to the desired sample
786        // (this will usually be some position prior to the desired sample)
787        let mut new_pos = decoder.seek(
788            self.frames_start
789                .ok_or(std::io::Error::from(std::io::ErrorKind::NotSeekable))?,
790            desired_pos / bytes_per_pcm_frame,
791        )? * bytes_per_pcm_frame;
792
793        // seeking invalidates current buffer
794        buf.clear();
795
796        // skip bytes to reach desired sample
797        while new_pos < desired_pos {
798            use std::io::BufRead;
799
800            let buf = self.fill_buf()?;
801
802            if !buf.is_empty() {
803                let to_skip = (usize::try_from(desired_pos - new_pos).unwrap()).min(buf.len());
804                self.consume(to_skip);
805                new_pos += to_skip as u64;
806            } else {
807                // attempting to seek beyond the end of the FLAC file
808                return Err(std::io::Error::new(
809                    std::io::ErrorKind::UnexpectedEof,
810                    "stream exhausted before sample reached",
811                ));
812            }
813        }
814
815        Ok(desired_pos)
816    }
817}
818
819impl<R: std::io::Read + std::io::Seek> FlacSampleReader<R> {
820    /// Seeks to the given channel-independent sample
821    ///
822    /// The sample is relative to the beginning of the stream
823    pub fn seek(&mut self, sample: u64) -> Result<(), Error> {
824        let channels: u8 = self.channel_count();
825
826        // actual position, in channel-independent samples
827        let mut pos = self.decoder.seek(
828            self.frames_start
829                .ok_or(std::io::Error::from(std::io::ErrorKind::NotSeekable))?,
830            sample,
831        )?;
832
833        // seeking invalidates the current buffer
834        self.buf.clear();
835
836        // needed channel-independent samples
837        while sample > pos {
838            let buf = self.fill_buf()?;
839
840            // size of buf in channel-independent samples
841            match buf.len() / usize::from(channels) {
842                0 => {
843                    // read beyond end of stream
844                    return Err(Error::InvalidSeek);
845                }
846                buf_samples => {
847                    // amount of channel-independent samples to consume
848                    let to_consume = buf_samples.min((sample - pos).try_into().unwrap());
849
850                    // mark samples in buffer as consumed
851                    self.consume(to_consume * usize::from(channels));
852
853                    // advance current actual position
854                    pos += to_consume as u64;
855                }
856            }
857        }
858
859        Ok(())
860    }
861}
862
863/// A FLAC reader which outputs non-interleaved channels
864///
865/// # Example
866/// ```
867/// use flac_codec::{
868///     encode::{FlacChannelWriter, Options},
869///     decode::FlacChannelReader,
870/// };
871/// use std::io::{Cursor, Seek};
872///
873/// let mut flac = Cursor::new(vec![]);  // a FLAC file in memory
874///
875/// let mut writer = FlacChannelWriter::new(
876///     &mut flac,           // our wrapped writer
877///     Options::default(),  // default encoding options
878///     44100,               // sample rate
879///     16,                  // bits-per-sample
880///     2,                   // channel count
881///     Some(5),             // total channel-independent samples
882/// ).unwrap();
883///
884/// // write our samples, divided by channel
885/// let written_samples = vec![
886///     vec![1, 2, 3, 4, 5],
887///     vec![-1, -2, -3, -4, -5],
888/// ];
889/// assert!(writer.write(&written_samples).is_ok());
890///
891/// // finalize writing file
892/// assert!(writer.finalize().is_ok());
893///
894/// flac.rewind().unwrap();
895///
896/// // open reader around written FLAC file
897/// let mut reader = FlacChannelReader::new(flac).unwrap();
898///
899/// // read a buffer's worth of samples
900/// let read_samples = reader.fill_buf().unwrap();
901///
902/// // ensure the channels match
903/// assert_eq!(read_samples.len(), written_samples.len());
904/// assert_eq!(read_samples[0], written_samples[0]);
905/// assert_eq!(read_samples[1], written_samples[1]);
906/// ```
907#[derive(Clone)]
908pub struct FlacChannelReader<R> {
909    // the wrapped decoder
910    decoder: Decoder<R>,
911    // amount of consumed frames across all channels
912    consumed: usize,
913    // start of FLAC frames
914    frames_start: Option<u64>,
915}
916
917impl<R: std::io::Read> FlacChannelReader<R> {
918    /// Opens new FLAC reader which wraps the given reader
919    ///
920    /// The reader must be positioned at the start of the
921    /// FLAC stream.  If the file has non-FLAC data
922    /// at the beginning (such as ID3v2 tags), one
923    /// should skip such data before initializing a `FlacByteReader`.
924    #[inline]
925    pub fn new(mut reader: R) -> Result<Self, Error> {
926        let blocklist = BlockList::read(reader.by_ref())?;
927
928        Ok(Self {
929            decoder: Decoder::new(reader, blocklist),
930            consumed: 0,
931            frames_start: None,
932        })
933    }
934
935    /// Returns FLAC metadata blocks
936    #[inline]
937    pub fn metadata(&self) -> &BlockList {
938        self.decoder.metadata()
939    }
940
941    /// Returns complete buffer of all read samples
942    ///
943    /// Analogous to [`std::io::BufRead::fill_buf`], this should
944    /// be paired with [`FlacSampleReader::consume`] to
945    /// consume samples in the filled buffer once used.
946    ///
947    /// Returned samples are returned as a `Vec` of channel slices,
948    /// like: [[left₀ , left₁ , left₂ , …], [right₀ , right₁ , right₂ , …]]
949    ///
950    /// The returned buffer will always contain at least one channel.
951    /// All channel slices will always be the same length.
952    ///
953    /// # Errors
954    ///
955    /// Returns error if some error occurs reading FLAC file
956    /// to fill buffer.
957    #[inline]
958    pub fn fill_buf(&mut self) -> Result<Vec<&[i32]>, Error> {
959        if self.consumed < self.decoder.buf.pcm_frames() {
960            Ok(self
961                .decoder
962                .buf
963                .channels()
964                .map(|c| &c[self.consumed..])
965                .collect())
966        } else {
967            self.consumed = 0;
968            let channels = usize::from(self.decoder.channel_count().get());
969            match self.decoder.read_frame()? {
970                Some(frame) => Ok(frame.channels().collect()),
971                None => Ok(vec![&[]; channels]),
972            }
973        }
974    }
975
976    /// Informs the reader that `amt` channel-indepedent samples
977    /// have been consumed.
978    ///
979    /// Analagous to [`std::io::BufRead::consume`], which marks
980    /// samples as having been read.
981    ///
982    /// May panic if attempting to consume more bytes
983    /// than are available in the buffer.
984    #[inline]
985    pub fn consume(&mut self, amt: usize) {
986        self.consumed += amt;
987    }
988}
989
990impl<R: std::io::Read + std::io::Seek> FlacChannelReader<R> {
991    /// Opens a new seekable FLAC reader which wraps the given reader
992    ///
993    /// If a stream is both readable and seekable,
994    /// it's vital to use this method to open it if one
995    /// also wishes to seek within the FLAC stream.
996    /// Otherwise, an I/O error will result when attempting to seek.
997    ///
998    /// [`FlacChannelReader::open`] calls this method to ensure
999    /// all `File`-based streams are also seekable.
1000    ///
1001    /// The reader must be positioned at the start of the
1002    /// FLAC stream.  If the file has non-FLAC data
1003    /// at the beginning (such as ID3v2 tags), one
1004    /// should skip such data before initializing a `FlacChannelReader`.
1005    pub fn new_seekable(mut reader: R) -> Result<Self, Error> {
1006        let blocklist = BlockList::read(reader.by_ref())?;
1007        let frames_start = reader.stream_position()?;
1008
1009        Ok(Self {
1010            decoder: Decoder::new(reader, blocklist),
1011            consumed: 0,
1012            frames_start: Some(frames_start),
1013        })
1014    }
1015}
1016
1017impl FlacChannelReader<BufReader<File>> {
1018    /// Opens FLAC file from the given path
1019    #[inline]
1020    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
1021        FlacChannelReader::new_seekable(BufReader::new(File::open(path.as_ref())?))
1022    }
1023}
1024
1025impl<R: std::io::Read + std::io::Seek> FlacChannelReader<R> {
1026    /// Seeks to the given channel-independent sample
1027    ///
1028    /// The sample is relative to the beginning of the stream
1029    pub fn seek(&mut self, sample: u64) -> Result<(), Error> {
1030        // actual position, in channel-independent samples
1031        let mut pos = self.decoder.seek(
1032            self.frames_start
1033                .ok_or(std::io::Error::from(std::io::ErrorKind::NotSeekable))?,
1034            sample,
1035        )?;
1036
1037        // seeking invalidates the current samples consumed
1038        self.consumed = 0;
1039
1040        // needed channel-independent samples
1041        while sample > pos {
1042            let buf = self.fill_buf()?;
1043
1044            // size of buf in channel-independent samples
1045            match buf[0].len() {
1046                0 => {
1047                    // read beyond end of stream
1048                    return Err(Error::InvalidSeek);
1049                }
1050                buf_samples => {
1051                    // amount of channel-independent samples to consume
1052                    let to_consume = buf_samples.min((sample - pos).try_into().unwrap());
1053
1054                    // mark samples in buffer as consumed
1055                    self.consume(to_consume);
1056
1057                    // advance current actual position
1058                    pos += to_consume as u64;
1059                }
1060            }
1061        }
1062
1063        Ok(())
1064    }
1065}
1066
1067impl<R: std::io::Read> Metadata for FlacChannelReader<R> {
1068    #[inline]
1069    fn channel_count(&self) -> u8 {
1070        self.decoder.channel_count().get()
1071    }
1072
1073    #[inline]
1074    fn channel_mask(&self) -> ChannelMask {
1075        self.decoder.channel_mask()
1076    }
1077
1078    #[inline]
1079    fn sample_rate(&self) -> u32 {
1080        self.decoder.sample_rate()
1081    }
1082
1083    #[inline]
1084    fn bits_per_sample(&self) -> u32 {
1085        self.decoder.bits_per_sample()
1086    }
1087
1088    #[inline]
1089    fn total_samples(&self) -> Option<u64> {
1090        self.decoder.total_samples().map(|s| s.get())
1091    }
1092
1093    #[inline]
1094    fn md5(&self) -> Option<&[u8; 16]> {
1095        self.decoder.md5()
1096    }
1097}
1098
1099/// A FLAC reader which operates on streamed input
1100///
1101/// Streamed FLAC files are simply a collection of raw
1102/// FLAC frames with no accompanying metadata,
1103/// like might be delivered over a multicast stream.
1104///
1105/// Because this reader needs to scan the stream for
1106/// valid frame sync codes before playback,
1107/// it requires [`std::io::BufRead`] instead of [`std::io::Read`].
1108///
1109/// # Example
1110///
1111/// ```
1112/// use flac_codec::{
1113///     decode::{FlacStreamReader, FrameBuf},
1114///     encode::{FlacStreamWriter, Options},
1115/// };
1116/// use std::io::{Cursor, Seek};
1117/// use std::num::NonZero;
1118/// use bitstream_io::SignedBitCount;
1119///
1120/// let mut flac = Cursor::new(vec![]);
1121///
1122/// let samples = (0..100).collect::<Vec<i32>>();
1123///
1124/// let mut w = FlacStreamWriter::new(&mut flac, Options::default());
1125///
1126/// // write a single FLAC frame with some samples
1127/// w.write(
1128///     44100,  // sample rate
1129///     1,      // channels
1130///     16,     // bits-per-sample
1131///     &samples,
1132/// ).unwrap();
1133///
1134/// flac.rewind().unwrap();
1135///
1136/// let mut r = FlacStreamReader::new(&mut flac);
1137///
1138/// // read a single FLAC frame with some samples
1139/// assert_eq!(
1140///     r.read().unwrap(),
1141///     FrameBuf {
1142///         samples: &samples,
1143///         sample_rate: 44100,
1144///         channels: 1,
1145///         bits_per_sample: 16,
1146///     },
1147/// );
1148/// ```
1149pub struct FlacStreamReader<R> {
1150    // the wrapped reader
1151    reader: R,
1152    // raw decoded frame samples
1153    buf: Frame,
1154    // interlaced frame samples
1155    samples: Vec<i32>,
1156}
1157
1158impl<R: std::io::BufRead> FlacStreamReader<R> {
1159    /// Opens new FLAC stream reader which wraps the given reader
1160    #[inline]
1161    pub fn new(reader: R) -> Self {
1162        Self {
1163            reader,
1164            buf: Frame::default(),
1165            samples: Vec::default(),
1166        }
1167    }
1168
1169    /// Returns the next decoded FLAC frame and its parameters
1170    ///
1171    /// # Errors
1172    ///
1173    /// Returns an I/O error from the stream or if any
1174    /// other error occurs when reading the file.
1175    pub fn read(&mut self) -> Result<FrameBuf<'_>, Error> {
1176        use crate::crc::{Checksum, Crc16, CrcReader};
1177        use crate::stream::FrameHeader;
1178        use bitstream_io::{BigEndian, BitReader};
1179        use std::io::Read;
1180
1181        // Finding the next frame header in a BufRead is
1182        // tougher than it seems because fill_buf might
1183        // slice a frame sync code in half, which needs
1184        // to be accounted for.
1185
1186        let (header, mut crc16_reader) = loop {
1187            // scan for the first byte of the frame sync
1188            self.reader.skip_until(0b11111111)?;
1189
1190            // either gotten the first half of the frame sync,
1191            // or have reached EOF
1192
1193            // check that the next byte is the other half of a frame sync
1194            match self.reader.fill_buf() {
1195                Ok([]) => {
1196                    return Err(std::io::Error::new(
1197                        std::io::ErrorKind::UnexpectedEof,
1198                        "eof looking for frame sync",
1199                    )
1200                    .into());
1201                }
1202                Ok([byte, ..]) if byte >> 1 == 0b1111100 => {
1203                    // got a whole frame sync
1204                    // so try to parse a whole frame header
1205                    let mut crc_reader: CrcReader<_, Crc16> = CrcReader::new(
1206                        std::slice::from_ref(&0b11111111).chain(self.reader.by_ref()),
1207                    );
1208
1209                    if let Ok(header) = FrameHeader::read_subset(&mut crc_reader) {
1210                        break (header, crc_reader);
1211                    }
1212                }
1213                Ok(_) => continue,
1214                // didn't get the other half of frame sync,
1215                // so continue without consuming anything
1216                Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
1217                Err(e) => return Err(e.into()),
1218            }
1219        };
1220
1221        read_subframes(
1222            BitReader::endian(crc16_reader.by_ref(), BigEndian),
1223            &header,
1224            &mut self.buf,
1225        )?;
1226
1227        if crc16_reader.into_checksum().valid() {
1228            self.samples.clear();
1229            self.samples.extend(self.buf.iter());
1230
1231            Ok(FrameBuf {
1232                samples: self.samples.as_slice(),
1233                sample_rate: header.sample_rate.into(),
1234                channels: header.channel_assignment.count(),
1235                bits_per_sample: header.bits_per_sample.into(),
1236            })
1237        } else {
1238            Err(Error::Crc16Mismatch)
1239        }
1240    }
1241}
1242
1243/// A buffer of samples read from a [`FlacStreamReader`]
1244///
1245/// In a conventional FLAC reader, the stream's metadata
1246/// is known in advance from the required STREAMINFO metadata block
1247/// and is an error for it to change mid-file.
1248///
1249/// In a streamed reader, that metadata isn't known in advance
1250/// and can change from frame to frame.  This buffer contains
1251/// all the metadata fields in the frame for decoding/playback.
1252#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1253pub struct FrameBuf<'s> {
1254    /// Decoded samples
1255    ///
1256    /// Samples are interleaved by channel, like:
1257    /// [left₀ , right₀ , left₁ , right₁ , left₂ , right₂ , …]
1258    pub samples: &'s [i32],
1259
1260    /// The sample rate, in Hz
1261    pub sample_rate: u32,
1262
1263    /// Channel count, from 1 to 8
1264    pub channels: u8,
1265
1266    /// Bits-per-sample, from 4 to 32
1267    pub bits_per_sample: u32,
1268}
1269
1270/// The results of FLAC file verification
1271#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
1272pub enum Verified {
1273    /// FLAC file has MD5 hash and decoded contents match that hash
1274    MD5Match,
1275    /// FLAC file has MD5 hash, but decoded contents do not match
1276    MD5Mismatch,
1277    /// FLAC file has no MD5 hash, but decodes successfully
1278    NoMD5,
1279}
1280
1281/// Verifies FLAC file for correctness
1282pub fn verify<P: AsRef<Path>>(p: P) -> Result<Verified, Error> {
1283    File::open(p.as_ref())
1284        .map_err(Error::Io)
1285        .and_then(|r| verify_reader(BufReader::new(r)))
1286}
1287
1288/// Verifies FLAC stream for correctness
1289///
1290/// The stream must be set to the start of the FLAC data
1291pub fn verify_reader<R: std::io::Read>(r: R) -> Result<Verified, Error> {
1292    use crate::byteorder::LittleEndian;
1293
1294    let mut r = FlacByteReader::endian(r, LittleEndian)?;
1295    match r.md5().cloned() {
1296        Some(flac_md5) => {
1297            let mut output_md5 = md5::Context::new();
1298            std::io::copy(&mut r, &mut output_md5)?;
1299            Ok(if flac_md5 == output_md5.finalize().0 {
1300                Verified::MD5Match
1301            } else {
1302                Verified::MD5Mismatch
1303            })
1304        }
1305        None => std::io::copy(&mut r, &mut std::io::sink())
1306            .map(|_| Verified::NoMD5)
1307            .map_err(Error::Io),
1308    }
1309}
1310
1311/// A FLAC decoder
1312#[derive(Clone)]
1313struct Decoder<R> {
1314    reader: R,
1315    // all metadata blocks
1316    blocks: BlockList,
1317    // // the size of everything before the first frame, in bytes
1318    // frames_start: u64,
1319    // the current sample, in channel-independent samples
1320    current_sample: u64,
1321    // raw decoded frame samples
1322    buf: Frame,
1323}
1324
1325impl<R: std::io::Read> Decoder<R> {
1326    /// Builds a new FLAC decoder from the given stream
1327    ///
1328    /// This assumes the stream is positioned at the start
1329    /// of the file.
1330    ///
1331    /// # Errors
1332    ///
1333    /// Returns an error of the initial FLAC metadata
1334    /// is invalid or an I/O error occurs reading
1335    /// the initial metadata.
1336    fn new(reader: R, blocks: BlockList) -> Self {
1337        Self {
1338            reader,
1339            blocks,
1340            current_sample: 0,
1341            buf: Frame::default(),
1342        }
1343    }
1344
1345    /// Returns channel count
1346    ///
1347    /// From 1 to 8
1348    fn channel_count(&self) -> NonZero<u8> {
1349        self.blocks.streaminfo().channels
1350    }
1351
1352    fn channel_mask(&self) -> ChannelMask {
1353        self.blocks.channel_mask()
1354    }
1355
1356    /// Returns sample rate, in Hz
1357    fn sample_rate(&self) -> u32 {
1358        self.blocks.streaminfo().sample_rate
1359    }
1360
1361    /// Returns decoder's bits-per-sample
1362    ///
1363    /// From 1 to 32
1364    fn bits_per_sample(&self) -> u32 {
1365        self.blocks.streaminfo().bits_per_sample.into()
1366    }
1367
1368    /// Returns total number of channel-independent samples, if known
1369    fn total_samples(&self) -> Option<NonZero<u64>> {
1370        self.blocks.streaminfo().total_samples
1371    }
1372
1373    /// Returns MD5 of entire stream, if known
1374    fn md5(&self) -> Option<&[u8; 16]> {
1375        self.blocks.streaminfo().md5.as_ref()
1376    }
1377
1378    /// Returns FLAC metadata
1379    fn metadata(&self) -> &BlockList {
1380        &self.blocks
1381    }
1382
1383    /// Returns decoded frame, if any.
1384    ///
1385    /// # Errors
1386    ///
1387    /// Returns any decoding error from the stream.
1388    fn read_frame(&mut self) -> Result<Option<&Frame>, Error> {
1389        use crate::crc::{Checksum, Crc16, CrcReader};
1390        use crate::stream::FrameHeader;
1391        use bitstream_io::{BigEndian, BitReader};
1392        use std::io::Read;
1393
1394        let mut crc16_reader: CrcReader<_, Crc16> = CrcReader::new(self.reader.by_ref());
1395
1396        let header = match self
1397            .blocks
1398            .streaminfo()
1399            .total_samples
1400            .map(|total| total.get() - self.current_sample)
1401        {
1402            Some(0) => return Ok(None),
1403            Some(remaining) => FrameHeader::read(crc16_reader.by_ref(), self.blocks.streaminfo())
1404                .and_then(|header| {
1405                // only the last block in a stream may contain <= 14 samples
1406                let block_size = u16::from(header.block_size);
1407                (u64::from(block_size) == remaining || block_size > 14)
1408                    .then_some(header)
1409                    .ok_or(Error::ShortBlock)
1410            })?,
1411            // if total number of remaining samples isn't known,
1412            // treat an EOF error as the end of stream
1413            // (this is an uncommon case)
1414            None => match FrameHeader::read(crc16_reader.by_ref(), self.blocks.streaminfo()) {
1415                Ok(header) => header,
1416                Err(Error::Io(err)) if err.kind() == std::io::ErrorKind::UnexpectedEof => {
1417                    return Ok(None);
1418                }
1419                Err(err) => return Err(err),
1420            },
1421        };
1422
1423        read_subframes(
1424            BitReader::endian(crc16_reader.by_ref(), BigEndian),
1425            &header,
1426            &mut self.buf,
1427        )?;
1428
1429        if !crc16_reader.into_checksum().valid() {
1430            return Err(Error::Crc16Mismatch);
1431        }
1432
1433        self.current_sample += u64::from(u16::from(header.block_size));
1434
1435        Ok(Some(&self.buf))
1436    }
1437}
1438
1439impl<R: std::io::Seek> Decoder<R> {
1440    /// Attempts to seek to desired sample number
1441    ///
1442    /// Sample number is indicated in channel-independent samples.
1443    ///
1444    /// Upon success, returns the actual sample number
1445    /// the stream is positioned to, in channel-independent samples,
1446    /// which may be less than the desired sample.
1447    ///
1448    /// # Errors
1449    ///
1450    /// Passes along an I/O error that occurs when seeking
1451    /// within the file.
1452    fn seek(&mut self, frames_start: u64, sample: u64) -> Result<u64, Error> {
1453        use crate::metadata::SeekPoint;
1454        use std::io::SeekFrom;
1455
1456        match self.blocks.get() {
1457            Some(SeekTable { points: seektable }) => {
1458                match seektable.iter().rfind(|point| {
1459                    point
1460                        .sample_offset()
1461                        .map(|offset| offset <= sample)
1462                        .unwrap_or(false)
1463                }) {
1464                    Some(SeekPoint::Defined {
1465                        sample_offset,
1466                        byte_offset,
1467                        ..
1468                    }) => {
1469                        assert!(*sample_offset <= sample);
1470                        self.reader
1471                            .seek(SeekFrom::Start(frames_start + byte_offset))?;
1472                        self.current_sample = *sample_offset;
1473                        Ok(*sample_offset)
1474                    }
1475                    _ => {
1476                        // empty seektable so rewind to start of stream
1477                        self.reader.seek(SeekFrom::Start(frames_start))?;
1478                        self.current_sample = 0;
1479                        Ok(0)
1480                    }
1481                }
1482            }
1483            None => {
1484                // no seektable
1485                // all we can do is rewind data to start of stream
1486                self.reader.seek(SeekFrom::Start(frames_start))?;
1487                self.current_sample = 0;
1488                Ok(0)
1489            }
1490        }
1491    }
1492}
1493
1494fn read_subframes<R: BitRead>(
1495    mut reader: R,
1496    header: &crate::stream::FrameHeader,
1497    buf: &mut Frame,
1498) -> Result<(), Error> {
1499    use crate::stream::ChannelAssignment;
1500
1501    match header.channel_assignment {
1502        ChannelAssignment::Independent(total_channels) => {
1503            buf.resized_channels(
1504                header.bits_per_sample.into(),
1505                total_channels.into(),
1506                u16::from(header.block_size).into(),
1507            )
1508            .try_for_each(|channel| {
1509                read_subframe(&mut reader, header.bits_per_sample.into(), channel)
1510            })?;
1511        }
1512        ChannelAssignment::LeftSide => {
1513            let (left, side) = buf.resized_stereo(
1514                header.bits_per_sample.into(),
1515                u16::from(header.block_size).into(),
1516            );
1517
1518            read_subframe(&mut reader, header.bits_per_sample.into(), left)?;
1519
1520            match header.bits_per_sample.checked_add(1) {
1521                Some(side_bps) => {
1522                    read_subframe(&mut reader, side_bps, side)?;
1523
1524                    left.iter().zip(side.iter_mut()).for_each(|(left, side)| {
1525                        *side = *left - *side;
1526                    });
1527                }
1528                None => {
1529                    // the very rare case of 32-bps streams
1530                    // accompanied by side channels
1531                    let mut side_i64 = vec![0; side.len()];
1532
1533                    read_subframe::<33, R, i64>(
1534                        &mut reader,
1535                        SignedBitCount::from(header.bits_per_sample)
1536                            .checked_add(1)
1537                            .expect("excessive bps for substream"),
1538                        &mut side_i64,
1539                    )?;
1540
1541                    left.iter().zip(side_i64).zip(side.iter_mut()).for_each(
1542                        |((left, side_i64), side)| {
1543                            *side = (*left as i64 - side_i64) as i32;
1544                        },
1545                    );
1546                }
1547            }
1548        }
1549        ChannelAssignment::SideRight => {
1550            let (side, right) = buf.resized_stereo(
1551                header.bits_per_sample.into(),
1552                u16::from(header.block_size).into(),
1553            );
1554
1555            match header.bits_per_sample.checked_add(1) {
1556                Some(side_bps) => {
1557                    read_subframe(&mut reader, side_bps, side)?;
1558                    read_subframe(&mut reader, header.bits_per_sample.into(), right)?;
1559
1560                    side.iter_mut().zip(right.iter()).for_each(|(side, right)| {
1561                        *side += *right;
1562                    });
1563                }
1564                None => {
1565                    // the very rare case of 32-bps streams
1566                    // accompanied by side channels
1567                    let mut side_i64 = vec![0; side.len()];
1568
1569                    read_subframe::<33, R, i64>(
1570                        &mut reader,
1571                        SignedBitCount::from(header.bits_per_sample)
1572                            .checked_add(1)
1573                            .expect("excessive bps for substream"),
1574                        &mut side_i64,
1575                    )?;
1576                    read_subframe(&mut reader, header.bits_per_sample.into(), right)?;
1577
1578                    side.iter_mut().zip(side_i64).zip(right.iter()).for_each(
1579                        |((side, side_64), right)| {
1580                            *side = (side_64 + *right as i64) as i32;
1581                        },
1582                    );
1583                }
1584            }
1585        }
1586        ChannelAssignment::MidSide => {
1587            let (mid, side) = buf.resized_stereo(
1588                header.bits_per_sample.into(),
1589                u16::from(header.block_size).into(),
1590            );
1591
1592            read_subframe(&mut reader, header.bits_per_sample.into(), mid)?;
1593
1594            match header.bits_per_sample.checked_add(1) {
1595                Some(side_bps) => {
1596                    read_subframe(&mut reader, side_bps, side)?;
1597
1598                    mid.iter_mut().zip(side.iter_mut()).for_each(|(mid, side)| {
1599                        let sum = *mid * 2 + side.abs() % 2;
1600                        *mid = (sum + *side) >> 1;
1601                        *side = (sum - *side) >> 1;
1602                    });
1603                }
1604                None => {
1605                    // the very rare case of 32-bps streams
1606                    // accompanied by side channels
1607                    let mut side_i64 = vec![0; side.len()];
1608
1609                    read_subframe::<33, R, i64>(
1610                        &mut reader,
1611                        SignedBitCount::from(header.bits_per_sample)
1612                            .checked_add(1)
1613                            .expect("excessive bps for substream"),
1614                        &mut side_i64,
1615                    )?;
1616
1617                    mid.iter_mut().zip(side.iter_mut()).zip(side_i64).for_each(
1618                        |((mid, side), side_i64)| {
1619                            let sum = *mid as i64 * 2 + (side_i64.abs() % 2);
1620                            *mid = ((sum + side_i64) >> 1) as i32;
1621                            *side = ((sum - side_i64) >> 1) as i32;
1622                        },
1623                    );
1624                }
1625            }
1626        }
1627    }
1628
1629    reader.byte_align();
1630    reader.skip(16)?; // CRC-16 checksum
1631
1632    Ok(())
1633}
1634
1635fn read_subframe<const MAX: u32, R: BitRead, I: SignedInteger>(
1636    reader: &mut R,
1637    bits_per_sample: SignedBitCount<MAX>,
1638    channel: &mut [I],
1639) -> Result<(), Error> {
1640    use crate::stream::{SubframeHeader, SubframeHeaderType};
1641
1642    let header = reader.parse::<SubframeHeader>()?;
1643
1644    let effective_bps = bits_per_sample
1645        .checked_sub::<MAX>(header.wasted_bps)
1646        .ok_or(Error::ExcessiveWastedBits)?;
1647
1648    match header.type_ {
1649        SubframeHeaderType::Constant => {
1650            channel.fill(reader.read_signed_counted(effective_bps)?);
1651        }
1652        SubframeHeaderType::Verbatim => {
1653            channel.iter_mut().try_for_each(|i| {
1654                *i = reader.read_signed_counted(effective_bps)?;
1655                Ok::<(), Error>(())
1656            })?;
1657        }
1658        SubframeHeaderType::Fixed { order } => {
1659            read_fixed_subframe(
1660                reader,
1661                effective_bps,
1662                SubframeHeaderType::FIXED_COEFFS[order as usize],
1663                channel,
1664            )?;
1665        }
1666        SubframeHeaderType::Lpc { order } => {
1667            read_lpc_subframe(reader, effective_bps, order, channel)?;
1668        }
1669    }
1670
1671    if header.wasted_bps > 0 {
1672        channel.iter_mut().for_each(|i| *i <<= header.wasted_bps);
1673    }
1674
1675    Ok(())
1676}
1677
1678fn read_fixed_subframe<const MAX: u32, R: BitRead, I: SignedInteger>(
1679    reader: &mut R,
1680    bits_per_sample: SignedBitCount<MAX>,
1681    coefficients: &[i64],
1682    channel: &mut [I],
1683) -> Result<(), Error> {
1684    let (warm_up, residuals) = channel
1685        .split_at_mut_checked(coefficients.len())
1686        .ok_or(Error::InvalidFixedOrder)?;
1687
1688    warm_up.iter_mut().try_for_each(|s| {
1689        *s = reader.read_signed_counted(bits_per_sample)?;
1690        Ok::<_, std::io::Error>(())
1691    })?;
1692
1693    read_residuals(reader, coefficients.len(), residuals)?;
1694    predict(coefficients, 0, channel);
1695    Ok(())
1696}
1697
1698fn read_lpc_subframe<const MAX: u32, R: BitRead, I: SignedInteger>(
1699    reader: &mut R,
1700    bits_per_sample: SignedBitCount<MAX>,
1701    predictor_order: NonZero<u8>,
1702    channel: &mut [I],
1703) -> Result<(), Error> {
1704    let mut coefficients: [i64; 32] = [0; 32];
1705
1706    let (warm_up, residuals) = channel
1707        .split_at_mut_checked(predictor_order.get().into())
1708        .ok_or(Error::InvalidLpcOrder)?;
1709
1710    warm_up.iter_mut().try_for_each(|s| {
1711        *s = reader.read_signed_counted(bits_per_sample)?;
1712        Ok::<_, std::io::Error>(())
1713    })?;
1714
1715    let qlp_precision: SignedBitCount<15> = reader
1716        .read_count::<0b1111>()?
1717        .checked_add(1)
1718        .and_then(|c| c.signed_count())
1719        .ok_or(Error::InvalidQlpPrecision)?;
1720
1721    let qlp_shift: u32 = reader
1722        .read::<5, i32>()?
1723        .try_into()
1724        .map_err(|_| Error::NegativeLpcShift)?;
1725
1726    let coefficients = &mut coefficients[0..predictor_order.get().into()];
1727
1728    coefficients.iter_mut().try_for_each(|c| {
1729        *c = reader.read_signed_counted(qlp_precision)?;
1730        Ok::<_, std::io::Error>(())
1731    })?;
1732
1733    read_residuals(reader, coefficients.len(), residuals)?;
1734    predict(coefficients, qlp_shift, channel);
1735    Ok(())
1736}
1737
1738fn predict<I: SignedInteger>(coefficients: &[i64], qlp_shift: u32, channel: &mut [I]) {
1739    for split in coefficients.len()..channel.len() {
1740        let (predicted, residuals) = channel.split_at_mut(split);
1741
1742        residuals[0] += I::from_i64(
1743            predicted
1744                .iter()
1745                .rev()
1746                .zip(coefficients)
1747                .map(|(x, y)| (*x).into() * y)
1748                .sum::<i64>()
1749                >> qlp_shift,
1750        );
1751    }
1752}
1753
1754#[test]
1755fn verify_prediction() {
1756    let mut coefficients = [-75, 166, 121, -269, -75, -399, 1042];
1757    let mut buffer = [
1758        -796, -547, -285, -32, 199, 443, 670, -2, -23, 14, 6, 3, -4, 12, -2, 10,
1759    ];
1760    coefficients.reverse();
1761    predict(&coefficients, 9, &mut buffer);
1762    assert_eq!(
1763        &buffer,
1764        &[
1765            -796, -547, -285, -32, 199, 443, 670, 875, 1046, 1208, 1343, 1454, 1541, 1616, 1663,
1766            1701
1767        ]
1768    );
1769
1770    let mut coefficients = [119, -255, 555, -836, 879, -1199, 1757];
1771    let mut buffer = [-21363, -21951, -22649, -24364, -27297, -26870, -30017, 3157];
1772    coefficients.reverse();
1773    predict(&coefficients, 10, &mut buffer);
1774    assert_eq!(
1775        &buffer,
1776        &[
1777            -21363, -21951, -22649, -24364, -27297, -26870, -30017, -29718
1778        ]
1779    );
1780
1781    let mut coefficients = [
1782        709, -2589, 4600, -4612, 1350, 4220, -9743, 12671, -12129, 8586, -3775, -645, 3904, -5543,
1783        4373, 182, -6873, 13265, -15417, 11550,
1784    ];
1785    let mut buffer = [
1786        213238, 210830, 234493, 209515, 235139, 201836, 208151, 186277, 157720, 148176, 115037,
1787        104836, 60794, 54523, 412, 17943, -6025, -3713, 8373, 11764, 30094,
1788    ];
1789    coefficients.reverse();
1790    predict(&coefficients, 12, &mut buffer);
1791    assert_eq!(
1792        &buffer,
1793        &[
1794            213238, 210830, 234493, 209515, 235139, 201836, 208151, 186277, 157720, 148176, 115037,
1795            104836, 60794, 54523, 412, 17943, -6025, -3713, 8373, 11764, 33931,
1796        ]
1797    );
1798}
1799
1800fn read_residuals<R: BitRead, I: SignedInteger>(
1801    reader: &mut R,
1802    predictor_order: usize,
1803    residuals: &mut [I],
1804) -> Result<(), Error> {
1805    fn read_block<const RICE_MAX: u32, R: BitRead, I: SignedInteger>(
1806        reader: &mut R,
1807        predictor_order: usize,
1808        residuals: &mut [I],
1809    ) -> Result<(), Error> {
1810        use crate::stream::ResidualPartitionHeader;
1811
1812        let block_size = predictor_order + residuals.len();
1813        let partition_order = reader.read::<4, u32>()?;
1814        let partition_count = 1 << partition_order;
1815
1816        let partitions = residuals.rchunks_mut(block_size / partition_count).rev();
1817
1818        if partitions.len() != partition_count {
1819            return Err(Error::InvalidPartitionOrder);
1820        }
1821        for partition in partitions {
1822            match reader.parse()? {
1823                ResidualPartitionHeader::Standard { rice } => {
1824                    partition.iter_mut().try_for_each(|s| {
1825                        let msb = reader.read_unary::<1>()?;
1826                        let lsb = reader.read_counted::<RICE_MAX, u32>(rice)?;
1827                        let unsigned = (msb << u32::from(rice)) | lsb;
1828                        *s = if (unsigned & 1) == 1 {
1829                            -(I::from_u32(unsigned >> 1)) - I::ONE
1830                        } else {
1831                            I::from_u32(unsigned >> 1)
1832                        };
1833                        Ok::<(), std::io::Error>(())
1834                    })?;
1835                }
1836                ResidualPartitionHeader::Escaped { escape_size } => {
1837                    partition.iter_mut().try_for_each(|s| {
1838                        *s = reader.read_signed_counted(escape_size)?;
1839                        Ok::<(), std::io::Error>(())
1840                    })?;
1841                }
1842                ResidualPartitionHeader::Constant => {
1843                    partition.fill(I::ZERO);
1844                }
1845            }
1846        }
1847
1848        Ok(())
1849    }
1850
1851    match reader.read::<2, u8>()? {
1852        0 => read_block::<0b1111, R, I>(reader, predictor_order, residuals),
1853        1 => read_block::<0b11111, R, I>(reader, predictor_order, residuals),
1854        _ => Err(Error::InvalidCodingMethod),
1855    }
1856}