1mod import;
10
11pub use import::*;
12
13use bytes::{Buf, BufMut, Bytes};
14
15const MARKER: [u8; 4] = *b"fLaC";
18
19const STREAMINFO_LEN: usize = 34;
21
22#[derive(Debug, Clone, thiserror::Error)]
24#[non_exhaustive]
25pub enum Error {
26 #[error("buffer too short for FLAC STREAMINFO")]
28 Short,
29
30 #[error("invalid FLAC stream marker")]
32 InvalidMarker,
33
34 #[error("first metadata block is not STREAMINFO")]
36 MissingStreamInfo,
37}
38
39pub type Result<T> = std::result::Result<T, Error>;
41
42#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Config {
46 pub min_block_size: u16,
48 pub max_block_size: u16,
50 pub min_frame_size: u32,
52 pub max_frame_size: u32,
54 pub sample_rate: u32,
56 pub channel_count: u32,
58 pub bits_per_sample: u32,
60 pub total_samples: u64,
62 pub md5: [u8; 16],
64}
65
66impl Config {
67 pub fn parse_stream_info<T: Buf>(buf: &mut T) -> Result<Self> {
70 if buf.remaining() < STREAMINFO_LEN {
71 return Err(Error::Short);
72 }
73
74 let min_block_size = buf.get_u16();
75 let max_block_size = buf.get_u16();
76 let min_frame_size = buf.get_uint(3) as u32;
77 let max_frame_size = buf.get_uint(3) as u32;
78
79 let packed = buf.get_u64();
82 let sample_rate = (packed >> 44) as u32;
83 let channel_count = (((packed >> 41) & 0x7) as u32) + 1;
84 let bits_per_sample = (((packed >> 36) & 0x1f) as u32) + 1;
85 let total_samples = packed & 0xF_FFFF_FFFF;
86
87 let mut md5 = [0u8; 16];
88 buf.copy_to_slice(&mut md5);
89
90 Ok(Self {
91 min_block_size,
92 max_block_size,
93 min_frame_size,
94 max_frame_size,
95 sample_rate,
96 channel_count,
97 bits_per_sample,
98 total_samples,
99 md5,
100 })
101 }
102
103 pub fn parse<T: Buf>(buf: &mut T) -> Result<Self> {
108 if buf.remaining() < 4 {
109 return Err(Error::Short);
110 }
111 let mut marker = [0u8; 4];
112 buf.copy_to_slice(&mut marker);
113 if marker != MARKER {
114 return Err(Error::InvalidMarker);
115 }
116
117 if buf.remaining() < 4 {
118 return Err(Error::Short);
119 }
120 let header = buf.get_u32();
122 let block_type = ((header >> 24) & 0x7f) as u8;
123 if block_type != 0 {
124 return Err(Error::MissingStreamInfo);
125 }
126
127 Self::parse_stream_info(buf)
128 }
129
130 pub fn encode_stream_info(&self) -> Bytes {
132 let mut buf = Vec::with_capacity(STREAMINFO_LEN);
133 buf.put_u16(self.min_block_size);
134 buf.put_u16(self.max_block_size);
135 buf.put_uint(self.min_frame_size as u64, 3);
136 buf.put_uint(self.max_frame_size as u64, 3);
137
138 let packed = ((self.sample_rate as u64 & 0xF_FFFF) << 44)
139 | ((self.channel_count.saturating_sub(1) as u64 & 0x7) << 41)
140 | ((self.bits_per_sample.saturating_sub(1) as u64 & 0x1f) << 36)
141 | (self.total_samples & 0xF_FFFF_FFFF);
142 buf.put_u64(packed);
143 buf.put_slice(&self.md5);
144
145 buf.into()
146 }
147
148 pub fn description(&self) -> Bytes {
153 let stream_info = self.encode_stream_info();
154 let mut buf = Vec::with_capacity(MARKER.len() + 4 + stream_info.len());
155 buf.put_slice(&MARKER);
156 buf.put_u8(0x80);
158 buf.put_uint(stream_info.len() as u64, 3);
159 buf.put_slice(&stream_info);
160 buf.into()
161 }
162}
163
164pub(crate) fn block_samples(frame: &[u8]) -> Option<u32> {
167 if frame.len() < 5 || frame[0] != 0xFF || frame[1] & 0xFE != 0xF8 {
169 return None;
170 }
171 let code = frame[2] >> 4;
172 match code {
173 1 => Some(192),
174 2..=5 => Some(576 << (code - 2)),
175 8..=15 => Some(256 << (code - 8)),
176 6 | 7 => {
178 let coded = match frame[4].leading_ones() {
179 0 => 1,
180 length @ 2..=7 => length as usize,
181 _ => return None,
182 };
183 let at = 4 + coded;
184 let size = match code {
185 6 => u32::from(*frame.get(at)?),
186 _ => u32::from(u16::from_be_bytes([*frame.get(at)?, *frame.get(at + 1)?])),
187 };
188 Some(size + 1)
189 }
190 _ => None,
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 #[test]
199 fn block_samples_reads_the_frame_header() {
200 assert_eq!(block_samples(&[0xFF, 0xF8, 0xC9, 0x18, 0x00]), Some(4096));
202 assert_eq!(block_samples(&[0xFF, 0xF8, 0x39, 0x18, 0x00]), Some(1152));
203 assert_eq!(block_samples(&[0xFF, 0xF8, 0x19, 0x18, 0x00]), Some(192));
204 assert_eq!(block_samples(&[0xFF, 0xF8, 0x69, 0x18, 0x05, 0xFF]), Some(256));
206 assert_eq!(
207 block_samples(&[0xFF, 0xF9, 0x79, 0x18, 0xC2, 0x80, 0x03, 0xE7]),
208 Some(1000)
209 );
210 assert_eq!(block_samples(&[0x00, 0xF8, 0xC9, 0x18, 0x00]), None);
212 assert_eq!(block_samples(&[0xFF, 0xF8, 0x09, 0x18, 0x00]), None);
213 assert_eq!(block_samples(&[0xFF, 0xF8, 0x79, 0x18, 0x00, 0x03]), None);
214 }
215
216 fn sample() -> Config {
217 Config {
218 min_block_size: 4608,
219 max_block_size: 4608,
220 min_frame_size: 16,
221 max_frame_size: 9102,
222 sample_rate: 44_100,
223 channel_count: 2,
224 bits_per_sample: 24,
225 total_samples: 120_832,
226 md5: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
227 }
228 }
229
230 #[test]
231 fn stream_info_roundtrip() {
232 let cfg = sample();
233 let encoded = cfg.encode_stream_info();
234 assert_eq!(encoded.len(), STREAMINFO_LEN);
235 let parsed = Config::parse_stream_info(&mut encoded.as_ref()).unwrap();
236 assert_eq!(parsed, cfg);
237 }
238
239 #[test]
240 fn description_roundtrip() {
241 let cfg = sample();
242 let desc = cfg.description();
243 assert_eq!(desc.len(), 4 + 4 + STREAMINFO_LEN);
245 assert_eq!(&desc[..4], b"fLaC");
246 assert_eq!(desc[4], 0x80);
248
249 let parsed = Config::parse(&mut desc.as_ref()).unwrap();
251 assert_eq!(parsed, cfg);
252 }
253
254 #[test]
255 fn parse_rejects_bad_marker() {
256 let mut desc = sample().description().to_vec();
257 desc[0] = b'X';
258 assert!(matches!(Config::parse(&mut desc.as_slice()), Err(Error::InvalidMarker)));
259 }
260
261 #[test]
262 fn parse_rejects_non_streaminfo_first_block() {
263 let mut desc = sample().description().to_vec();
264 desc[4] = 0x80 | 0x04; assert!(matches!(
267 Config::parse(&mut desc.as_slice()),
268 Err(Error::MissingStreamInfo)
269 ));
270 }
271}