flac_codec/
stream.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 handling common FLAC stream items
10//!
11//! Many items are capitalized simply because they were capitalized
12//! in the original FLAC format documentation.
13
14use crate::Error;
15use crate::crc::{Checksum, Crc16, CrcReader, CrcWriter};
16use crate::metadata::Streaminfo;
17use bitstream_io::{
18    BitCount, BitRead, BitWrite, FromBitStream, FromBitStreamUsing, FromBitStreamWith,
19    SignedBitCount, ToBitStream, ToBitStreamUsing, ToBitStreamWith,
20};
21use std::num::NonZero;
22
23/// A common trait for signed integers
24pub trait SignedInteger: private::SignedInteger {}
25
26impl SignedInteger for i32 {}
27
28impl private::SignedInteger for i32 {
29    #[inline]
30    fn from_u32(u: u32) -> Self {
31        u as i32
32    }
33
34    #[inline]
35    fn to_u32(self) -> u32 {
36        self as u32
37    }
38
39    fn from_i64(i: i64) -> Self {
40        i as i32
41    }
42}
43
44impl SignedInteger for i64 {}
45
46impl private::SignedInteger for i64 {
47    #[inline]
48    fn from_u32(u: u32) -> Self {
49        u as i64
50    }
51
52    #[inline]
53    fn to_u32(self) -> u32 {
54        self as u32
55    }
56
57    #[inline]
58    fn from_i64(i: i64) -> Self {
59        i
60    }
61}
62
63mod private {
64    /// A common trait for signed integers
65    pub trait SignedInteger:
66        bitstream_io::SignedInteger
67        + std::ops::Shl<Output = Self>
68        + std::ops::Neg<Output = Self>
69        + std::ops::AddAssign
70        + Into<i64>
71        + std::fmt::Display
72    {
73        /// Unconditionally converts a u32 to ourself
74        fn from_u32(u: u32) -> Self;
75
76        /// Unconditionally converts ourself to u32
77        fn to_u32(self) -> u32;
78
79        /// Unconditionally converts i64 to ourself
80        fn from_i64(i: i64) -> Self;
81    }
82}
83
84/// A FLAC frame header
85///
86/// | Bits      | Field |
87/// |----------:|-------|
88/// | 15        | sync code (`0b111111111111100`)
89/// | 1         | `blocking_strategy`
90/// | 4         | `block_size`
91/// | 4         | `sample_rate`
92/// | 4         | `channel_assignment`
93/// | 3         | `bits_per_sample`
94/// | 1         | padding (0)
95/// | 8-56      | `frame_number`
96/// | (8 or 16) | uncommon block size
97/// | (8 or 16) | uncommon sample rate
98/// | 8         | CRC-8 of header data
99///
100/// # Example
101/// ```
102/// use flac_codec::stream::{
103///     FrameHeader, BlockSize, SampleRate, ChannelAssignment,
104///     Independent, BitsPerSample, FrameNumber,
105/// };
106///
107/// let mut data: &[u8] = &[
108///     0b11111111, 0b1111100_0,  // sync code + blocking
109///     0b0110_1001,              // block size + sample rate
110///     0b0000_100_0,             // channels + bps + pad
111///     0x00,                     // frame number
112///     0x13,                     // uncommon block size (+1)
113///     0x64,                     // CRC-8
114/// ];
115///
116/// assert_eq!(
117///     FrameHeader::read_subset(&mut data).unwrap(),
118///     FrameHeader {
119///         blocking_strategy: false,
120///         block_size: BlockSize::Uncommon8(20),
121///         sample_rate: SampleRate::Hz44100,
122///         channel_assignment: ChannelAssignment::Independent(
123///             Independent::Mono
124///         ),
125///         bits_per_sample: BitsPerSample::Bps16,
126///         frame_number: FrameNumber(0),
127///     },
128/// );
129/// ```
130#[derive(Debug, Eq, PartialEq)]
131pub struct FrameHeader {
132    /// The blocking strategy bit
133    pub blocking_strategy: bool,
134    /// The block size, in samples
135    pub block_size: BlockSize<u16>,
136    /// The sample rate, in Hz
137    pub sample_rate: SampleRate<u32>,
138    /// How the channels are assigned
139    pub channel_assignment: ChannelAssignment,
140    /// The number if bits per output sample
141    // pub bits_per_sample: SignedBitCount<32>,
142    pub bits_per_sample: BitsPerSample,
143    /// The frame's number in the stream
144    pub frame_number: FrameNumber,
145}
146
147impl FrameHeader {
148    const SYNC_CODE: u32 = 0b111111111111100;
149
150    /// Reads new header from the given reader
151    pub fn read<R: std::io::Read>(reader: &mut R, streaminfo: &Streaminfo) -> Result<Self, Error> {
152        use crate::crc::{Checksum, Crc8, CrcReader};
153        use bitstream_io::{BigEndian, BitReader};
154        use std::io::Read;
155
156        let mut crc8: CrcReader<_, Crc8> = CrcReader::new(reader);
157        BitReader::endian(crc8.by_ref(), BigEndian)
158            .parse_with(streaminfo)
159            .and_then(|header| {
160                crc8.into_checksum()
161                    .valid()
162                    .then_some(header)
163                    .ok_or(Error::Crc8Mismatch)
164            })
165    }
166
167    /// Reads new header from the given reader
168    pub fn read_subset<R: std::io::Read>(reader: &mut R) -> Result<Self, Error> {
169        use crate::crc::{Checksum, Crc8, CrcReader};
170        use bitstream_io::{BigEndian, BitReader};
171        use std::io::Read;
172
173        let mut crc8: CrcReader<_, Crc8> = CrcReader::new(reader);
174        BitReader::endian(crc8.by_ref(), BigEndian)
175            .parse()
176            .and_then(|header| {
177                crc8.into_checksum()
178                    .valid()
179                    .then_some(header)
180                    .ok_or(Error::Crc8Mismatch)
181            })
182    }
183
184    /// Builds header to the given writer
185    pub fn write<W: std::io::Write>(
186        &self,
187        writer: &mut W,
188        streaminfo: &Streaminfo,
189    ) -> Result<(), Error> {
190        use crate::crc::{Crc8, CrcWriter};
191        use bitstream_io::{BigEndian, BitWriter};
192        use std::io::Write;
193
194        let mut crc8: CrcWriter<_, Crc8> = CrcWriter::new(writer.by_ref());
195        BitWriter::endian(crc8.by_ref(), BigEndian).build_with(self, streaminfo)?;
196        let crc8 = crc8.into_checksum().into();
197        writer.write_all(std::slice::from_ref(&crc8))?;
198        Ok(())
199    }
200
201    /// Builds header to the given writer
202    pub fn write_subset<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
203        use crate::crc::{Crc8, CrcWriter};
204        use bitstream_io::{BigEndian, BitWriter};
205        use std::io::Write;
206
207        let mut crc8: CrcWriter<_, Crc8> = CrcWriter::new(writer.by_ref());
208        BitWriter::endian(crc8.by_ref(), BigEndian).build(self)?;
209        let crc8 = crc8.into_checksum().into();
210        writer.write_all(std::slice::from_ref(&crc8))?;
211        Ok(())
212    }
213
214    fn parse<R: BitRead + ?Sized>(
215        r: &mut R,
216        non_subset_rate: Option<u32>,
217        non_subset_bps: Option<SignedBitCount<32>>,
218    ) -> Result<Self, Error> {
219        r.read_const::<15, { Self::SYNC_CODE }, _>(Error::InvalidSyncCode)?;
220        let blocking_strategy = r.read_bit()?;
221        let encoded_block_size = r.parse()?;
222        let encoded_sample_rate = r.parse_using(non_subset_rate)?;
223        let channel_assignment = r.parse()?;
224        let bits_per_sample = r.parse_using(non_subset_bps)?;
225        r.skip(1)?;
226        let frame_number = r.parse()?;
227
228        let frame_header = Self {
229            blocking_strategy,
230            frame_number,
231            block_size: r.parse_using(encoded_block_size)?,
232            sample_rate: r.parse_using(encoded_sample_rate)?,
233            channel_assignment,
234            bits_per_sample,
235        };
236
237        r.skip(8)?; // CRC-8
238
239        Ok(frame_header)
240    }
241
242    fn build<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
243        w.write_const::<15, { Self::SYNC_CODE }>()?;
244        w.write_bit(self.blocking_strategy)?;
245        w.build(&self.block_size)?;
246        w.build(&self.sample_rate)?;
247        w.build(&self.channel_assignment)?;
248        w.build(&self.bits_per_sample)?;
249        w.pad(1)?;
250        w.build(&self.frame_number)?;
251
252        // uncommon block size
253        match self.block_size {
254            BlockSize::Uncommon8(size) => {
255                w.write::<8, _>(size.checked_sub(1).ok_or(Error::InvalidBlockSize)?)?
256            }
257            BlockSize::Uncommon16(size) => {
258                w.write::<16, _>(size.checked_sub(1).ok_or(Error::InvalidBlockSize)?)?
259            }
260            _ => { /* do nothing */ }
261        }
262
263        // uncommon sample rate
264        match self.sample_rate {
265            SampleRate::KHz(rate) => w.write::<8, _>(rate / 1000)?,
266            SampleRate::Hz(rate) => {
267                w.write::<16, _>(rate)?;
268            }
269            SampleRate::DHz(rate) => {
270                w.write::<16, _>(rate / 10)?;
271            }
272            _ => { /* do nothing */ }
273        }
274
275        Ok(())
276    }
277}
278
279impl FromBitStreamWith<'_> for FrameHeader {
280    type Error = Error;
281    type Context = Streaminfo;
282
283    fn from_reader<R: BitRead + ?Sized>(
284        r: &mut R,
285        streaminfo: &Streaminfo,
286    ) -> Result<Self, Self::Error> {
287        FrameHeader::parse(
288            r,
289            Some(streaminfo.sample_rate),
290            Some(streaminfo.bits_per_sample),
291        )
292        .and_then(|h| {
293            (u16::from(h.block_size) <= streaminfo.maximum_block_size)
294                .then_some(h)
295                .ok_or(Error::BlockSizeMismatch)
296        })
297        .and_then(|h| {
298            (u32::from(h.sample_rate) == streaminfo.sample_rate)
299                .then_some(h)
300                .ok_or(Error::SampleRateMismatch)
301        })
302        .and_then(|h| {
303            (h.channel_assignment.count() == streaminfo.channels.get())
304                .then_some(h)
305                .ok_or(Error::ChannelsMismatch)
306        })
307        .and_then(|h| {
308            (h.bits_per_sample == streaminfo.bits_per_sample)
309                .then_some(h)
310                .ok_or(Error::BitsPerSampleMismatch)
311        })
312    }
313}
314
315impl FromBitStream for FrameHeader {
316    type Error = Error;
317
318    #[inline]
319    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error> {
320        FrameHeader::parse(r, None, None)
321    }
322}
323
324impl ToBitStreamWith<'_> for FrameHeader {
325    type Error = Error;
326    type Context = Streaminfo;
327
328    #[inline]
329    fn to_writer<W: BitWrite + ?Sized>(
330        &self,
331        w: &mut W,
332        _streaminfo: &Streaminfo,
333    ) -> Result<(), Self::Error> {
334        self.build(w)
335    }
336}
337
338impl ToBitStream for FrameHeader {
339    type Error = Error;
340
341    #[inline]
342    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
343        self.build(w)
344    }
345}
346
347/// Possible block sizes in a FLAC frame, in samples
348///
349/// Common sizes are stored as a 4-bit value,
350/// while uncommon sizes are stored as 8 or 16 bit values.
351///
352/// | Bits   | Block Size |
353/// |-------:|------------|
354/// | `0000` | invalid
355/// | `0001` | 192
356/// | `0010` | 576
357/// | `0011` | 1152
358/// | `0100` | 2304
359/// | `0101` | 4606
360/// | `0110` | 8 bit field (+1)
361/// | `0111` | 16 bit field (+1)
362/// | `1000` | 256
363/// | `1001` | 512
364/// | `1010` | 1024
365/// | `1011` | 2048
366/// | `1100` | 4096
367/// | `1101` | 8192
368/// | `1110` | 16384
369/// | `1111` | 32768
370///
371/// Handing uncommon block sizes is why this type
372/// is a generic with two different implementations
373/// from reading from a bitstream.
374/// The first reads common sizes, while the second
375/// reads additional bits if necessary.
376///
377/// # Example
378///
379/// ```
380/// use flac_codec::stream::BlockSize;
381/// use bitstream_io::{BitReader, BitRead, BigEndian};
382///
383/// let data: &[u8] = &[
384///     0b0110_1001,              // block size + sample rate
385///     0b0000_100_0,             // channels + bps + pad
386///     0x00,                     // frame number
387///     0x13,                     // uncommon block size (+1)
388/// ];
389///
390/// let mut r = BitReader::endian(data, BigEndian);
391/// let block_size = r.parse::<BlockSize<()>>().unwrap();  // reads 0b0110
392/// assert_eq!(
393///     block_size,
394///     BlockSize::Uncommon8(()),  // need to read actual block size from end of frame
395/// );
396/// r.skip(4 + 8 + 8).unwrap();    // skip unnecessary bits for this example
397/// assert_eq!(
398///     // read remainder of block size from end of frame
399///     r.parse_using::<BlockSize<u16>>(block_size).unwrap(),
400///     BlockSize::Uncommon8(0x13 + 1),
401/// );
402/// ```
403#[derive(Copy, Clone, Debug, Eq, PartialEq)]
404pub enum BlockSize<B> {
405    /// 192 samples
406    Samples192,
407    /// 576 samples
408    Samples576,
409    /// 1152 samples
410    Samples1152,
411    /// 2304 samples
412    Samples2304,
413    /// 4608 samples
414    Samples4608,
415    /// Uncommon 8 bit sample count + 1
416    Uncommon8(B),
417    /// Uncommon 16 bit sample count + 1
418    Uncommon16(B),
419    /// 256 samples
420    Samples256,
421    /// 512 samples
422    Samples512,
423    /// 1024 samples
424    Samples1024,
425    /// 2048 samples
426    Samples2048,
427    /// 4096 samples
428    Samples4096,
429    /// 8192 samples
430    Samples8192,
431    /// 16384 samples
432    Samples16384,
433    /// 32768 samples
434    Samples32768,
435}
436
437impl FromBitStream for BlockSize<()> {
438    type Error = Error;
439
440    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error> {
441        match r.read::<4, u8>()? {
442            0b0000 => Err(Error::InvalidBlockSize),
443            0b0001 => Ok(Self::Samples192),
444            0b0010 => Ok(Self::Samples576),
445            0b0011 => Ok(Self::Samples1152),
446            0b0100 => Ok(Self::Samples2304),
447            0b0101 => Ok(Self::Samples4608),
448            0b0110 => Ok(Self::Uncommon8(())),
449            0b0111 => Ok(Self::Uncommon16(())),
450            0b1000 => Ok(Self::Samples256),
451            0b1001 => Ok(Self::Samples512),
452            0b1010 => Ok(Self::Samples1024),
453            0b1011 => Ok(Self::Samples2048),
454            0b1100 => Ok(Self::Samples4096),
455            0b1101 => Ok(Self::Samples8192),
456            0b1110 => Ok(Self::Samples16384),
457            0b1111 => Ok(Self::Samples32768),
458            0b10000.. => unreachable!(), // 4-bit field
459        }
460    }
461}
462
463impl FromBitStreamUsing for BlockSize<u16> {
464    type Context = BlockSize<()>;
465    type Error = Error;
466
467    fn from_reader<R: BitRead + ?Sized>(r: &mut R, size: BlockSize<()>) -> Result<Self, Error> {
468        match size {
469            BlockSize::Samples192 => Ok(Self::Samples192),
470            BlockSize::Samples576 => Ok(Self::Samples576),
471            BlockSize::Samples1152 => Ok(Self::Samples1152),
472            BlockSize::Samples2304 => Ok(Self::Samples2304),
473            BlockSize::Samples4608 => Ok(Self::Samples4608),
474            BlockSize::Samples256 => Ok(Self::Samples256),
475            BlockSize::Samples512 => Ok(Self::Samples512),
476            BlockSize::Samples1024 => Ok(Self::Samples1024),
477            BlockSize::Samples2048 => Ok(Self::Samples2048),
478            BlockSize::Samples4096 => Ok(Self::Samples4096),
479            BlockSize::Samples8192 => Ok(Self::Samples8192),
480            BlockSize::Samples16384 => Ok(Self::Samples16384),
481            BlockSize::Samples32768 => Ok(Self::Samples32768),
482            BlockSize::Uncommon8(()) => Ok(Self::Uncommon8(r.read::<8, u16>()? + 1)),
483            BlockSize::Uncommon16(()) => Ok(Self::Uncommon16(
484                r.read::<16, u16>()?
485                    .checked_add(1)
486                    .ok_or(Error::InvalidBlockSize)?,
487            )),
488        }
489    }
490}
491
492impl<B> ToBitStream for BlockSize<B> {
493    type Error = std::io::Error;
494
495    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
496        w.write::<4, u8>(match self {
497            Self::Samples192 => 0b0001,
498            Self::Samples576 => 0b0010,
499            Self::Samples1152 => 0b0011,
500            Self::Samples2304 => 0b0100,
501            Self::Samples4608 => 0b0101,
502            Self::Uncommon8(_) => 0b0110,
503            Self::Uncommon16(_) => 0b0111,
504            Self::Samples256 => 0b1000,
505            Self::Samples512 => 0b1001,
506            Self::Samples1024 => 0b1010,
507            Self::Samples2048 => 0b1011,
508            Self::Samples4096 => 0b1100,
509            Self::Samples8192 => 0b1101,
510            Self::Samples16384 => 0b1110,
511            Self::Samples32768 => 0b1111,
512        })
513    }
514}
515
516impl From<BlockSize<u16>> for u16 {
517    fn from(size: BlockSize<u16>) -> Self {
518        match size {
519            BlockSize::Samples192 => 192,
520            BlockSize::Samples576 => 576,
521            BlockSize::Samples1152 => 1152,
522            BlockSize::Samples2304 => 2304,
523            BlockSize::Samples4608 => 4608,
524            BlockSize::Samples256 => 256,
525            BlockSize::Samples512 => 512,
526            BlockSize::Samples1024 => 1024,
527            BlockSize::Samples2048 => 2048,
528            BlockSize::Samples4096 => 4096,
529            BlockSize::Samples8192 => 8192,
530            BlockSize::Samples16384 => 16384,
531            BlockSize::Samples32768 => 32768,
532            BlockSize::Uncommon8(s) | BlockSize::Uncommon16(s) => s,
533        }
534    }
535}
536
537impl TryFrom<u16> for BlockSize<u16> {
538    type Error = Error;
539
540    fn try_from(size: u16) -> Result<Self, Error> {
541        match size {
542            0 => Err(Error::InvalidBlockSize),
543            192 => Ok(Self::Samples192),
544            576 => Ok(Self::Samples576),
545            1152 => Ok(Self::Samples1152),
546            2304 => Ok(Self::Samples2304),
547            4608 => Ok(Self::Samples4608),
548            256 => Ok(Self::Samples256),
549            512 => Ok(Self::Samples512),
550            1024 => Ok(Self::Samples1024),
551            2048 => Ok(Self::Samples2048),
552            4096 => Ok(Self::Samples4096),
553            8192 => Ok(Self::Samples8192),
554            16384 => Ok(Self::Samples16384),
555            32768 => Ok(Self::Samples32768),
556            size if size <= 256 => Ok(Self::Uncommon8(size)),
557            size => Ok(Self::Uncommon16(size)),
558        }
559    }
560}
561
562impl std::fmt::Display for BlockSize<u16> {
563    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
564        u16::from(*self).fmt(f)
565    }
566}
567
568/// Possible sample rates in a FLAC frame
569///
570/// Common rates are stored as a 4-bit value,
571/// while uncommon rates are stored as 8 or 16 bit values.
572/// Sample rates defined in the STREAMINFO metadata block
573/// are only possible on a "non-subset" stream, which is
574/// not streamable.
575///
576/// | Bits   | Sample Rate |
577/// |-------:|-------------|
578/// | `0000` | get from STREAMINFO
579/// | `0001` | 88200 Hz
580/// | `0010` | 176400 Hz
581/// | `0011` | 192000 Hz
582/// | `0100` | 8000 Hz
583/// | `0101` | 16000 Hz
584/// | `0110` | 22050 Hz
585/// | `0111` | 24000 Hz
586/// | `1000` | 32000 Hz
587/// | `1001` | 44100 Hz
588/// | `1010` | 48000 Hz
589/// | `1011` | 96000 Hz
590/// | `1100` | read 8 bits, in kHz
591/// | `1101` | read 16 bits, in Hz
592/// | `1110` | read 16 bits, in 10s of Hz
593/// | `1111` | invalid sample rate
594///
595/// Handing uncommon frame rates is why this type is a generic
596/// with multiple implementations from reading from a bitstream.
597/// The first reads common rates, while the second reads additional bits if necessary.
598///
599/// # Example
600///
601/// ```
602/// use flac_codec::stream::SampleRate;
603/// use bitstream_io::{BitReader, BitRead, BigEndian};
604///
605/// let data: &[u8] = &[
606///     0b0110_1001,              // block size + sample rate
607///     0b0000_100_0,             // channels + bps + pad
608///     0x00,                     // frame number
609///     0x13,                     // uncommon block size (+1)
610/// ];
611///
612/// let mut r = BitReader::endian(data, BigEndian);
613/// r.skip(4).unwrap();          // skip block size
614/// let sample_rate = r.parse::<SampleRate<()>>().unwrap();  // reads 0b1001
615/// assert_eq!(
616///     sample_rate,
617///     SampleRate::Hz44100,     // got defined sample rate
618/// );
619/// r.skip(8 + 8 + 8).unwrap();  // skip unnecessary bits for this example
620/// assert_eq!(
621///     // since our rate is defined, no need to read additional bits
622///     r.parse_using::<SampleRate<u32>>(sample_rate).unwrap(),
623///     SampleRate::Hz44100,
624/// );
625/// ```
626#[derive(Copy, Clone, Debug, Eq, PartialEq)]
627pub enum SampleRate<R> {
628    /// Get rate from STREAMINFO metadata block
629    Streaminfo(u32),
630    /// 88200 Hz
631    Hz88200,
632    /// 176,400 Hz
633    Hz176400,
634    /// 192,000 Hz
635    Hz192000,
636    /// 8,000 Hz
637    Hz8000,
638    /// 16,000 Hz
639    Hz16000,
640    /// 22,050 Hz
641    Hz22050,
642    /// 24,000 Hz
643    Hz24000,
644    /// 32,000 Hz
645    Hz32000,
646    /// 44,100 Hz
647    Hz44100,
648    /// 48,000 Hz
649    Hz48000,
650    /// 96,000 Hz
651    Hz96000,
652    /// 8-bit value in kHz
653    KHz(R),
654    /// 16-bit value in Hz
655    Hz(R),
656    /// 16-bit value * 10 in Hz
657    DHz(R),
658}
659
660/// Reads the raw sample rate bits, which need to be finalized
661impl FromBitStreamUsing for SampleRate<()> {
662    type Context = Option<u32>;
663
664    type Error = Error;
665
666    fn from_reader<R: BitRead + ?Sized>(
667        r: &mut R,
668        streaminfo_rate: Option<u32>,
669    ) -> Result<Self, Self::Error> {
670        match r.read::<4, u8>()? {
671            0b0000 => Ok(Self::Streaminfo(
672                streaminfo_rate.ok_or(Error::NonSubsetSampleRate)?,
673            )),
674            0b0001 => Ok(Self::Hz88200),
675            0b0010 => Ok(Self::Hz176400),
676            0b0011 => Ok(Self::Hz192000),
677            0b0100 => Ok(Self::Hz8000),
678            0b0101 => Ok(Self::Hz16000),
679            0b0110 => Ok(Self::Hz22050),
680            0b0111 => Ok(Self::Hz24000),
681            0b1000 => Ok(Self::Hz32000),
682            0b1001 => Ok(Self::Hz44100),
683            0b1010 => Ok(Self::Hz48000),
684            0b1011 => Ok(Self::Hz96000),
685            0b1100 => Ok(Self::KHz(())),
686            0b1101 => Ok(Self::Hz(())),
687            0b1110 => Ok(Self::DHz(())),
688            0b1111 => Err(Error::InvalidSampleRate),
689            _ => unreachable!(), // 4-bit field
690        }
691    }
692}
693
694impl FromBitStream for SampleRate<()> {
695    type Error = Error;
696
697    #[inline]
698    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error> {
699        r.parse_using(None)
700    }
701}
702
703impl FromBitStreamUsing for SampleRate<u32> {
704    type Context = SampleRate<()>;
705
706    type Error = Error;
707
708    fn from_reader<R: BitRead + ?Sized>(
709        r: &mut R,
710        rate: SampleRate<()>,
711    ) -> Result<Self, Self::Error> {
712        match rate {
713            SampleRate::Streaminfo(s) => Ok(Self::Streaminfo(s)),
714            SampleRate::Hz88200 => Ok(Self::Hz88200),
715            SampleRate::Hz176400 => Ok(Self::Hz176400),
716            SampleRate::Hz192000 => Ok(Self::Hz192000),
717            SampleRate::Hz8000 => Ok(Self::Hz8000),
718            SampleRate::Hz16000 => Ok(Self::Hz16000),
719            SampleRate::Hz22050 => Ok(Self::Hz22050),
720            SampleRate::Hz24000 => Ok(Self::Hz24000),
721            SampleRate::Hz32000 => Ok(Self::Hz32000),
722            SampleRate::Hz44100 => Ok(Self::Hz44100),
723            SampleRate::Hz48000 => Ok(Self::Hz48000),
724            SampleRate::Hz96000 => Ok(Self::Hz96000),
725            SampleRate::KHz(()) => Ok(Self::KHz(r.read::<8, u32>()? * 1000)),
726            SampleRate::Hz(()) => Ok(Self::Hz(r.read::<16, _>()?)),
727            SampleRate::DHz(()) => Ok(Self::DHz(r.read::<16, u32>()? * 10)),
728        }
729    }
730}
731
732/// Writes the raw sample rate bits
733impl<R> ToBitStream for SampleRate<R> {
734    type Error = std::io::Error;
735
736    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
737        w.write::<4, u8>(match self {
738            Self::Streaminfo(_) => 0b0000,
739            Self::Hz88200 => 0b0001,
740            Self::Hz176400 => 0b0010,
741            Self::Hz192000 => 0b0011,
742            Self::Hz8000 => 0b0100,
743            Self::Hz16000 => 0b0101,
744            Self::Hz22050 => 0b0110,
745            Self::Hz24000 => 0b0111,
746            Self::Hz32000 => 0b1000,
747            Self::Hz44100 => 0b1001,
748            Self::Hz48000 => 0b1010,
749            Self::Hz96000 => 0b1011,
750            Self::KHz(_) => 0b1100,
751            Self::Hz(_) => 0b1101,
752            Self::DHz(_) => 0b1110,
753        })
754    }
755}
756
757impl From<SampleRate<u32>> for u32 {
758    fn from(rate: SampleRate<u32>) -> Self {
759        match rate {
760            SampleRate::Streaminfo(u)
761            | SampleRate::KHz(u)
762            | SampleRate::Hz(u)
763            | SampleRate::DHz(u) => u,
764            SampleRate::Hz88200 => 88200,
765            SampleRate::Hz176400 => 176400,
766            SampleRate::Hz192000 => 192000,
767            SampleRate::Hz8000 => 8000,
768            SampleRate::Hz16000 => 16000,
769            SampleRate::Hz22050 => 22050,
770            SampleRate::Hz24000 => 24000,
771            SampleRate::Hz32000 => 32000,
772            SampleRate::Hz44100 => 44100,
773            SampleRate::Hz48000 => 48000,
774            SampleRate::Hz96000 => 96000,
775        }
776    }
777}
778
779impl TryFrom<u32> for SampleRate<u32> {
780    type Error = Error;
781
782    fn try_from(sample_rate: u32) -> Result<Self, Error> {
783        match sample_rate {
784            88200 => Ok(Self::Hz88200),
785            176400 => Ok(Self::Hz176400),
786            192000 => Ok(Self::Hz192000),
787            8000 => Ok(Self::Hz8000),
788            16000 => Ok(Self::Hz16000),
789            22050 => Ok(Self::Hz22050),
790            24000 => Ok(Self::Hz24000),
791            32000 => Ok(Self::Hz32000),
792            44100 => Ok(Self::Hz44100),
793            48000 => Ok(Self::Hz48000),
794            96000 => Ok(Self::Hz96000),
795            rate if (rate % 1000) == 0 && (rate / 1000) < u8::MAX as u32 => Ok(Self::KHz(rate)),
796            rate if (rate % 10) == 0 && (rate / 10) < u16::MAX as u32 => Ok(Self::DHz(rate)),
797            rate if rate < u16::MAX as u32 => Ok(Self::Hz(rate)),
798            rate if rate < 1 << 20 => Ok(Self::Streaminfo(rate)),
799            _ => Err(Error::InvalidSampleRate),
800        }
801    }
802}
803
804impl std::fmt::Display for SampleRate<u32> {
805    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
806        u32::from(*self).fmt(f)
807    }
808}
809
810/// How independent channels are stored
811#[derive(Copy, Clone, Debug, Eq, PartialEq)]
812pub enum Independent {
813    /// 1 monoaural channel
814    Mono = 1,
815    /// left, right channels
816    Stereo = 2,
817    /// left, right, center channels
818    Channels3 = 3,
819    /// front left, front right, back left, back right channels
820    Channels4 = 4,
821    /// front left, front right, front center,
822    /// back/surround left, back/surround right channels
823    Channels5 = 5,
824    /// front left, front right, front center,
825    /// LFE, back/surround left, back/surround right channels
826    Channels6 = 6,
827    /// front left, front right, front center,
828    /// LFE, back center, side left, side right channels
829    Channels7 = 7,
830    /// front left, front right, front center,
831    /// LFE, back left, back right, side left, side right channels
832    Channels8 = 8,
833}
834
835impl From<Independent> for u8 {
836    fn from(ch: Independent) -> Self {
837        ch as u8
838    }
839}
840
841impl From<Independent> for usize {
842    fn from(ch: Independent) -> Self {
843        ch as usize
844    }
845}
846
847impl TryFrom<usize> for Independent {
848    type Error = ();
849
850    fn try_from(ch: usize) -> Result<Self, Self::Error> {
851        match ch {
852            1 => Ok(Self::Mono),
853            2 => Ok(Self::Stereo),
854            3 => Ok(Self::Channels3),
855            4 => Ok(Self::Channels4),
856            5 => Ok(Self::Channels5),
857            6 => Ok(Self::Channels6),
858            7 => Ok(Self::Channels7),
859            8 => Ok(Self::Channels8),
860            _ => Err(()),
861        }
862    }
863}
864
865/// How the channels are assigned in a FLAC frame
866///
867/// | Bits   | Channel Assingment |
868/// |-------:|--------------------|
869/// | `0000` | 1 mono channel
870/// | `0001` | 2 independent channels
871/// | `0010` | 3 independent channels
872/// | `0011` | 4 independent channels
873/// | `0100` | 5 independent channels
874/// | `0101` | 6 independent channels
875/// | `0110` | 7 independent channels
876/// | `0111` | 8 independent channels
877/// | `1000` | left channel, side channel
878/// | `1001` | side channel, right channel
879/// | `1010` | mid channel, side channel
880/// | `1011` | invalid channel assignment
881/// | `1100` | invalid channel assignment
882/// | `1101` | invalid channel assignment
883/// | `1110` | invalid channel assignment
884/// | `1111` | invalid channel assignment
885///
886/// # Example
887///
888/// ```
889/// use flac_codec::stream::{ChannelAssignment, Independent};
890/// use bitstream_io::{BitReader, BitRead, BigEndian};
891///
892/// let data: &[u8] = &[
893///     0b0000_100_0,             // channels + bps + pad
894/// ];
895///
896/// let mut r = BitReader::endian(data, BigEndian);
897/// assert_eq!(
898///     r.parse::<ChannelAssignment>().unwrap(),
899///     ChannelAssignment::Independent(Independent::Mono),
900/// );
901/// ```
902///
903/// The samples in the side channel can be calculated like:
904///
905/// > sideᵢ = leftᵢ - rightᵢ
906///
907/// This requires that the side channel have one additional
908/// bit-per-sample during decoding, since the difference
909/// between the left and right channels could overflow
910/// if the two are at opposite extremes.
911///
912/// And with a bit of math, we can see that:
913///
914/// > rightᵢ = leftᵢ - sideᵢ
915///
916/// or:
917///
918/// > leftᵢ = sideᵢ + rightᵢ
919///
920/// For transforming left-side and side-right assignments back
921/// to left-right for output.
922///
923/// The samples in the mid channel can be calculated like:
924///
925/// > midᵢ = (leftᵢ + rightᵢ) ÷ 2
926///
927/// Mid-side assignment can be restored to left-right like:
928///
929/// > sumᵢ = midᵢ × 2 + |sideᵢ| % 2
930/// >
931/// > leftᵢ = (sumᵢ + sideᵢ) ÷ 2
932/// >
933/// > rightᵢ = (sumᵢ - sideᵢ) ÷ 2
934///
935/// The mid channel does *not* require any additional bits
936/// to decode, since the average cannot exceed either channel.
937#[derive(Copy, Clone, Debug, Eq, PartialEq)]
938pub enum ChannelAssignment {
939    /// Channels are stored independently
940    Independent(Independent),
941    /// Channel 0 is stored verbatim, channel 1 derived from both
942    LeftSide,
943    /// Channel 0 is derived from both, channel 1 is stored verbatim
944    SideRight,
945    /// Channel 0 is averaged from both, channel 1 is derived from both
946    MidSide,
947}
948
949impl ChannelAssignment {
950    /// Returns total number of channels defined by assignment
951    pub fn count(&self) -> u8 {
952        match self {
953            Self::Independent(c) => (*c).into(),
954            _ => 2,
955        }
956    }
957}
958
959impl std::fmt::Display for ChannelAssignment {
960    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
961        match self {
962            Self::Independent(_) => "INDEPENDENT".fmt(f),
963            Self::LeftSide => "LEFT_SIDE".fmt(f),
964            Self::SideRight => "SIDE_RIGHT".fmt(f),
965            Self::MidSide => "MID_SIDE".fmt(f),
966        }
967    }
968}
969
970impl FromBitStream for ChannelAssignment {
971    type Error = Error;
972
973    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
974        match r.read::<4, u8>()? {
975            0b0000 => Ok(Self::Independent(Independent::Mono)),
976            0b0001 => Ok(Self::Independent(Independent::Stereo)),
977            0b0010 => Ok(Self::Independent(Independent::Channels3)),
978            0b0011 => Ok(Self::Independent(Independent::Channels4)),
979            0b0100 => Ok(Self::Independent(Independent::Channels5)),
980            0b0101 => Ok(Self::Independent(Independent::Channels6)),
981            0b0110 => Ok(Self::Independent(Independent::Channels7)),
982            0b0111 => Ok(Self::Independent(Independent::Channels8)),
983            0b1000 => Ok(Self::LeftSide),
984            0b1001 => Ok(Self::SideRight),
985            0b1010 => Ok(Self::MidSide),
986            0b1011..=0b1111 => Err(Error::InvalidChannels),
987            0b10000.. => unreachable!(), // 4-bit field
988        }
989    }
990}
991
992impl ToBitStream for ChannelAssignment {
993    type Error = Error;
994
995    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
996        Ok(w.write::<4, u8>(match self {
997            Self::Independent(Independent::Mono) => 0b0000,
998            Self::Independent(Independent::Stereo) => 0b0001,
999            Self::Independent(Independent::Channels3) => 0b0010,
1000            Self::Independent(Independent::Channels4) => 0b0011,
1001            Self::Independent(Independent::Channels5) => 0b0100,
1002            Self::Independent(Independent::Channels6) => 0b0101,
1003            Self::Independent(Independent::Channels7) => 0b0110,
1004            Self::Independent(Independent::Channels8) => 0b0111,
1005            Self::LeftSide => 0b1000,
1006            Self::SideRight => 0b1001,
1007            Self::MidSide => 0b1010,
1008        })?)
1009    }
1010}
1011
1012/// The the possible bits-per-sample of a FLAC frame
1013///
1014/// Common bits-per-sample are stored as a 3-bit value,
1015/// while uncommon bits-per-sample are stored in the
1016/// STREAMINFO metadata block.
1017/// Bits-per-sample defined in the STREAMINFO metadata block
1018/// are only possible on a "non-subset" stream, which is
1019/// not streamable.
1020///
1021/// | Bits  | Bits-per-Sample |
1022/// |------:|-------------|
1023/// | `000` | get from STREAMINFO
1024/// | `001` | 8
1025/// | `010` | 12
1026/// | `011` | invalid
1027/// | `100` | 16
1028/// | `101` | 20
1029/// | `110` | 24
1030/// | `111` | 32
1031///
1032/// # Example
1033/// ```
1034/// use flac_codec::stream::BitsPerSample;
1035/// use bitstream_io::{BitReader, BitRead, BigEndian};
1036///
1037/// let data: &[u8] = &[
1038///     0b0000_100_0,             // channels + bps + pad
1039/// ];
1040///
1041/// let mut r = BitReader::endian(data, BigEndian);
1042/// r.skip(4).unwrap();  // skip channel assignment
1043/// assert_eq!(
1044///     r.parse::<BitsPerSample>().unwrap(),
1045///     BitsPerSample::Bps16,
1046/// );
1047/// ```
1048#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1049pub enum BitsPerSample {
1050    /// Gets bps from STREAMINFO metadata block
1051    Streaminfo(SignedBitCount<32>),
1052    /// 8 bits-per-sample
1053    Bps8,
1054    /// 12 bits-per-sample
1055    Bps12,
1056    /// 16 bits-per-sample
1057    Bps16,
1058    /// 20 bits-per-sample
1059    Bps20,
1060    /// 24 bits-per-sample
1061    Bps24,
1062    /// 32 bits-per-sample
1063    Bps32,
1064}
1065
1066impl BitsPerSample {
1067    const BPS8: SignedBitCount<32> = SignedBitCount::new::<8>();
1068    const BPS12: SignedBitCount<32> = SignedBitCount::new::<12>();
1069    const BPS16: SignedBitCount<32> = SignedBitCount::new::<16>();
1070    const BPS20: SignedBitCount<32> = SignedBitCount::new::<20>();
1071    const BPS24: SignedBitCount<32> = SignedBitCount::new::<24>();
1072    const BPS32: SignedBitCount<32> = SignedBitCount::new::<32>();
1073
1074    /// Adds the given number of bits to this bit count, if possible.
1075    ///
1076    /// If the number of bits would overflow the maximum count,
1077    /// returns `None`.
1078    #[inline]
1079    pub fn checked_add(self, rhs: u32) -> Option<SignedBitCount<32>> {
1080        match self {
1081            Self::Streaminfo(c) => c.checked_add(rhs),
1082            Self::Bps8 => Self::BPS8.checked_add(rhs),
1083            Self::Bps12 => Self::BPS12.checked_add(rhs),
1084            Self::Bps16 => Self::BPS16.checked_add(rhs),
1085            Self::Bps20 => Self::BPS20.checked_add(rhs),
1086            Self::Bps24 => Self::BPS24.checked_add(rhs),
1087            Self::Bps32 => Self::BPS32.checked_add(rhs),
1088        }
1089    }
1090}
1091
1092impl PartialEq<SignedBitCount<32>> for BitsPerSample {
1093    fn eq(&self, rhs: &SignedBitCount<32>) -> bool {
1094        match self {
1095            Self::Streaminfo(c) => c.eq(rhs),
1096            Self::Bps8 => Self::BPS8.eq(rhs),
1097            Self::Bps12 => Self::BPS12.eq(rhs),
1098            Self::Bps16 => Self::BPS16.eq(rhs),
1099            Self::Bps20 => Self::BPS20.eq(rhs),
1100            Self::Bps24 => Self::BPS24.eq(rhs),
1101            Self::Bps32 => Self::BPS32.eq(rhs),
1102        }
1103    }
1104}
1105
1106impl From<BitsPerSample> for SignedBitCount<32> {
1107    #[inline]
1108    fn from(bps: BitsPerSample) -> Self {
1109        match bps {
1110            BitsPerSample::Streaminfo(c) => c,
1111            BitsPerSample::Bps8 => BitsPerSample::BPS8,
1112            BitsPerSample::Bps12 => BitsPerSample::BPS12,
1113            BitsPerSample::Bps16 => BitsPerSample::BPS16,
1114            BitsPerSample::Bps20 => BitsPerSample::BPS20,
1115            BitsPerSample::Bps24 => BitsPerSample::BPS24,
1116            BitsPerSample::Bps32 => BitsPerSample::BPS32,
1117        }
1118    }
1119}
1120
1121impl From<BitsPerSample> for u32 {
1122    #[inline]
1123    fn from(bps: BitsPerSample) -> Self {
1124        match bps {
1125            BitsPerSample::Streaminfo(c) => c.into(),
1126            BitsPerSample::Bps8 => 8,
1127            BitsPerSample::Bps12 => 12,
1128            BitsPerSample::Bps16 => 16,
1129            BitsPerSample::Bps20 => 20,
1130            BitsPerSample::Bps24 => 24,
1131            BitsPerSample::Bps32 => 32,
1132        }
1133    }
1134}
1135
1136impl From<SignedBitCount<32>> for BitsPerSample {
1137    #[inline]
1138    fn from(bps: SignedBitCount<32>) -> Self {
1139        match bps {
1140            Self::BPS8 => Self::Bps8,
1141            Self::BPS12 => Self::Bps12,
1142            Self::BPS16 => Self::Bps16,
1143            Self::BPS20 => Self::Bps20,
1144            Self::BPS24 => Self::Bps24,
1145            Self::BPS32 => Self::Bps32,
1146            bps => Self::Streaminfo(bps),
1147        }
1148    }
1149}
1150
1151impl FromBitStreamUsing for BitsPerSample {
1152    type Context = Option<SignedBitCount<32>>;
1153    type Error = Error;
1154
1155    fn from_reader<R: BitRead + ?Sized>(
1156        r: &mut R,
1157        streaminfo_bps: Option<SignedBitCount<32>>,
1158    ) -> Result<Self, Error> {
1159        match r.read::<3, u8>()? {
1160            0b000 => Ok(Self::Streaminfo(
1161                streaminfo_bps.ok_or(Error::NonSubsetBitsPerSample)?,
1162            )),
1163            0b001 => Ok(Self::Bps8),
1164            0b010 => Ok(Self::Bps12),
1165            0b011 => Err(Error::InvalidBitsPerSample),
1166            0b100 => Ok(Self::Bps16),
1167            0b101 => Ok(Self::Bps20),
1168            0b110 => Ok(Self::Bps24),
1169            0b111 => Ok(Self::Bps32),
1170            0b1000.. => unreachable!(), // 3-bit field
1171        }
1172    }
1173}
1174
1175impl FromBitStream for BitsPerSample {
1176    type Error = Error;
1177
1178    #[inline]
1179    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
1180        r.parse_using(None)
1181    }
1182}
1183
1184impl ToBitStream for BitsPerSample {
1185    type Error = std::io::Error;
1186
1187    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
1188        w.write::<3, u8>(match self {
1189            Self::Streaminfo(_) => 0b000,
1190            Self::Bps8 => 0b001,
1191            Self::Bps12 => 0b010,
1192            Self::Bps16 => 0b100,
1193            Self::Bps20 => 0b101,
1194            Self::Bps24 => 0b110,
1195            Self::Bps32 => 0b111,
1196        })
1197    }
1198}
1199
1200/// A frame number in the stream, as FLAC frames or samples
1201///
1202/// The frame number is stored as a UTF-8-like value
1203/// where the total number of bytes is encoded
1204/// in the initial byte.
1205///
1206/// | byte 0     | byte 1     | byte 2     | byte 3     | byte 4     | byte 5     | byte 6
1207/// |------------|------------|------------|------------|------------|------------|---------
1208/// | `0xxxxxxx` |            |            |            |            |            |
1209/// | `110xxxxx` | `10xxxxxx` |            |            |            |            |
1210/// | `1110xxxx` | `10xxxxxx` | `10xxxxxx` |            |            |            |
1211/// | `11110xxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` |            |            |
1212/// | `111110xx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` |            |
1213/// | `1111110x` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` |
1214/// | `11111110` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx` | `10xxxxxx`
1215///
1216/// The `x` bits are the frame number, encoded from most-significant
1217/// to least significant.
1218#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1219pub struct FrameNumber(pub u64);
1220
1221impl FrameNumber {
1222    /// Our maximum frame number
1223    const MAX_FRAME_NUMBER: u64 = (1 << 36) - 1;
1224
1225    /// Attempt to increment frame number
1226    ///
1227    /// # Error
1228    ///
1229    /// Returns an error if the frame number is too large
1230    pub fn try_increment(&mut self) -> Result<(), Error> {
1231        if self.0 < Self::MAX_FRAME_NUMBER {
1232            self.0 += 1;
1233            Ok(())
1234        } else {
1235            Err(Error::ExcessiveFrameNumber)
1236        }
1237    }
1238}
1239
1240impl std::fmt::Display for FrameNumber {
1241    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1242        self.0.fmt(f)
1243    }
1244}
1245
1246impl FromBitStream for FrameNumber {
1247    type Error = Error;
1248
1249    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
1250        match r.read_unary::<0>()? {
1251            0 => Ok(Self(r.read::<7, _>()?)),
1252            1 => Err(Error::InvalidFrameNumber),
1253            bytes @ 2..=7 => {
1254                let mut frame = r.read_var(7 - bytes)?;
1255                for _ in 1..bytes {
1256                    r.read_const::<2, 0b10, _>(Error::InvalidFrameNumber)?;
1257                    frame = (frame << 6) | r.read::<6, u64>()?;
1258                }
1259                Ok(Self(frame))
1260            }
1261            _ => Err(Error::InvalidFrameNumber),
1262        }
1263    }
1264}
1265
1266impl ToBitStream for FrameNumber {
1267    type Error = Error;
1268
1269    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
1270        #[inline]
1271        fn byte(num: u64, byte: u32) -> u8 {
1272            0b10_000000 | ((num >> (6 * byte)) & 0b111111) as u8
1273        }
1274
1275        match self.0 {
1276            v @ 0..=0x7F => {
1277                w.write_unary::<0>(0)?;
1278                w.write::<7, _>(v)?;
1279                Ok(())
1280            }
1281            v @ 0x80..=0x7FF => {
1282                w.write_unary::<0>(2)?;
1283                w.write::<5, _>(v >> 6)?;
1284                w.write::<8, _>(byte(v, 0))?;
1285                Ok(())
1286            }
1287            v @ 0x800..=0xFFFF => {
1288                w.write_unary::<0>(3)?;
1289                w.write::<4, _>(v >> (6 * 2))?;
1290                w.write::<8, _>([byte(v, 1), byte(v, 0)])?;
1291                Ok(())
1292            }
1293            v @ 0x1_0000..=0x1F_FFFF => {
1294                w.write_unary::<0>(4)?;
1295                w.write::<3, _>(v >> (6 * 3))?;
1296                w.write::<8, _>([byte(v, 2), byte(v, 1), byte(v, 0)])?;
1297                Ok(())
1298            }
1299            v @ 0x20_0000..=0x3FF_FFFF => {
1300                w.write_unary::<0>(5)?;
1301                w.write::<2, _>(v >> (6 * 4))?;
1302                w.write::<8, _>([byte(v, 3), byte(v, 2), byte(v, 1), byte(v, 0)])?;
1303                Ok(())
1304            }
1305            v @ 0x400_0000..=0x7FFF_FFFF => {
1306                w.write_unary::<0>(6)?;
1307                w.write::<1, _>(v >> (6 * 5))?;
1308                w.write::<8, _>([byte(v, 4), byte(v, 3), byte(v, 2), byte(v, 1), byte(v, 0)])?;
1309                Ok(())
1310            }
1311            v @ 0x8000_0000..=0xF_FFFF_FFFF => {
1312                w.write_unary::<0>(7)?;
1313                w.write::<8, _>([
1314                    byte(v, 5),
1315                    byte(v, 4),
1316                    byte(v, 3),
1317                    byte(v, 2),
1318                    byte(v, 1),
1319                    byte(v, 0),
1320                ])?;
1321                Ok(())
1322            }
1323            _ => Err(Error::InvalidFrameNumber),
1324        }
1325    }
1326}
1327
1328#[test]
1329fn test_frame_number() {
1330    use bitstream_io::{BigEndian, BitRead, BitReader, BitWrite, BitWriter};
1331
1332    let mut buf: [u8; 7] = [0; 7];
1333
1334    for i in (0..=0xFFFF)
1335        .chain((0x1_0000..=0x1F_FFFF).step_by(32))
1336        .chain((0x20_0000..=0x3FF_FFFF).step_by(1024))
1337        .chain((0x400_0000..=0x7FFF_FFFF).step_by(33760))
1338        .chain((0x8000_0000..=0xF_FFFF_FFFF).step_by(1048592))
1339    {
1340        let num = FrameNumber(i);
1341
1342        assert!(
1343            BitWriter::endian(buf.as_mut_slice(), BigEndian)
1344                .build(&num)
1345                .is_ok()
1346        );
1347
1348        let num2 = BitReader::endian(buf.as_slice(), BigEndian)
1349            .parse::<FrameNumber>()
1350            .unwrap();
1351
1352        assert_eq!(num.0, num2.0);
1353
1354        buf.fill(0);
1355    }
1356}
1357
1358/// A Subframe Header
1359///
1360/// | Bits | Field   | Meaning
1361/// |-----:|---------|--------
1362/// | 1    | pad (0) |
1363/// | 6    | `type_` | subframe type and (if any) order
1364/// | 1    | has wasted bits | whether the subframe has wasted bits-per-sample
1365/// | (0+) | `wasted_bps`| the number of wasted bits-per-sample, as unary
1366///
1367/// "Wasted" bits is when all of the samples in a given subframe
1368/// have one or more `0` bits in the least-significant bits position.
1369/// In this case, the samples can all be safely right shifted
1370/// by that amount of wasted bits during encoding, and left
1371/// shifted by that amount of bits during decoding, without loss.
1372///
1373/// This is an uncommon case.
1374#[derive(Debug)]
1375pub struct SubframeHeader {
1376    /// The subframe header's type
1377    pub type_: SubframeHeaderType,
1378    /// The number of wasted bits-per-sample
1379    pub wasted_bps: u32,
1380}
1381
1382impl FromBitStream for SubframeHeader {
1383    type Error = Error;
1384
1385    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
1386        r.read_const::<1, 0, _>(Error::InvalidSubframeHeader)?;
1387        Ok(Self {
1388            type_: r.parse()?,
1389            wasted_bps: match r.read_bit()? {
1390                false => 0,
1391                true => r.read_unary::<1>()? + 1,
1392            },
1393        })
1394    }
1395}
1396
1397impl ToBitStream for SubframeHeader {
1398    type Error = Error;
1399
1400    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
1401        w.write_const::<1, 0>()?;
1402        w.build(&self.type_)?;
1403        match self.wasted_bps.checked_sub(1) {
1404            None => w.write_bit(false)?,
1405            Some(wasted) => {
1406                w.write_bit(true)?;
1407                w.write_unary::<1>(wasted)?;
1408            }
1409        }
1410
1411        Ok(())
1412    }
1413}
1414
1415/// A subframe's type
1416#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash, Ord, PartialOrd)]
1417pub enum SubframeType {
1418    /// A constant subframe
1419    Constant,
1420    /// A verbatim subframe
1421    Verbatim,
1422    /// A fixed subframe
1423    Fixed,
1424    /// An LPC subframe
1425    Lpc,
1426}
1427
1428impl std::fmt::Display for SubframeType {
1429    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1430        match self {
1431            Self::Constant => "CONSTANT".fmt(f),
1432            Self::Verbatim => "VERBATIM".fmt(f),
1433            Self::Fixed => "FIXED".fmt(f),
1434            Self::Lpc => "LPC".fmt(f),
1435        }
1436    }
1437}
1438
1439/// A subframe header's type and order
1440///
1441/// This is always a 6-bit field.
1442///
1443/// | Bits     | Type | Order
1444/// |----------|------|--------
1445/// | `000000` | CONSTANT | N/A
1446/// | `000001` | VERBATIM | N/A
1447/// | `000010` to `000111` | reserved | N/A
1448/// | `001000` to `001100` | FIXED    | `v - 8`
1449/// | `001101` to `011111` | reserved | N/A
1450/// | `100000` to `111111` | LPC      | `v - 31`
1451#[derive(Debug, Eq, PartialEq)]
1452pub enum SubframeHeaderType {
1453    /// All samples are the same
1454    ///
1455    /// # Example
1456    /// ```
1457    /// use flac_codec::stream::SubframeHeaderType;
1458    /// use bitstream_io::{BitReader, BitRead, BigEndian};
1459    ///
1460    /// let data: &[u8] = &[0b0_000000_0];
1461    /// let mut r = BitReader::endian(data, BigEndian);
1462    /// r.skip(1).unwrap();  // pad bit
1463    /// assert_eq!(
1464    ///     r.parse::<SubframeHeaderType>().unwrap(),
1465    ///     SubframeHeaderType::Constant,
1466    /// );
1467    /// ```
1468    Constant,
1469    /// All samples as stored verbatim, without compression
1470    ///
1471    /// # Example
1472    /// ```
1473    /// use flac_codec::stream::SubframeHeaderType;
1474    /// use bitstream_io::{BitReader, BitRead, BigEndian};
1475    ///
1476    /// let data: &[u8] = &[0b0_000001_0];
1477    /// let mut r = BitReader::endian(data, BigEndian);
1478    /// r.skip(1).unwrap();  // pad bit
1479    /// assert_eq!(
1480    ///     r.parse::<SubframeHeaderType>().unwrap(),
1481    ///     SubframeHeaderType::Verbatim,
1482    /// );
1483    /// ```
1484    Verbatim,
1485    /// Samples are stored with one of a set of fixed LPC parameters
1486    ///
1487    /// # Example
1488    /// ```
1489    /// use flac_codec::stream::SubframeHeaderType;
1490    /// use bitstream_io::{BitReader, BitRead, BigEndian};
1491    ///
1492    /// let data: &[u8] = &[0b0_001100_0];
1493    /// let mut r = BitReader::endian(data, BigEndian);
1494    /// r.skip(1).unwrap();  // pad bit
1495    /// assert_eq!(
1496    ///     r.parse::<SubframeHeaderType>().unwrap(),
1497    ///     SubframeHeaderType::Fixed { order: 0b001100 - 8 },  // order = 4
1498    /// );
1499    /// ```
1500    Fixed {
1501        /// The predictor order, from 0..5
1502        order: u8,
1503    },
1504    /// Samples are stored with dynamic LPC parameters
1505    ///
1506    /// # Example
1507    /// ```
1508    /// use flac_codec::stream::SubframeHeaderType;
1509    /// use bitstream_io::{BitReader, BitRead, BigEndian};
1510    /// use std::num::NonZero;
1511    ///
1512    /// let data: &[u8] = &[0b0_100000_0];
1513    /// let mut r = BitReader::endian(data, BigEndian);
1514    /// r.skip(1).unwrap();  // pad bit
1515    /// assert_eq!(
1516    ///     r.parse::<SubframeHeaderType>().unwrap(),
1517    ///     SubframeHeaderType::Lpc {
1518    ///         order: NonZero::new(0b100000 - 31).unwrap(),  // order = 1
1519    ///     },
1520    /// );
1521    /// ```
1522    Lpc {
1523        /// The predictor order, from 1..33
1524        order: NonZero<u8>,
1525    },
1526}
1527
1528impl SubframeHeaderType {
1529    /// A set of FIXED subframe coefficients
1530    ///
1531    /// Note that these are in the reverse order from how
1532    /// they're usually presented, simply because we'll
1533    /// be predicting samples in reverse order.
1534    pub const FIXED_COEFFS: [&[i64]; 5] = [&[], &[1], &[2, -1], &[3, -3, 1], &[4, -6, 4, -1]];
1535}
1536
1537impl FromBitStream for SubframeHeaderType {
1538    type Error = Error;
1539
1540    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
1541        match r.read::<6, u8>()? {
1542            0b000000 => Ok(Self::Constant),
1543            0b000001 => Ok(Self::Verbatim),
1544            v @ 0b001000..=0b001100 => Ok(Self::Fixed {
1545                order: v - 0b001000,
1546            }),
1547            v @ 0b100000..=0b111111 => Ok(Self::Lpc {
1548                order: NonZero::new(v - 31).unwrap(),
1549            }),
1550            _ => Err(Error::InvalidSubframeHeaderType),
1551        }
1552    }
1553}
1554
1555impl ToBitStream for SubframeHeaderType {
1556    type Error = Error;
1557
1558    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
1559        w.write::<6, u8>(match self {
1560            Self::Constant => 0b000000,
1561            Self::Verbatim => 0b000001,
1562            Self::Fixed { order } => 0b001000 + order,
1563            Self::Lpc { order } => order.get() + 31,
1564        })?;
1565        Ok(())
1566    }
1567}
1568
1569/// A FLAC residual partition header
1570#[derive(Copy, Clone, Debug, Eq, PartialEq)]
1571pub enum ResidualPartitionHeader<const RICE_MAX: u32> {
1572    /// Standard, un-escaped partition
1573    Standard {
1574        /// The partition's Rice parameter
1575        rice: BitCount<RICE_MAX>,
1576    },
1577    /// Escaped partition
1578    Escaped {
1579        /// The size of each residual in bits
1580        escape_size: SignedBitCount<0b11111>,
1581    },
1582    /// All residuals in partition are 0
1583    Constant,
1584}
1585
1586impl<const RICE_MAX: u32> FromBitStream for ResidualPartitionHeader<RICE_MAX> {
1587    type Error = std::io::Error;
1588
1589    fn from_reader<R: BitRead + ?Sized>(r: &mut R) -> Result<Self, Self::Error> {
1590        let rice = r.read_count()?;
1591
1592        if rice == BitCount::new::<{ RICE_MAX }>() {
1593            match r.read_count()?.signed_count() {
1594                Some(escape_size) => Ok(Self::Escaped { escape_size }),
1595                None => Ok(Self::Constant),
1596            }
1597        } else {
1598            Ok(Self::Standard { rice })
1599        }
1600    }
1601}
1602
1603impl<const RICE_MAX: u32> ToBitStream for ResidualPartitionHeader<RICE_MAX> {
1604    type Error = std::io::Error;
1605
1606    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Self::Error> {
1607        match self {
1608            Self::Standard { rice } => w.write_count(*rice),
1609            Self::Escaped { escape_size } => {
1610                w.write_count(BitCount::<RICE_MAX>::new::<{ RICE_MAX }>())?;
1611                w.write_count(escape_size.count())
1612            }
1613            Self::Constant => {
1614                w.write_count(BitCount::<RICE_MAX>::new::<{ RICE_MAX }>())?;
1615                w.write_count(BitCount::<0b11111>::new::<0>())
1616            }
1617        }
1618    }
1619}
1620
1621/// A whole FLAC frame
1622///
1623/// A FLAC frame consists of a header, one or more subframes
1624/// (each corresponding to a different channel), and concludes with
1625/// a CRC-16 checksum over all the data in the frame.
1626///
1627/// ```text
1628/// ┌──────────┬────────┬┄┄┄┄┄┄┄┄┬┄┄┄┬────────┬┄┄┄┄┄┄┄┄┬┄┄┄╮
1629/// │ FLAC Tag │ Block₀ │ Block₁ ┆ … ┆ Frame₀ │ Frame₁ ┆ … ┆ FLAC File
1630/// └──────────┴────────┴┄┄┄┄┄┄┄┄┴┄┄┄┼────────┼┄┄┄┄┄┄┄┄┴┄┄┄╯
1631/// ╭────────────────────────────────╯        ╰─────────╮
1632/// ├──────────────┬───────────┬┄┄┄┄┄┄┄┄┄┄┄┬┄┄┄┬────────┤
1633/// │ Frame Header │ Subframe₀ │ Subframe₁ ┆ … ┆ CRC-16 │    FLAC Frame
1634/// └──────────────┴───────────┴┄┄┄┄┄┄┄┄┄┄┄┴┄┄┄┴────────┘
1635/// ```
1636///
1637/// # Example
1638///
1639/// ```
1640/// use flac_codec::stream::{
1641///     Frame, FrameHeader, BlockSize, SampleRate, ChannelAssignment,
1642///     Independent, BitsPerSample, FrameNumber, SubframeWidth, Subframe,
1643/// };
1644///
1645/// let mut data: &[u8] = &[
1646///     // frame header
1647///     0xff, 0xf8, 0x69, 0x08, 0x00, 0x13, 0x64,
1648///     // subframe
1649///     0x00, 0x00, 0x00,
1650///     // CRC-16
1651///     0xd3, 0x3b,
1652/// ];
1653///
1654/// assert_eq!(
1655///     Frame::read_subset(&mut data).unwrap(),
1656///     Frame {
1657///         header: FrameHeader {
1658///             blocking_strategy: false,
1659///             block_size: BlockSize::Uncommon8(20),
1660///             sample_rate: SampleRate::Hz44100,
1661///             channel_assignment: ChannelAssignment::Independent(
1662///                 Independent::Mono
1663///             ),
1664///             bits_per_sample: BitsPerSample::Bps16,
1665///             frame_number: FrameNumber(0),
1666///         },
1667///         subframes: vec![
1668///             SubframeWidth::Common(
1669///                 Subframe::Constant {
1670///                     block_size: 20,
1671///                     sample: 0x00_00,
1672///                     wasted_bps: 0,
1673///                 },
1674///             )
1675///         ],
1676///     },
1677/// );
1678/// ```
1679#[derive(Debug, Eq, PartialEq)]
1680pub struct Frame {
1681    /// The FLAC frame's header
1682    pub header: FrameHeader,
1683    /// A FLAC frame's sub-frames
1684    pub subframes: Vec<SubframeWidth>,
1685}
1686
1687impl Frame {
1688    fn read_inner<R, F>(reader: &mut R, read_header: F) -> Result<Self, Error>
1689    where
1690        R: std::io::Read,
1691        F: FnOnce(&mut CrcReader<&mut R, Crc16>) -> Result<FrameHeader, Error>,
1692    {
1693        use bitstream_io::{BigEndian, BitReader};
1694        use std::io::Read;
1695
1696        let mut crc16_reader: CrcReader<_, Crc16> = CrcReader::new(reader.by_ref());
1697
1698        let header = read_header(crc16_reader.by_ref())?;
1699
1700        let mut reader = BitReader::endian(crc16_reader.by_ref(), BigEndian);
1701
1702        let subframes = match header.channel_assignment {
1703            ChannelAssignment::Independent(total_channels) => (0..total_channels as u8)
1704                .map(|_| {
1705                    reader
1706                        .parse_using::<Subframe<i32>>((
1707                            header.block_size.into(),
1708                            header.bits_per_sample.into(),
1709                        ))
1710                        .map(SubframeWidth::Common)
1711                })
1712                .collect::<Result<Vec<_>, _>>()?,
1713            ChannelAssignment::LeftSide => vec![
1714                reader
1715                    .parse_using((header.block_size.into(), header.bits_per_sample.into()))
1716                    .map(SubframeWidth::Common)?,
1717                match header.bits_per_sample.checked_add(1) {
1718                    Some(side_bps) => reader
1719                        .parse_using((header.block_size.into(), side_bps))
1720                        .map(SubframeWidth::Common)?,
1721                    None => reader
1722                        .parse_using((
1723                            header.block_size.into(),
1724                            SignedBitCount::from(header.bits_per_sample)
1725                                .checked_add(1)
1726                                .unwrap(),
1727                        ))
1728                        .map(SubframeWidth::Wide)?,
1729                },
1730            ],
1731            ChannelAssignment::SideRight => vec![
1732                match header.bits_per_sample.checked_add(1) {
1733                    Some(side_bps) => reader
1734                        .parse_using((header.block_size.into(), side_bps))
1735                        .map(SubframeWidth::Common)?,
1736                    None => reader
1737                        .parse_using((
1738                            header.block_size.into(),
1739                            SignedBitCount::from(header.bits_per_sample)
1740                                .checked_add(1)
1741                                .unwrap(),
1742                        ))
1743                        .map(SubframeWidth::Wide)?,
1744                },
1745                reader
1746                    .parse_using((header.block_size.into(), header.bits_per_sample.into()))
1747                    .map(SubframeWidth::Common)?,
1748            ],
1749            ChannelAssignment::MidSide => vec![
1750                reader
1751                    .parse_using((header.block_size.into(), header.bits_per_sample.into()))
1752                    .map(SubframeWidth::Common)?,
1753                match header.bits_per_sample.checked_add(1) {
1754                    Some(side_bps) => reader
1755                        .parse_using((header.block_size.into(), side_bps))
1756                        .map(SubframeWidth::Common)?,
1757                    None => reader
1758                        .parse_using((
1759                            header.block_size.into(),
1760                            SignedBitCount::from(header.bits_per_sample)
1761                                .checked_add(1)
1762                                .unwrap(),
1763                        ))
1764                        .map(SubframeWidth::Wide)?,
1765                },
1766            ],
1767        };
1768
1769        reader.byte_align();
1770        reader.skip(16)?; // CRC-16 checksum
1771
1772        if crc16_reader.into_checksum().valid() {
1773            Ok(Self { header, subframes })
1774        } else {
1775            Err(Error::Crc16Mismatch)
1776        }
1777    }
1778
1779    /// Reads new frame from the given reader
1780    #[inline]
1781    pub fn read<R: std::io::Read>(reader: &mut R, streaminfo: &Streaminfo) -> Result<Self, Error> {
1782        Self::read_inner(reader, |r| FrameHeader::read(r, streaminfo))
1783    }
1784
1785    /// Reads new frame from the given reader
1786    ///
1787    /// Subset files are streamable FLAC files whose decoding
1788    /// parameters are fully contained within each frame header.
1789    #[inline]
1790    pub fn read_subset<R: std::io::Read>(reader: &mut R) -> Result<Self, Error> {
1791        Self::read_inner(reader, |r| FrameHeader::read_subset(r))
1792    }
1793
1794    fn write_inner<W, F>(&self, write_header: F, writer: &mut W) -> Result<(), Error>
1795    where
1796        W: std::io::Write,
1797        F: FnOnce(&mut CrcWriter<&mut W, Crc16>, &FrameHeader) -> Result<(), Error>,
1798    {
1799        use bitstream_io::{BigEndian, BitWriter};
1800        use std::io::Write;
1801
1802        let mut crc16_writer: CrcWriter<_, Crc16> = CrcWriter::new(writer.by_ref());
1803
1804        write_header(crc16_writer.by_ref(), &self.header)?;
1805
1806        let mut writer = BitWriter::endian(crc16_writer.by_ref(), BigEndian);
1807
1808        match self.header.channel_assignment {
1809            ChannelAssignment::Independent(total_channels) => {
1810                assert_eq!(total_channels as usize, self.subframes.len());
1811
1812                for subframe in &self.subframes {
1813                    // independent subframes should always be standard width
1814                    if let SubframeWidth::Common(subframe) = subframe {
1815                        writer.build_using(subframe, self.header.bits_per_sample.into())?;
1816                    }
1817                }
1818            }
1819            ChannelAssignment::LeftSide => match self.subframes.as_slice() {
1820                [left, side] => {
1821                    if let SubframeWidth::Common(left) = left {
1822                        writer.build_using(left, self.header.bits_per_sample.into())?;
1823                    }
1824
1825                    match side {
1826                        SubframeWidth::Common(side) => {
1827                            writer.build_using(
1828                                side,
1829                                self.header
1830                                    .bits_per_sample
1831                                    .checked_add(1)
1832                                    .ok_or(Error::ExcessiveBps)?,
1833                            )?;
1834                        }
1835                        SubframeWidth::Wide(side) => {
1836                            writer.build_using(
1837                                side,
1838                                SignedBitCount::from(self.header.bits_per_sample)
1839                                    .checked_add(1)
1840                                    .ok_or(Error::ExcessiveBps)?,
1841                            )?;
1842                        }
1843                    }
1844                }
1845                _ => panic!("incorrect subframe count for left-side"),
1846            },
1847            ChannelAssignment::SideRight => match self.subframes.as_slice() {
1848                [side, right] => {
1849                    match side {
1850                        SubframeWidth::Common(side) => {
1851                            writer.build_using(
1852                                side,
1853                                self.header
1854                                    .bits_per_sample
1855                                    .checked_add(1)
1856                                    .ok_or(Error::ExcessiveBps)?,
1857                            )?;
1858                        }
1859                        SubframeWidth::Wide(side) => {
1860                            writer.build_using(
1861                                side,
1862                                SignedBitCount::from(self.header.bits_per_sample)
1863                                    .checked_add(1)
1864                                    .ok_or(Error::ExcessiveBps)?,
1865                            )?;
1866                        }
1867                    }
1868
1869                    if let SubframeWidth::Common(right) = right {
1870                        writer.build_using(right, self.header.bits_per_sample.into())?;
1871                    }
1872                }
1873                _ => panic!("incorrect subframe count for left-side"),
1874            },
1875            ChannelAssignment::MidSide => match self.subframes.as_slice() {
1876                [mid, side] => {
1877                    if let SubframeWidth::Common(mid) = mid {
1878                        writer.build_using(mid, self.header.bits_per_sample.into())?;
1879                    }
1880
1881                    match side {
1882                        SubframeWidth::Common(side) => {
1883                            writer.build_using(
1884                                side,
1885                                self.header
1886                                    .bits_per_sample
1887                                    .checked_add(1)
1888                                    .ok_or(Error::ExcessiveBps)?,
1889                            )?;
1890                        }
1891                        SubframeWidth::Wide(side) => {
1892                            writer.build_using(
1893                                side,
1894                                SignedBitCount::from(self.header.bits_per_sample)
1895                                    .checked_add(1)
1896                                    .ok_or(Error::ExcessiveBps)?,
1897                            )?;
1898                        }
1899                    }
1900                }
1901                _ => panic!("incorrect subframe count for left-side"),
1902            },
1903        }
1904
1905        let crc16: u16 = writer.aligned_writer()?.checksum().into();
1906        writer.write_from(crc16)?;
1907
1908        Ok(())
1909    }
1910
1911    /// Writes frame to the given writer
1912    pub fn write<W: std::io::Write>(
1913        &self,
1914        streaminfo: &Streaminfo,
1915        writer: &mut W,
1916    ) -> Result<(), Error> {
1917        self.write_inner(|w, header| header.write(w, streaminfo), writer)
1918    }
1919
1920    /// Writes frame to the given writer
1921    ///
1922    /// Subset files are streamable FLAC files whose encoding
1923    /// parameters are fully contained within each frame header.
1924    #[inline]
1925    pub fn write_subset<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Error> {
1926        self.write_inner(|w, header| header.write_subset(w), writer)
1927    }
1928}
1929
1930/// An iterator of Frames
1931pub struct FrameIterator<R> {
1932    reader: crate::Counter<R>,
1933    blocks: crate::metadata::BlockList,
1934    metadata_len: u64,
1935    remaining_samples: Option<u64>,
1936}
1937
1938impl<R: std::io::Read> FrameIterator<R> {
1939    /// Opens new FrameIterator from the given reader
1940    ///
1941    /// The reader must be positioned at the start of the
1942    /// FLAC stream.  If the file has non-FLAC data
1943    /// at the beginning (such as ID3v2 tags), one
1944    /// should skip such data before initializing a `FrameIterator`.
1945    pub fn new(reader: R) -> Result<Self, Error> {
1946        let mut reader = crate::Counter::new(reader);
1947        let blocks = crate::metadata::BlockList::read(&mut reader)?;
1948
1949        Ok(Self {
1950            metadata_len: reader.count,
1951            remaining_samples: blocks.streaminfo().total_samples.map(|s| s.get()),
1952            blocks,
1953            reader,
1954        })
1955    }
1956
1957    /// Returns shared reference to FLAC's metadata blocks
1958    pub fn metadata(&self) -> &crate::metadata::BlockList {
1959        &self.blocks
1960    }
1961
1962    /// Returns total length of all metadata blocks and FLAC tag
1963    pub fn metadata_len(&self) -> u64 {
1964        self.metadata_len
1965    }
1966}
1967
1968impl FrameIterator<std::io::BufReader<std::fs::File>> {
1969    /// Opens new FrameIterator from file on disk
1970    pub fn open<P: AsRef<std::path::Path>>(path: P) -> Result<Self, Error> {
1971        std::fs::File::open(path.as_ref())
1972            .map_err(Error::Io)
1973            .and_then(|f| Self::new(std::io::BufReader::new(f)))
1974    }
1975}
1976
1977impl<R: std::io::Read> Iterator for FrameIterator<R> {
1978    /// Returns both frame and frame's absolute position in stream, in bytes
1979    type Item = Result<(Frame, u64), Error>;
1980
1981    fn next(&mut self) -> Option<Self::Item> {
1982        match self.remaining_samples.as_mut() {
1983            Some(0) => None,
1984            Some(remaining) => {
1985                let offset = self.reader.count;
1986                match Frame::read(&mut self.reader, self.blocks.streaminfo()) {
1987                    Ok(frame) => {
1988                        *remaining = remaining
1989                            .checked_sub(u64::from(u16::from(frame.header.block_size)))
1990                            .unwrap_or_default();
1991                        Some(Ok((frame, offset)))
1992                    }
1993                    Err(err) => Some(Err(err)),
1994                }
1995            }
1996            None => {
1997                // if total number of remaining samples isn't known,
1998                // treat an EOF error as the end of stream
1999                // (this is an uncommon case)
2000                let offset = self.reader.count;
2001                match Frame::read(&mut self.reader, self.blocks.streaminfo()) {
2002                    Ok(frame) => Some(Ok((frame, offset))),
2003                    Err(Error::Io(err)) if err.kind() == std::io::ErrorKind::UnexpectedEof => None,
2004                    Err(err) => Some(Err(err)),
2005                }
2006            }
2007        }
2008    }
2009}
2010
2011impl<R> crate::metadata::Metadata for FrameIterator<R> {
2012    fn channel_count(&self) -> u8 {
2013        self.blocks.streaminfo().channels.get()
2014    }
2015
2016    fn channel_mask(&self) -> crate::metadata::ChannelMask {
2017        self.blocks.channel_mask()
2018    }
2019
2020    fn sample_rate(&self) -> u32 {
2021        self.blocks.streaminfo().sample_rate
2022    }
2023
2024    fn bits_per_sample(&self) -> u32 {
2025        self.blocks.streaminfo().bits_per_sample.into()
2026    }
2027
2028    fn total_samples(&self) -> Option<u64> {
2029        self.blocks.streaminfo().total_samples.map(|s| s.get())
2030    }
2031
2032    fn md5(&self) -> Option<&[u8; 16]> {
2033        self.blocks.streaminfo().md5.as_ref()
2034    }
2035}
2036
2037/// A 32 or 64-bit FLAC file subframe
2038///
2039/// The FLAC format itself is limited to 32-bit samples
2040/// for input and output, as shown in the STREAMINFO metadata
2041/// block.  However, channel correlation means that the
2042/// side (difference) channel needs 1 additional bit.
2043/// Therefore, the side channel of a 32-bit stereo stream
2044/// needs *33* bits to store its samples.
2045///
2046/// Such subframes are considered "wide" and need to
2047/// handle 64-bit samples internally.
2048///
2049/// This is an extremely rare case in practice.
2050#[derive(Debug, Eq, PartialEq)]
2051pub enum SubframeWidth {
2052    /// A common 32-bit subframe
2053    Common(Subframe<i32>),
2054    /// A rare 64-bit subframe
2055    Wide(Subframe<i64>),
2056}
2057
2058/// A FLAC's frame's subframe, one per channel
2059///
2060/// A subframe consists of a subframe header followed by subframe data.
2061#[derive(Debug, Eq, PartialEq)]
2062pub enum Subframe<I> {
2063    /// A CONSTANT subframe, in which all samples are identical
2064    ///
2065    /// | Bits                       | Field    |
2066    /// |----------------------------|----------|
2067    /// | subframe's bits-per-sample | `sample` |
2068    ///
2069    /// This single sample is repeated for all the samples in the subframe.
2070    ///
2071    /// This is typically for long stretches of silence,
2072    /// or for the difference channel when both channels are
2073    /// identical in a stereo stream (false stereo).
2074    ///
2075    /// # Example
2076    ///
2077    /// ```
2078    /// use flac_codec::stream::Subframe;
2079    /// use bitstream_io::{BitReader, BitRead, BigEndian, SignedBitCount};
2080    ///
2081    /// let data: &[u8] = &[
2082    ///     0b0_000000_0,  // subframe header
2083    ///     0x00, 0x00,    // subframe data
2084    /// ];
2085    ///
2086    /// let mut r = BitReader::endian(data, BigEndian);
2087    ///
2088    /// assert_eq!(
2089    ///     r.parse_using::<Subframe<i32>>((20, SignedBitCount::new::<16>())).unwrap(),
2090    ///     Subframe::Constant {
2091    ///         // taken from context
2092    ///         block_size: 20,
2093    ///         // constant subframes always have exactly one sample
2094    ///         // this sample's size is a signed 16-bit value
2095    ///         // taken from the subframe signed bit count
2096    ///         sample: 0x00_00,
2097    ///         // wasted bits-per-sample is taken from the subframe header
2098    ///         wasted_bps: 0,
2099    ///     },
2100    /// );
2101    /// ```
2102    Constant {
2103        /// the subframe's block size in samples
2104        block_size: u16,
2105        /// The subframe's sample
2106        sample: I,
2107        /// Any wasted bits-per-sample
2108        wasted_bps: u32,
2109    },
2110    /// A VERBATIM subframe, in which all samples are stored uncompressed
2111    ///
2112    /// | Bits           | Field      |
2113    /// |----------------|------------|
2114    /// | subframe's bps | `samples₀` |
2115    /// | subframe's bps | `samples₁` |
2116    /// | subframe's bps | `samples₂` |
2117    /// |                | ⋮          |
2118    ///
2119    /// The number of samples equals the frame's block size.
2120    ///
2121    /// This is for random noise which does not compress well
2122    /// by any other method.
2123    ///
2124    /// # Example
2125    ///
2126    /// ```
2127    /// use flac_codec::stream::Subframe;
2128    /// use bitstream_io::{BitReader, BitRead, BigEndian, SignedBitCount};
2129    ///
2130    /// let data: &[u8] = &[
2131    ///     0b0_000001_0,  // subframe header
2132    ///     // subframe data
2133    ///     0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04,
2134    ///     0x00, 0x05, 0x00, 0x06, 0x00, 0x07, 0x00, 0x08, 0x00, 0x09,
2135    ///     0x00, 0x0a, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x0d, 0x00, 0x0e,
2136    ///     0x00, 0x0f, 0x00, 0x10, 0x00, 0x11, 0x00, 0x12, 0x00, 0x13,
2137    /// ];
2138    ///
2139    /// let mut r = BitReader::endian(data, BigEndian);
2140    ///
2141    /// assert_eq!(
2142    ///     r.parse_using::<Subframe<i32>>((20, SignedBitCount::new::<16>())).unwrap(),
2143    ///     Subframe::Verbatim {
2144    ///         // the total number of samples equals the block size
2145    ///         // (20 in this case)
2146    ///         // each sample is a signed 16-bit value,
2147    ///         // taken from the subframe signed bit count
2148    ///         samples: vec![
2149    ///             0x00, 0x01, 0x02, 0x03, 0x04,
2150    ///             0x05, 0x06, 0x07, 0x08, 0x09,
2151    ///             0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
2152    ///             0x0f, 0x10, 0x11, 0x12, 0x13,
2153    ///         ],
2154    ///         // wasted bits-per-sample is taken from the subframe header
2155    ///         wasted_bps: 0,
2156    ///     },
2157    /// );
2158    /// ```
2159    Verbatim {
2160        /// The subframe's samples
2161        samples: Vec<I>,
2162        /// Any wasted bits-per-sample
2163        wasted_bps: u32,
2164    },
2165    /// A FIXED subframe, encoded with a fixed set of parameters
2166    ///
2167    /// | Bits           | Field         |
2168    /// |----------------|---------------|
2169    /// | subframe's bps | `warm_up₀`    |
2170    /// | subframe's bps | `warm_up₁`    |
2171    /// | subframe's bps | `warm_up₂`    |
2172    /// |                | ⋮             |
2173    /// |                | [`Residuals`] |
2174    ///
2175    /// The number of warm-up simples equals the subframe's
2176    /// predictor order (from the subframe header).
2177    ///
2178    /// FIXED subframes have predictor coefficients that are
2179    /// defined by their predictor order.  Because those coefficients
2180    /// require no floating-point math to calculate, these subframes
2181    /// can be encoded by limited hardware with no floating-point
2182    /// capabilities.
2183    ///
2184    /// # Example
2185    ///
2186    /// ```
2187    /// use flac_codec::stream::{Subframe, Residuals, ResidualPartition};
2188    /// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount, SignedBitCount};
2189    ///
2190    /// let data: &[u8] = &[
2191    ///     0b0_001100_0,  // subframe header
2192    ///     // warm-up samples
2193    ///     0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03,
2194    ///     // residuals
2195    ///     0x00, 0x3f, 0xff, 0xc0,
2196    /// ];
2197    ///
2198    /// let mut r = BitReader::endian(data, BigEndian);
2199    ///
2200    /// assert_eq!(
2201    ///     r.parse_using::<Subframe<i32>>((20, SignedBitCount::new::<16>())).unwrap(),
2202    ///     Subframe::Fixed {
2203    ///         // predictor order is determined from subframe header
2204    ///         order: 4,
2205    ///         // the total number of warm-up samples equals the predictor order (4)
2206    ///         // each warm-up sample is a signed 16-bit value,
2207    ///         // taken from the subframe signed bit count
2208    ///         warm_up: vec![0x00, 0x01, 0x02, 0x03],
2209    ///         // the total number of residuals equals the block size
2210    ///         // minus the predictor order,
2211    ///         // which is 20 - 4 = 16 in this case
2212    ///         residuals: Residuals::Method0 {
2213    ///             partitions: vec![
2214    ///                 ResidualPartition::Standard {
2215    ///                     rice: BitCount::new::<0>(),
2216    ///                     residuals: vec![0; 16],
2217    ///                 }
2218    ///             ],
2219    ///         },
2220    ///         // wasted bits-per-sample is taken from the subframe header
2221    ///         wasted_bps: 0,
2222    ///     },
2223    /// );
2224    /// ```
2225    Fixed {
2226        /// The subframe's predictor order from 0 to 4 (inclusive)
2227        order: u8,
2228        /// The subframe's warm-up samples (one per order)
2229        warm_up: Vec<I>,
2230        /// The subframe's residuals
2231        residuals: Residuals<I>,
2232        /// Any wasted bits-per-sample
2233        wasted_bps: u32,
2234    },
2235    /// An LPC subframe, encoded with a variable set of parameters
2236    ///
2237    /// | Bits           | Field            |
2238    /// |----------------|------------------|
2239    /// | subframe's bps | `warm_up₀`       |
2240    /// | subframe's bps | `warm_up₁`       |
2241    /// | subframe's bps | `warm_up₂`       |
2242    /// |                | ⋮                |
2243    /// | 4              | `precision` (+1) |
2244    /// | 5              | `shift`          |
2245    /// | `precision`    | `coefficients₀`  |
2246    /// | `precision`    | `coefficients₁`  |
2247    /// | `precision`    | `coefficients₂`  |
2248    /// |                | ⋮                |
2249    /// |                | [`Residuals`]    |
2250    ///
2251    /// The number of warm-up samples *and* number of predictor
2252    /// coefficients is equal to the subframe's predictor order
2253    /// (from the subframe header).  The `precision` value
2254    /// is used to determine the size of the predictor coefficients.
2255    /// The `shift` value is stored as a signed integer,
2256    /// but negative shifts are *not* supported by the format
2257    /// and should be considered an error.
2258    ///
2259    /// # Example
2260    ///
2261    /// ```
2262    /// use flac_codec::stream::{Subframe, Residuals, ResidualPartition};
2263    /// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount, SignedBitCount};
2264    /// use std::num::NonZero;
2265    ///
2266    /// let data: &[u8] = &[
2267    ///     0b0_100000_0,  // subframe header
2268    ///     // warm-up sample
2269    ///     0x00, 0x00,
2270    ///     // precision + shift + coefficient
2271    ///     0b1011_0101, 0b1_0111110, 0b00101_000,
2272    ///     // residuals
2273    ///     0x02, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x80,
2274    /// ];
2275    ///
2276    /// let mut r = BitReader::endian(data, BigEndian);
2277    ///
2278    /// assert_eq!(
2279    ///     r.parse_using::<Subframe<i32>>((20, SignedBitCount::new::<16>())).unwrap(),
2280    ///     Subframe::Lpc {
2281    ///         // predictor order is determined from the subframe header
2282    ///         order: NonZero::new(1).unwrap(),
2283    ///         // the total number of warm-up samples equals the predictor order (1)
2284    ///         // each warm-up sample is a signed 16-bit value,
2285    ///         // taken from the subframe signed bit count
2286    ///         warm_up: vec![0x00],
2287    ///         // precision is a 4 bit value, plus one
2288    ///         precision: SignedBitCount::new::<{0b1011 + 1}>(),  // 12 bits
2289    ///         // shift is a 5 bit value
2290    ///         shift: 0b0101_1,  // 11
2291    ///         // the total number of coefficients equals the predictor order (1)
2292    ///         // size of each coefficient is a signed 12-bit value (from precision)
2293    ///         coefficients: vec![0b0111110_00101],  // 1989
2294    ///         // the total number of residuals equals the block size
2295    ///         // minus the predictor order,
2296    ///         // which is 20 - 1 = 19 in this case
2297    ///         residuals: Residuals::Method0 {
2298    ///             partitions: vec![
2299    ///                 ResidualPartition::Standard {
2300    ///                     rice: BitCount::new::<1>(),
2301    ///                     residuals: vec![
2302    ///                          1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2303    ///                          2, 2, 2, 2, 2, 2, 2, 2, 2
2304    ///                     ],
2305    ///                 }
2306    ///             ],
2307    ///         },
2308    ///         // wasted bits-per-sample is taken from the subframe header
2309    ///         wasted_bps: 0,
2310    ///     },
2311    /// );
2312    /// ```
2313    Lpc {
2314        /// The subframe's predictor order
2315        order: NonZero<u8>,
2316        /// The subframe's warm-up samples (one per order)
2317        warm_up: Vec<I>,
2318        /// The subframe's QLP precision
2319        precision: SignedBitCount<15>,
2320        /// The subframe's QLP shift
2321        shift: u32,
2322        /// The subframe's QLP coefficients (one per order)
2323        coefficients: Vec<i32>,
2324        /// The subframe's residuals
2325        residuals: Residuals<I>,
2326        /// Any wasted bits-per-sample
2327        wasted_bps: u32,
2328    },
2329}
2330
2331impl<I> Subframe<I> {
2332    /// Our subframe type
2333    pub fn subframe_type(&self) -> SubframeType {
2334        match self {
2335            Self::Constant { .. } => SubframeType::Constant,
2336            Self::Verbatim { .. } => SubframeType::Verbatim,
2337            Self::Fixed { .. } => SubframeType::Fixed,
2338            Self::Lpc { .. } => SubframeType::Lpc,
2339        }
2340    }
2341}
2342
2343impl<I: SignedInteger> Subframe<I> {
2344    /// Decodes subframe to samples
2345    ///
2346    /// Note that decoding subframes to samples using this method
2347    /// is intended for analysis purposes.  The [`crate::decode`]
2348    /// module's decoders are preferred for general-purpose
2349    /// decoding as they perform fewer temporary allocations.
2350    pub fn decode(&self) -> Box<dyn Iterator<Item = I> + '_> {
2351        fn predict<I: SignedInteger>(coefficients: &[i64], qlp_shift: u32, channel: &mut [I]) {
2352            for split in coefficients.len()..channel.len() {
2353                let (predicted, residuals) = channel.split_at_mut(split);
2354
2355                residuals[0] += I::from_i64(
2356                    predicted
2357                        .iter()
2358                        .rev()
2359                        .zip(coefficients)
2360                        .map(|(x, y)| (*x).into() * y)
2361                        .sum::<i64>()
2362                        >> qlp_shift,
2363                );
2364            }
2365        }
2366
2367        match self {
2368            Self::Constant {
2369                sample,
2370                block_size,
2371                wasted_bps,
2372            } => Box::new((0..*block_size).map(move |_| *sample << *wasted_bps)),
2373            Self::Verbatim {
2374                samples,
2375                wasted_bps,
2376            } => Box::new(samples.iter().map(move |sample| *sample << *wasted_bps)),
2377            Self::Fixed {
2378                order,
2379                warm_up,
2380                residuals,
2381                wasted_bps,
2382            } => {
2383                let mut samples = warm_up.clone();
2384                samples.extend(residuals.residuals());
2385                predict(
2386                    SubframeHeaderType::FIXED_COEFFS[*order as usize],
2387                    0,
2388                    &mut samples,
2389                );
2390                Box::new(samples.into_iter().map(move |sample| sample << *wasted_bps))
2391            }
2392            Self::Lpc {
2393                warm_up,
2394                coefficients,
2395                residuals,
2396                wasted_bps,
2397                shift,
2398                ..
2399            } => {
2400                let mut samples = warm_up.clone();
2401                samples.extend(residuals.residuals());
2402                predict(
2403                    &coefficients
2404                        .iter()
2405                        .copied()
2406                        .map(i64::from)
2407                        .collect::<Vec<_>>(),
2408                    *shift,
2409                    &mut samples,
2410                );
2411                Box::new(samples.into_iter().map(move |sample| sample << *wasted_bps))
2412            }
2413        }
2414    }
2415}
2416
2417fn read_subframe<const MAX: u32, R, I>(
2418    r: &mut R,
2419    block_size: u16,
2420    bits_per_sample: SignedBitCount<MAX>,
2421) -> Result<Subframe<I>, Error>
2422where
2423    R: BitRead + ?Sized,
2424    I: SignedInteger,
2425{
2426    match r.parse()? {
2427        SubframeHeader {
2428            type_: SubframeHeaderType::Constant,
2429            wasted_bps,
2430        } => Ok(Subframe::Constant {
2431            block_size,
2432            sample: r.read_signed_counted(
2433                bits_per_sample
2434                    .checked_sub::<MAX>(wasted_bps)
2435                    .ok_or(Error::ExcessiveWastedBits)?,
2436            )?,
2437            wasted_bps,
2438        }),
2439        SubframeHeader {
2440            type_: SubframeHeaderType::Verbatim,
2441            wasted_bps,
2442        } => {
2443            let effective_bps = bits_per_sample
2444                .checked_sub::<MAX>(wasted_bps)
2445                .ok_or(Error::ExcessiveWastedBits)?;
2446
2447            Ok(Subframe::Verbatim {
2448                samples: (0..block_size)
2449                    .map(|_| r.read_signed_counted::<MAX, I>(effective_bps))
2450                    .collect::<Result<Vec<_>, _>>()?,
2451                wasted_bps,
2452            })
2453        }
2454        SubframeHeader {
2455            type_: SubframeHeaderType::Fixed { order },
2456            wasted_bps,
2457        } => {
2458            let effective_bps = bits_per_sample
2459                .checked_sub::<MAX>(wasted_bps)
2460                .ok_or(Error::ExcessiveWastedBits)?;
2461
2462            Ok(Subframe::Fixed {
2463                order,
2464                warm_up: (0..order)
2465                    .map(|_| r.read_signed_counted::<MAX, I>(effective_bps))
2466                    .collect::<Result<Vec<_>, _>>()?,
2467                residuals: r.parse_using((block_size.into(), order.into()))?,
2468                wasted_bps,
2469            })
2470        }
2471        SubframeHeader {
2472            type_: SubframeHeaderType::Lpc { order },
2473            wasted_bps,
2474        } => {
2475            let effective_bps = bits_per_sample
2476                .checked_sub::<MAX>(wasted_bps)
2477                .ok_or(Error::ExcessiveWastedBits)?;
2478
2479            let warm_up = (0..order.get())
2480                .map(|_| r.read_signed_counted::<MAX, I>(effective_bps))
2481                .collect::<Result<Vec<_>, _>>()?;
2482
2483            let precision: SignedBitCount<15> = r
2484                .read_count::<0b1111>()?
2485                .checked_add(1)
2486                .and_then(|c| c.signed_count())
2487                .ok_or(Error::InvalidQlpPrecision)?;
2488
2489            let shift: u32 = r
2490                .read::<5, i32>()?
2491                .try_into()
2492                .map_err(|_| Error::NegativeLpcShift)?;
2493
2494            let coefficients = (0..order.get())
2495                .map(|_| r.read_signed_counted(precision))
2496                .collect::<Result<Vec<_>, _>>()?;
2497
2498            Ok(Subframe::Lpc {
2499                order,
2500                warm_up,
2501                precision,
2502                shift,
2503                coefficients,
2504                residuals: r.parse_using((block_size.into(), order.get().into()))?,
2505                wasted_bps,
2506            })
2507        }
2508    }
2509}
2510
2511impl FromBitStreamUsing for Subframe<i32> {
2512    type Context = (u16, SignedBitCount<32>);
2513    type Error = Error;
2514
2515    fn from_reader<R: BitRead + ?Sized>(
2516        r: &mut R,
2517        (block_size, bits_per_sample): (u16, SignedBitCount<32>),
2518    ) -> Result<Self, Error> {
2519        read_subframe(r, block_size, bits_per_sample)
2520    }
2521}
2522
2523impl FromBitStreamUsing for Subframe<i64> {
2524    type Context = (u16, SignedBitCount<33>);
2525    type Error = Error;
2526
2527    fn from_reader<R: BitRead + ?Sized>(
2528        r: &mut R,
2529        (block_size, bits_per_sample): (u16, SignedBitCount<33>),
2530    ) -> Result<Self, Error> {
2531        read_subframe(r, block_size, bits_per_sample)
2532    }
2533}
2534
2535fn write_subframe<const MAX: u32, W, I>(
2536    w: &mut W,
2537    bits_per_sample: SignedBitCount<MAX>,
2538    subframe: &Subframe<I>,
2539) -> Result<(), Error>
2540where
2541    W: BitWrite + ?Sized,
2542    I: SignedInteger,
2543{
2544    match subframe {
2545        Subframe::Constant {
2546            sample, wasted_bps, ..
2547        } => {
2548            w.build(&SubframeHeader {
2549                type_: SubframeHeaderType::Constant,
2550                wasted_bps: *wasted_bps,
2551            })?;
2552
2553            w.write_signed_counted(
2554                bits_per_sample
2555                    .checked_sub::<MAX>(*wasted_bps)
2556                    .ok_or(Error::ExcessiveWastedBits)?,
2557                *sample,
2558            )?;
2559
2560            Ok(())
2561        }
2562        Subframe::Verbatim {
2563            samples,
2564            wasted_bps,
2565        } => {
2566            let effective_bps = bits_per_sample
2567                .checked_sub::<MAX>(*wasted_bps)
2568                .ok_or(Error::ExcessiveWastedBits)?;
2569
2570            w.build(&SubframeHeader {
2571                type_: SubframeHeaderType::Verbatim,
2572                wasted_bps: *wasted_bps,
2573            })?;
2574
2575            for sample in samples {
2576                w.write_signed_counted(effective_bps, *sample)?;
2577            }
2578
2579            Ok(())
2580        }
2581        Subframe::Fixed {
2582            order,
2583            warm_up,
2584            residuals,
2585            wasted_bps,
2586        } => {
2587            assert_eq!(*order as usize, warm_up.len());
2588
2589            let effective_bps = bits_per_sample
2590                .checked_sub::<MAX>(*wasted_bps)
2591                .ok_or(Error::ExcessiveWastedBits)?;
2592
2593            w.build(&SubframeHeader {
2594                type_: SubframeHeaderType::Fixed { order: *order },
2595                wasted_bps: *wasted_bps,
2596            })?;
2597
2598            for sample in warm_up {
2599                w.write_signed_counted(effective_bps, *sample)?;
2600            }
2601
2602            w.build(residuals)?;
2603
2604            Ok(())
2605        }
2606        Subframe::Lpc {
2607            order,
2608            warm_up,
2609            precision,
2610            shift,
2611            coefficients,
2612            residuals,
2613            wasted_bps,
2614        } => {
2615            assert_eq!(order.get() as usize, warm_up.len());
2616            assert_eq!(order.get() as usize, coefficients.len());
2617
2618            let effective_bps = bits_per_sample
2619                .checked_sub::<MAX>(*wasted_bps)
2620                .ok_or(Error::ExcessiveWastedBits)?;
2621
2622            w.build(&SubframeHeader {
2623                type_: SubframeHeaderType::Lpc { order: *order },
2624                wasted_bps: *wasted_bps,
2625            })?;
2626
2627            for sample in warm_up {
2628                w.write_signed_counted(effective_bps, *sample)?;
2629            }
2630
2631            w.write_count(
2632                precision
2633                    .checked_sub::<0b1111>(1)
2634                    .ok_or(Error::InvalidQlpPrecision)?
2635                    .count(),
2636            )?;
2637
2638            w.write::<5, i32>(i32::try_from(*shift).unwrap())?;
2639
2640            for coeff in coefficients {
2641                w.write_signed_counted(*precision, *coeff)?;
2642            }
2643
2644            w.build(residuals)?;
2645
2646            Ok(())
2647        }
2648    }
2649}
2650
2651impl ToBitStreamUsing for Subframe<i32> {
2652    type Context = SignedBitCount<32>;
2653    type Error = Error;
2654
2655    fn to_writer<W: BitWrite + ?Sized>(
2656        &self,
2657        w: &mut W,
2658        bits_per_sample: SignedBitCount<32>,
2659    ) -> Result<(), Error> {
2660        write_subframe(w, bits_per_sample, self)
2661    }
2662}
2663
2664impl ToBitStreamUsing for Subframe<i64> {
2665    type Context = SignedBitCount<33>;
2666    type Error = Error;
2667
2668    fn to_writer<W: BitWrite + ?Sized>(
2669        &self,
2670        w: &mut W,
2671        bits_per_sample: SignedBitCount<33>,
2672    ) -> Result<(), Error> {
2673        write_subframe(w, bits_per_sample, self)
2674    }
2675}
2676
2677/// A residual block's type
2678#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash, Ord, PartialOrd)]
2679pub enum CodingMethod {
2680    /// Partitioned Rice code with 4-bit parameters
2681    Rice,
2682    /// Partitioned Rice code with 5-bit parameters
2683    Rice2,
2684}
2685
2686impl std::fmt::Display for CodingMethod {
2687    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
2688        match self {
2689            Self::Rice => "RICE".fmt(f),
2690            Self::Rice2 => "RICE2".fmt(f),
2691        }
2692    }
2693}
2694
2695/// Residual values for FIXED or LPC subframes
2696///
2697/// | Bits | Meaning |
2698/// |-----:|---------|
2699/// | 2    | residual coding method
2700/// | 4    | partition order
2701/// |      | residual partition₀
2702/// |      | (residual partition₁)
2703/// |      | ⋮
2704///
2705/// The residual coding method can be 0 or 1.
2706/// A coding method of 0 means 4-bit Rice parameters
2707/// in residual partitions.  A coding method of 5
2708/// means 5-bit Rice parameters in residual partitions
2709/// (method 0 is the common case).
2710///
2711/// The number of residual partitions equals
2712/// 2ⁿ where n is the partition order.
2713///
2714/// # Example
2715/// ```
2716/// use flac_codec::stream::{Residuals, ResidualPartition};
2717/// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount};
2718///
2719/// let data: &[u8] = &[
2720///     0b00_0000_00,  // coding method + partition order + partition
2721///     // residual partition
2722///     0b01010001,
2723///     0b00010001,
2724///     0b00010001,
2725///     0b00010001,
2726///     0b00010001,
2727///     0b00010001,
2728///     0b00010001,
2729///     0b00010001,
2730///     0b00010001,
2731///     0b00010000,
2732///     0b00000000,
2733/// ];
2734///
2735/// let mut r = BitReader::endian(data, BigEndian);
2736///
2737/// assert_eq!(
2738///     r.parse_using::<Residuals<i32>>((20, 1)).unwrap(),
2739///     // coding method = 0b00
2740///     // partition order = 0b0000, or 1 partition
2741///     Residuals::Method0 {
2742///         partitions: vec![
2743///             ResidualPartition::Standard {
2744///                 rice: BitCount::new::<1>(),
2745///                 residuals: vec![
2746///                      1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2747///                      2, 2, 2, 2, 2, 2, 2, 2, 2
2748///                 ],
2749///             }
2750///         ],
2751///     },
2752/// );
2753/// ```
2754#[derive(Debug, Eq, PartialEq)]
2755pub enum Residuals<I> {
2756    /// Coding method 0
2757    Method0 {
2758        /// The residual partitions
2759        partitions: Vec<ResidualPartition<0b1111, I>>,
2760    },
2761    /// Coding method 1
2762    Method1 {
2763        /// The residual partitions
2764        partitions: Vec<ResidualPartition<0b11111, I>>,
2765    },
2766}
2767
2768impl<I> Residuals<I> {
2769    /// The type of coding method in use, either Rice or Rice2
2770    pub fn coding_method(&self) -> CodingMethod {
2771        match self {
2772            Self::Method0 { .. } => CodingMethod::Rice,
2773            Self::Method1 { .. } => CodingMethod::Rice2,
2774        }
2775    }
2776
2777    /// The residual block's partition order
2778    pub fn partition_order(&self) -> u32 {
2779        match self {
2780            Self::Method0 { partitions } => partitions.len().ilog2(),
2781            Self::Method1 { partitions } => partitions.len().ilog2(),
2782        }
2783    }
2784}
2785
2786impl<I: SignedInteger> Residuals<I> {
2787    /// Iterates over all individual residual values
2788    fn residuals(&self) -> Box<dyn Iterator<Item = I> + '_> {
2789        match self {
2790            Self::Method0 { partitions } => Box::new(partitions.iter().flat_map(|p| p.residuals())),
2791            Self::Method1 { partitions } => Box::new(partitions.iter().flat_map(|p| p.residuals())),
2792        }
2793    }
2794}
2795
2796impl<I: SignedInteger> FromBitStreamUsing for Residuals<I> {
2797    type Context = (usize, usize);
2798    type Error = Error;
2799
2800    fn from_reader<R: BitRead + ?Sized>(
2801        r: &mut R,
2802        (block_size, predictor_order): (usize, usize),
2803    ) -> Result<Self, Error> {
2804        fn read_partitions<const RICE_MAX: u32, R: BitRead + ?Sized, I: SignedInteger>(
2805            reader: &mut R,
2806            (block_size, predictor_order): (usize, usize),
2807        ) -> Result<Vec<ResidualPartition<RICE_MAX, I>>, Error> {
2808            let partition_order = reader.read::<4, u32>()?;
2809            let partition_count = 1 << partition_order;
2810
2811            (0..partition_count)
2812                .map(|p| {
2813                    reader.parse_using(
2814                        (block_size / partition_count)
2815                            .checked_sub(if p == 0 { predictor_order } else { 0 })
2816                            .ok_or(Error::InvalidPartitionOrder)?,
2817                    )
2818                })
2819                .collect()
2820        }
2821
2822        match r.read::<2, u8>()? {
2823            0 => Ok(Self::Method0 {
2824                partitions: read_partitions::<0b1111, R, I>(r, (block_size, predictor_order))?,
2825            }),
2826            1 => Ok(Self::Method1 {
2827                partitions: read_partitions::<0b11111, R, I>(r, (block_size, predictor_order))?,
2828            }),
2829            _ => Err(Error::InvalidCodingMethod),
2830        }
2831    }
2832}
2833
2834impl<I: SignedInteger> ToBitStream for Residuals<I> {
2835    type Error = Error;
2836
2837    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
2838        fn write_partitions<const RICE_MAX: u32, W: BitWrite + ?Sized, I: SignedInteger>(
2839            writer: &mut W,
2840            partitions: &[ResidualPartition<RICE_MAX, I>],
2841        ) -> Result<(), Error> {
2842            assert!(!partitions.is_empty());
2843            assert!(partitions.len().is_power_of_two());
2844
2845            writer.write::<4, _>(partitions.len().ilog2())?;
2846
2847            for partition in partitions.iter() {
2848                writer.build(partition)?;
2849            }
2850
2851            Ok(())
2852        }
2853
2854        match self {
2855            Self::Method0 { partitions } => {
2856                w.write::<2, u8>(0)?; // coding method
2857                write_partitions(w, partitions)
2858            }
2859            Self::Method1 { partitions } => {
2860                w.write::<2, u8>(1)?; // coding method
2861                write_partitions(w, partitions)
2862            }
2863        }
2864    }
2865}
2866
2867/// An individual residual block partition
2868///
2869/// Each partition consists of a Rice parameter
2870/// followed by an optional escape code and signed residual values.
2871/// The number of bits to read for the Rice parameters
2872/// depends on if we're using coding method 0 or 1.
2873/// If the Rice parameter equals the maximum,
2874/// it means the partition is escaped in some way
2875/// (this is an uncommon case).
2876///
2877/// | Bits    | Meaning |
2878/// |--------:|---------|
2879/// | 4 or 5  | Rice parameter
2880/// | (5)     | escape code if parameter is `1111` or `11111`
2881///
2882/// The total number of residuals in the partition is:
2883///
2884/// > block size ÷ partition count - predictor order
2885///
2886/// for the first partition, and:
2887///
2888/// > block size ÷ partition count
2889///
2890/// for subsequent partitions.
2891///
2892/// If the partition is escaped, we read an additional 5 bit value
2893/// to determine the size of each signed residual in the partition.
2894/// If the *escape code* is 0, all the residuals in the partition are 0
2895/// (this is an even more uncommon case).
2896///
2897/// # Example
2898/// ```
2899/// use flac_codec::stream::ResidualPartition;
2900/// use bitstream_io::{BitReader, BitRead, BigEndian, BitCount};
2901///
2902/// let data: &[u8] = &[
2903///     0b0001_01_0_0,  // Rice code + residuals
2904///     0b01_0_001_0_0,
2905///     0b01_0_001_0_0,
2906///     0b01_0_001_0_0,
2907///     0b01_0_001_0_0,
2908///     0b01_0_001_0_0,
2909///     0b01_0_001_0_0,
2910///     0b01_0_001_0_0,
2911///     0b01_0_001_0_0,
2912///     0b01_0_001_0_0,
2913/// ];
2914///
2915/// let mut r = BitReader::endian(data, BigEndian);
2916/// assert_eq!(
2917///     r.parse_using::<ResidualPartition<0b1111, i32>>(19).unwrap(),
2918///     ResidualPartition::Standard {
2919///         rice: BitCount::new::<0b0001>(),
2920///         residuals: vec![
2921///              1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2922///              2, 2, 2, 2, 2, 2, 2, 2, 2
2923///         ],
2924///     },
2925/// );
2926/// ```
2927///
2928/// Each individual residual is a unary value with a stop bit of 1
2929/// for the most-significant bits, followed by "Rice" number of
2930/// bits as the least significant bits, combined into a single
2931/// unsigned value.
2932///
2933/// Unary-encoding is simply counting the number of 0 bits
2934/// before the next 1 bit:
2935///
2936/// | Bits    | Value |
2937/// |--------:|-------|
2938/// | `1`     | 0
2939/// | `01`    | 1
2940/// | `001`   | 2
2941/// | `0001`  | 3
2942/// | `00001` | 4
2943/// | ⋮       |
2944///
2945/// Unlike regular twos-complement signed values, individual residuals
2946/// are stored with the sign in the *least* significant bit position.
2947/// They can be transformed from unsigned to signed like:
2948/// ```
2949/// fn unsigned_to_signed(unsigned: u32) -> i32 {
2950///     if (unsigned & 1) == 1 {
2951///         // negative residual
2952///         -((unsigned >> 1) as i32) - 1
2953///     } else {
2954///         // positive residual
2955///         (unsigned >> 1) as i32
2956///     }
2957/// }
2958/// ```
2959///
2960/// In our example, above, the Rice parameter happens to be 1
2961/// and all the sign bits happen to be 0, so the value of each
2962/// signed residual is simply its preceding unary value
2963/// (which are all `01` or `001`, meaning 1 and 2).
2964///
2965/// As one can see, the smaller the value each residual has,
2966/// the smaller it can be when written to disk.
2967/// And the key to making residual values small is to choose
2968/// predictor coefficients which best match the input signal.
2969/// The more accurate the prediction, the less difference
2970/// there is between the predicted values and the actual
2971/// values - which means smaller residuals - which means
2972/// better compression.
2973#[derive(Debug, Eq, PartialEq)]
2974pub enum ResidualPartition<const RICE_MAX: u32, I> {
2975    /// A standard residual partition
2976    Standard {
2977        /// The partition's Rice parameter
2978        rice: BitCount<RICE_MAX>,
2979        /// The partition's residuals
2980        residuals: Vec<I>,
2981    },
2982    /// An escaped residual partition
2983    Escaped {
2984        /// The size of each residual in bits
2985        escape_size: SignedBitCount<0b11111>,
2986        /// The partition's residuals
2987        residuals: Vec<I>,
2988    },
2989    /// A partition in which all residuals are 0
2990    Constant {
2991        /// The length of the partition in samples
2992        partition_len: usize,
2993    },
2994}
2995
2996impl<const RICE_MAX: u32, I: SignedInteger> ResidualPartition<RICE_MAX, I> {
2997    fn residuals(&self) -> Box<dyn Iterator<Item = I> + '_> {
2998        match self {
2999            Self::Standard { residuals, .. } | Self::Escaped { residuals, .. } => {
3000                Box::new(residuals.iter().copied())
3001            }
3002            Self::Constant { partition_len } => {
3003                Box::new(std::iter::repeat_n(I::default(), *partition_len))
3004            }
3005        }
3006    }
3007}
3008
3009impl<const RICE_MAX: u32, I: SignedInteger> FromBitStreamUsing for ResidualPartition<RICE_MAX, I> {
3010    type Context = usize;
3011    type Error = Error;
3012
3013    fn from_reader<R: BitRead + ?Sized>(r: &mut R, partition_len: usize) -> Result<Self, Error> {
3014        match r.parse::<ResidualPartitionHeader<RICE_MAX>>()? {
3015            ResidualPartitionHeader::Standard { rice } => Ok(Self::Standard {
3016                residuals: (0..partition_len)
3017                    .map(|_| {
3018                        let msb = r.read_unary::<1>()?;
3019                        let lsb = r.read_counted::<RICE_MAX, u32>(rice)?;
3020                        let unsigned = (msb << u32::from(rice)) | lsb;
3021                        Ok::<_, Error>(if (unsigned & 1) == 1 {
3022                            -(I::from_u32(unsigned >> 1)) - I::ONE
3023                        } else {
3024                            I::from_u32(unsigned >> 1)
3025                        })
3026                    })
3027                    .collect::<Result<Vec<_>, _>>()?,
3028                rice,
3029            }),
3030            ResidualPartitionHeader::Escaped { escape_size } => Ok(Self::Escaped {
3031                residuals: (0..partition_len)
3032                    .map(|_| r.read_signed_counted(escape_size))
3033                    .collect::<Result<Vec<_>, _>>()?,
3034                escape_size,
3035            }),
3036            ResidualPartitionHeader::Constant => Ok(Self::Constant { partition_len }),
3037        }
3038    }
3039}
3040
3041impl<const RICE_MAX: u32, I: SignedInteger> ToBitStream for ResidualPartition<RICE_MAX, I> {
3042    type Error = Error;
3043
3044    fn to_writer<W: BitWrite + ?Sized>(&self, w: &mut W) -> Result<(), Error> {
3045        match self {
3046            Self::Standard { residuals, rice } => {
3047                w.build(&ResidualPartitionHeader::Standard { rice: *rice })?;
3048
3049                let mask = rice.mask_lsb();
3050
3051                for residual in residuals {
3052                    let (msb, lsb) = mask(if residual.is_negative() {
3053                        (((-*residual).to_u32() - 1) << 1) + 1
3054                    } else {
3055                        (*residual).to_u32() << 1
3056                    });
3057                    w.write_unary::<1>(msb)?;
3058                    w.write_checked(lsb)?;
3059                }
3060                Ok(())
3061            }
3062            Self::Escaped {
3063                escape_size,
3064                residuals,
3065            } => {
3066                w.build(&ResidualPartitionHeader::<RICE_MAX>::Escaped {
3067                    escape_size: *escape_size,
3068                })?;
3069
3070                for residual in residuals {
3071                    w.write_signed_counted(*escape_size, *residual)?;
3072                }
3073
3074                Ok(())
3075            }
3076            Self::Constant { .. } => Ok(w.build(&ResidualPartitionHeader::<RICE_MAX>::Constant)?),
3077        }
3078    }
3079}