Skip to main content

rff_format/
flac.rs

1//! FLAC helpers shared by containers (MP4 `dfLa`, Matroska `A_FLAC`
2//! CodecPrivate): the frame header's block size and a STREAMINFO rewritten
3//! from the frames a muxer actually wrote (total samples, frame and block
4//! size bounds), as FFmpeg's FLAC-carrying muxers do at the trailer.
5
6/// The block size (samples per channel) a FLAC frame header declares, or
7/// `None` when `frame` does not start with a frame header.
8pub fn frame_block_size(frame: &[u8]) -> Option<u32> {
9    if frame.len() < 5 || frame[0] != 0xFF || frame[1] & 0xFE != 0xF8 {
10        return None;
11    }
12    let code = frame[2] >> 4;
13    // The UTF-8-style coded frame/sample number: its length from the
14    // leading ones of the first byte.
15    let lead = frame[4].leading_ones() as usize;
16    let num_len = match lead {
17        0 => 1,
18        2..=7 => lead,
19        _ => return None,
20    };
21    let at = 4 + num_len;
22    match code {
23        1 => Some(192),
24        2..=5 => Some(576 << (code - 2)),
25        6 => frame.get(at).map(|&b| u32::from(b) + 1),
26        7 => frame
27            .get(at..at + 2)
28            .map(|b| u32::from(u16::from_be_bytes([b[0], b[1]])) + 1),
29        8..=15 => Some(256 << (code - 8)),
30        _ => None,
31    }
32}
33
34/// What a muxer learns from the FLAC frames it writes.
35#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub struct FlacStats {
37    pub frames: u64,
38    pub total_samples: u64,
39    pub min_frame: u32,
40    pub max_frame: u32,
41    /// Smallest block size of every frame but the last (which may be short).
42    pub min_block: u32,
43    pub max_block: u32,
44    last_block: u32,
45    /// A frame whose header did not parse: the totals are unknown.
46    pub unparsed: bool,
47}
48
49impl FlacStats {
50    /// Account for one FLAC frame (one packet).
51    pub fn push(&mut self, frame: &[u8]) {
52        let size = u32::try_from(frame.len()).unwrap_or(u32::MAX);
53        let Some(block) = frame_block_size(frame) else {
54            self.unparsed = true;
55            return;
56        };
57        if self.frames > 0 {
58            // The previous frame was not the last after all.
59            self.min_block = match self.min_block {
60                0 => self.last_block,
61                m => m.min(self.last_block),
62            };
63        }
64        self.frames += 1;
65        self.total_samples += u64::from(block);
66        self.max_block = self.max_block.max(block);
67        self.last_block = block;
68        self.min_frame = if self.frames == 1 {
69            size
70        } else {
71            self.min_frame.min(size)
72        };
73        self.max_frame = self.max_frame.max(size);
74    }
75
76    /// `streaminfo` (the 34-byte body) with the block and frame size bounds
77    /// and the total sample count from the frames written. The MD5 is kept
78    /// only when the original declared the same total (the same audio);
79    /// otherwise it is zeroed, which means "unknown". Rate, channels and bit
80    /// depth are left alone. Unchanged when no frame was written or a frame
81    /// header did not parse.
82    pub fn rewrite(&self, streaminfo: &[u8; 34]) -> [u8; 34] {
83        let mut si = *streaminfo;
84        if self.frames == 0 || self.unparsed {
85            return si;
86        }
87        let min_block = if self.frames == 1 {
88            self.last_block
89        } else {
90            self.min_block
91        };
92        let old_total =
93            u64::from_be_bytes([0, 0, 0, si[13] & 0x0F, si[14], si[15], si[16], si[17]]);
94        si[0..2].copy_from_slice(&(min_block.min(0xFFFF) as u16).to_be_bytes());
95        si[2..4].copy_from_slice(&(self.max_block.min(0xFFFF) as u16).to_be_bytes());
96        si[4..7].copy_from_slice(&self.min_frame.min(0xFF_FFFF).to_be_bytes()[1..]);
97        si[7..10].copy_from_slice(&self.max_frame.min(0xFF_FFFF).to_be_bytes()[1..]);
98        let total = self.total_samples.min((1 << 36) - 1);
99        si[13] = (si[13] & 0xF0) | (total >> 32) as u8;
100        si[14..18].copy_from_slice(&(total as u32).to_be_bytes());
101        if old_total != total {
102            si[18..34].fill(0);
103        }
104        si
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    /// A frame header: block size code, coded number bytes, optional size.
113    fn frame(code: u8, number: &[u8], extra: &[u8], len: usize) -> Vec<u8> {
114        let mut f = vec![0xFF, 0xF8, code << 4 | 9, 0x08];
115        f.extend_from_slice(number);
116        f.extend_from_slice(extra);
117        f.resize(len, 0);
118        f
119    }
120
121    #[test]
122    fn block_sizes_from_every_code() {
123        assert_eq!(frame_block_size(&frame(12, &[0], &[], 16)), Some(4096));
124        assert_eq!(frame_block_size(&frame(1, &[5], &[], 16)), Some(192));
125        assert_eq!(frame_block_size(&frame(3, &[5], &[], 16)), Some(1152));
126        assert_eq!(
127            frame_block_size(&frame(6, &[0xC2, 0x80], &[99], 16)),
128            Some(100)
129        );
130        assert_eq!(
131            frame_block_size(&frame(7, &[1], &[0x01, 0x00], 16)),
132            Some(257)
133        );
134        assert_eq!(frame_block_size(b"not flac"), None);
135    }
136
137    #[test]
138    fn streaminfo_is_rewritten_from_the_frames() {
139        let mut st = FlacStats::default();
140        for (i, len) in [(0u8, 900usize), (1, 1200), (2, 700)] {
141            st.push(&frame(12, &[i], &[], len));
142        }
143        st.push(&frame(7, &[3], &[0x03, 0xE7], 300)); // a short last block: 1000
144        let mut si = [0u8; 34];
145        si[10..14].copy_from_slice(&[0x0B, 0xB8, 0x03, 0x70]); // 48 kHz, 2 ch, 24 bit
146        si[18..].fill(0xAB);
147        let out = st.rewrite(&si);
148        assert_eq!(u16::from_be_bytes([out[0], out[1]]), 4096); // min: not the last
149        assert_eq!(u16::from_be_bytes([out[2], out[3]]), 4096);
150        assert_eq!(&out[4..7], &[0, 0x01, 0x2C]); // 300
151        assert_eq!(&out[7..10], &[0, 0x04, 0xB0]); // 1200
152        assert_eq!(&out[10..13], &si[10..13]);
153        assert_eq!(out[13] >> 4, si[13] >> 4);
154        assert_eq!(
155            u32::from_be_bytes([out[14], out[15], out[16], out[17]]),
156            3 * 4096 + 1000
157        );
158        assert_eq!(&out[18..], &[0u8; 16], "a different total: MD5 unknown");
159        // Same total: the MD5 stays.
160        let mut same = out;
161        same[18..].fill(0xCD);
162        assert_eq!(&st.rewrite(&same)[18..], &[0xCD; 16]);
163    }
164}