Skip to main content

threers_codec/
flac.rs

1//! FLAC decoding (native `.flac` streams and FLAC-in-Ogg via
2//! [`super::ogg`]): STREAMINFO, frames with constant / verbatim / fixed /
3//! LPC subframes, wasted bits, Rice and escaped residuals, and the three
4//! stereo decorrelations, with the frame CRC-8 / CRC-16 checked. Lossless,
5//! so the integer samples are the encoder's exactly.
6
7// Ported loop structure is kept as in the C reference.
8#![allow(
9    clippy::needless_range_loop,
10    clippy::manual_memcpy,
11    clippy::unnecessary_cast,
12    clippy::manual_is_multiple_of
13)]
14
15/// The `STREAMINFO` metadata block.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct StreamInfo {
18    /// Smallest block size in the stream, in samples.
19    pub min_block: u16,
20    /// Largest block size in the stream, in samples.
21    pub max_block: u16,
22    /// Samples per second.
23    pub sample_rate: u32,
24    /// Channel count, 1 to 8.
25    pub channels: u8,
26    /// Bits per sample, 4 to 32.
27    pub bits_per_sample: u8,
28    /// Samples per channel, or 0 when the encoder did not know.
29    pub total_samples: u64,
30}
31
32/// Decoded FLAC: per-channel integer samples at `bits_per_sample`.
33#[derive(Debug, Clone)]
34pub struct Flac {
35    /// The stream's `STREAMINFO`.
36    pub info: StreamInfo,
37    /// One `Vec` per channel.
38    pub channels: Vec<Vec<i32>>,
39}
40
41impl Flac {
42    /// `int / 2^(bits-1)` (libsndfile's float normalisation), per channel.
43    pub fn to_f32(&self) -> Vec<Vec<f32>> {
44        let s = (1u64 << (self.info.bits_per_sample - 1)) as f64;
45        self.channels
46            .iter()
47            .map(|c| c.iter().map(|&v| (v as f64 / s) as f32).collect())
48            .collect()
49    }
50}
51
52struct Bits<'a> {
53    d: &'a [u8],
54    pos: usize,
55}
56
57impl<'a> Bits<'a> {
58    fn new(d: &'a [u8]) -> Self {
59        Self { d, pos: 0 }
60    }
61    fn bit(&mut self) -> Result<u32, String> {
62        let b = *self.d.get(self.pos >> 3).ok_or("FLAC stream truncated")?;
63        let v = (b >> (7 - (self.pos & 7))) & 1;
64        self.pos += 1;
65        Ok(v as u32)
66    }
67    fn bits(&mut self, n: u32) -> Result<u64, String> {
68        let mut v = 0u64;
69        let mut n = n;
70        while n > 0 {
71            if self.pos & 7 == 0 && n >= 8 {
72                let b = *self.d.get(self.pos >> 3).ok_or("FLAC stream truncated")?;
73                v = (v << 8) | b as u64;
74                self.pos += 8;
75                n -= 8;
76            } else {
77                v = (v << 1) | self.bit()? as u64;
78                n -= 1;
79            }
80        }
81        Ok(v)
82    }
83    fn signed(&mut self, n: u32) -> Result<i64, String> {
84        if n == 0 {
85            return Ok(0);
86        }
87        let v = self.bits(n)? as i64;
88        Ok((v << (64 - n)) >> (64 - n))
89    }
90    fn unary(&mut self) -> Result<u32, String> {
91        let mut n = 0;
92        while self.bit()? == 0 {
93            n += 1;
94        }
95        Ok(n)
96    }
97    fn align(&mut self) {
98        self.pos = (self.pos + 7) & !7;
99    }
100    fn byte_pos(&self) -> usize {
101        self.pos >> 3
102    }
103}
104
105fn crc8(d: &[u8]) -> u8 {
106    let mut c = 0u8;
107    for &b in d {
108        c ^= b;
109        for _ in 0..8 {
110            c = if c & 0x80 != 0 {
111                (c << 1) ^ 0x07
112            } else {
113                c << 1
114            };
115        }
116    }
117    c
118}
119
120fn crc16(d: &[u8]) -> u16 {
121    let mut c = 0u16;
122    for &b in d {
123        c ^= (b as u16) << 8;
124        for _ in 0..8 {
125            c = if c & 0x8000 != 0 {
126                (c << 1) ^ 0x8005
127            } else {
128                c << 1
129            };
130        }
131    }
132    c
133}
134
135/// Parse a STREAMINFO block body (34 bytes).
136pub fn parse_streaminfo(b: &[u8]) -> Result<StreamInfo, String> {
137    if b.len() < 34 {
138        return Err("short STREAMINFO".into());
139    }
140    let mut r = Bits::new(b);
141    let min_block = r.bits(16)? as u16;
142    let max_block = r.bits(16)? as u16;
143    r.bits(24)?;
144    r.bits(24)?;
145    let sample_rate = r.bits(20)? as u32;
146    let channels = r.bits(3)? as u8 + 1;
147    let bits_per_sample = r.bits(5)? as u8 + 1;
148    let total_samples = r.bits(36)?;
149    Ok(StreamInfo {
150        min_block,
151        max_block,
152        sample_rate,
153        channels,
154        bits_per_sample,
155        total_samples,
156    })
157}
158
159/// Decode one frame starting at `d[0]`; returns its samples per channel and
160/// its length in bytes.
161pub fn decode_frame(d: &[u8], info: &StreamInfo) -> Result<(Vec<Vec<i32>>, usize), String> {
162    let mut r = Bits::new(d);
163    if r.bits(14)? != 0x3ffe {
164        return Err("FLAC frame sync not found".into());
165    }
166    r.bits(1)?;
167    let _variable = r.bit()?;
168    let bs_code = r.bits(4)? as u32;
169    let sr_code = r.bits(4)? as u32;
170    let ch_code = r.bits(4)? as u32;
171    let ss_code = r.bits(3)? as u32;
172    r.bits(1)?;
173    // UTF-8-style coded frame/sample number.
174    let first = r.bits(8)? as u32;
175    let extra = (!first as u8).leading_zeros().saturating_sub(1) as u32;
176    let extra = if first & 0x80 == 0 { 0 } else { extra };
177    for _ in 0..extra {
178        r.bits(8)?;
179    }
180    let block = match bs_code {
181        1 => 192,
182        2..=5 => 576 << (bs_code - 2),
183        6 => r.bits(8)? as u32 + 1,
184        7 => r.bits(16)? as u32 + 1,
185        8..=15 => 256 << (bs_code - 8),
186        _ => return Err("reserved FLAC block size".into()),
187    } as usize;
188    match sr_code {
189        12 => {
190            r.bits(8)?;
191        }
192        13 | 14 => {
193            r.bits(16)?;
194        }
195        15 => return Err("invalid FLAC sample rate code".into()),
196        _ => {}
197    }
198    let hdr_end = r.byte_pos();
199    let crc = r.bits(8)? as u8;
200    if crc8(&d[..hdr_end]) != crc {
201        return Err("FLAC frame header CRC mismatch".into());
202    }
203    let bps = match ss_code {
204        0 => info.bits_per_sample as u32,
205        1 => 8,
206        2 => 12,
207        4 => 16,
208        5 => 20,
209        6 => 24,
210        7 => 32,
211        _ => return Err("reserved FLAC sample size".into()),
212    };
213    let (n_ch, decor) = match ch_code {
214        0..=7 => (ch_code as usize + 1, 0),
215        8..=10 => (2, ch_code),
216        _ => return Err("reserved FLAC channel assignment".into()),
217    };
218    let mut chans = Vec::with_capacity(n_ch);
219    for c in 0..n_ch {
220        // The side channel carries one extra bit.
221        let side = (decor == 8 && c == 1) || (decor == 9 && c == 0) || (decor == 10 && c == 1);
222        chans.push(subframe(&mut r, block, bps + side as u32)?);
223    }
224    r.align();
225    let end = r.byte_pos();
226    let crc = r.bits(16)? as u16;
227    if crc16(&d[..end]) != crc {
228        return Err("FLAC frame CRC mismatch".into());
229    }
230    let out: Vec<Vec<i32>> = match decor {
231        8 => {
232            // left/side
233            let (l, s) = (&chans[0], &chans[1]);
234            let r: Vec<i64> = l.iter().zip(s).map(|(&l, &s)| l - s).collect();
235            vec![to32(l), to32(&r)]
236        }
237        9 => {
238            // side/right
239            let (s, rr) = (&chans[0], &chans[1]);
240            let l: Vec<i64> = s.iter().zip(rr).map(|(&s, &r)| s + r).collect();
241            vec![to32(&l), to32(rr)]
242        }
243        10 => {
244            // mid/side
245            let (m, s) = (&chans[0], &chans[1]);
246            let mut l = Vec::with_capacity(block);
247            let mut rr = Vec::with_capacity(block);
248            for (&m, &s) in m.iter().zip(s) {
249                let m = (m << 1) | (s & 1);
250                l.push((m + s) >> 1);
251                rr.push((m - s) >> 1);
252            }
253            vec![to32(&l), to32(&rr)]
254        }
255        _ => chans.iter().map(|c| to32(c)).collect(),
256    };
257    Ok((out, end + 2))
258}
259
260fn to32(v: &[i64]) -> Vec<i32> {
261    v.iter().map(|&x| x as i32).collect()
262}
263
264fn subframe(r: &mut Bits, block: usize, bps: u32) -> Result<Vec<i64>, String> {
265    if r.bit()? != 0 {
266        return Err("FLAC subframe padding bit set".into());
267    }
268    let kind = r.bits(6)? as u32;
269    let mut wasted = 0;
270    if r.bit()? == 1 {
271        wasted = r.unary()? + 1;
272    }
273    let bps = bps - wasted;
274    let mut s = match kind {
275        0 => vec![r.signed(bps)?; block],
276        1 => (0..block)
277            .map(|_| r.signed(bps))
278            .collect::<Result<_, _>>()?,
279        8..=12 => {
280            let order = (kind - 8) as usize;
281            let mut s: Vec<i64> = (0..order)
282                .map(|_| r.signed(bps))
283                .collect::<Result<_, _>>()?;
284            residual(r, block, order, &mut s)?;
285            for i in order..block {
286                let p = match order {
287                    0 => 0,
288                    1 => s[i - 1],
289                    2 => 2 * s[i - 1] - s[i - 2],
290                    3 => 3 * s[i - 1] - 3 * s[i - 2] + s[i - 3],
291                    _ => 4 * s[i - 1] - 6 * s[i - 2] + 4 * s[i - 3] - s[i - 4],
292                };
293                s[i] += p;
294            }
295            s
296        }
297        32..=63 => {
298            let order = (kind - 31) as usize;
299            let mut s: Vec<i64> = (0..order)
300                .map(|_| r.signed(bps))
301                .collect::<Result<_, _>>()?;
302            let prec = r.bits(4)? as u32 + 1;
303            if prec == 16 {
304                return Err("invalid FLAC LPC precision".into());
305            }
306            let shift = r.signed(5)?;
307            if shift < 0 {
308                return Err("negative FLAC LPC shift".into());
309            }
310            let coefs: Vec<i64> = (0..order)
311                .map(|_| r.signed(prec))
312                .collect::<Result<_, _>>()?;
313            residual(r, block, order, &mut s)?;
314            for i in order..block {
315                let mut acc: i64 = 0;
316                for (j, &c) in coefs.iter().enumerate() {
317                    acc += c * s[i - 1 - j];
318                }
319                s[i] += acc >> shift;
320            }
321            s
322        }
323        _ => return Err(format!("reserved FLAC subframe type {kind}")),
324    };
325    if wasted > 0 {
326        for v in &mut s {
327            *v <<= wasted;
328        }
329    }
330    Ok(s)
331}
332
333/// Rice-coded residual; appends `block - order` values to `s`.
334fn residual(r: &mut Bits, block: usize, order: usize, s: &mut Vec<i64>) -> Result<(), String> {
335    let method = r.bits(2)?;
336    let param_bits = match method {
337        0 => 4,
338        1 => 5,
339        _ => return Err("reserved FLAC residual coding".into()),
340    };
341    let escape = (1u64 << param_bits) - 1;
342    let part_order = r.bits(4)? as u32;
343    let parts = 1usize << part_order;
344    if block % parts != 0 || block / parts < order && part_order > 0 {
345        return Err("bad FLAC partition order".into());
346    }
347    for p in 0..parts {
348        let n = if p == 0 {
349            block / parts - order
350        } else {
351            block / parts
352        };
353        let k = r.bits(param_bits)?;
354        if k == escape {
355            let nb = r.bits(5)? as u32;
356            for _ in 0..n {
357                s.push(r.signed(nb)?);
358            }
359        } else {
360            let k = k as u32;
361            for _ in 0..n {
362                let q = r.unary()? as u64;
363                let v = (q << k) | r.bits(k)?;
364                s.push(((v >> 1) as i64) ^ -((v & 1) as i64));
365            }
366        }
367    }
368    Ok(())
369}
370
371/// Decode a native FLAC file (`fLaC` + metadata + frames). ID3v2 tags in
372/// front of the stream are skipped.
373pub fn decode(data: &[u8]) -> Result<Flac, String> {
374    let mut off = 0;
375    if data.starts_with(b"ID3") && data.len() > 10 {
376        let sz = data[6..10]
377            .iter()
378            .fold(0usize, |a, &b| (a << 7) | (b & 0x7f) as usize);
379        off = 10 + sz;
380    }
381    if data.get(off..off + 4) != Some(b"fLaC".as_slice()) {
382        return Err("not a FLAC file".into());
383    }
384    off += 4;
385    let mut info = None;
386    loop {
387        let h = *data.get(off).ok_or("truncated FLAC metadata")?;
388        let len = u32::from_be_bytes([0, data[off + 1], data[off + 2], data[off + 3]]) as usize;
389        let body = data
390            .get(off + 4..off + 4 + len)
391            .ok_or("truncated FLAC metadata")?;
392        if h & 0x7f == 0 {
393            info = Some(parse_streaminfo(body)?);
394        }
395        off += 4 + len;
396        if h & 0x80 != 0 {
397            break;
398        }
399    }
400    let info = info.ok_or("FLAC without STREAMINFO")?;
401    let mut channels = vec![Vec::new(); info.channels as usize];
402    decode_frames(&data[off..], &info, &mut channels)?;
403    Ok(Flac { info, channels })
404}
405
406/// Decode consecutive frames from `d` into `channels`.
407pub fn decode_frames(d: &[u8], info: &StreamInfo, channels: &mut [Vec<i32>]) -> Result<(), String> {
408    let mut off = 0;
409    while off + 2 <= d.len() {
410        let (frame, len) = decode_frame(&d[off..], info)?;
411        if frame.len() != channels.len() {
412            return Err("FLAC frame channel count changed".into());
413        }
414        for (c, f) in channels.iter_mut().zip(frame) {
415            c.extend(f);
416        }
417        off += len;
418    }
419    if info.total_samples > 0 {
420        for c in channels.iter_mut() {
421            c.truncate(info.total_samples as usize);
422        }
423    }
424    Ok(())
425}