Skip to main content

moq_mux/codec/flac/
mod.rs

1//! FLAC.
2//!
3//! Parse and serialize the FLAC `STREAMINFO` metadata block (RFC 9639 §8.2),
4//! the codec's configuration record. [`Config::description`] builds the
5//! WebCodecs `description` (the `fLaC` stream marker followed by the STREAMINFO
6//! block) so a browser can initialize a decoder from the catalog alone.
7//! [`Import`] publishes raw FLAC frames to a moq broadcast.
8
9mod import;
10
11pub use import::*;
12
13use bytes::{Buf, BufMut, Bytes};
14
15/// The four-byte stream marker that opens a native FLAC bitstream and the
16/// WebCodecs `description`.
17const MARKER: [u8; 4] = *b"fLaC";
18
19/// Length of a STREAMINFO metadata block body in bytes (RFC 9639 §8.2).
20const STREAMINFO_LEN: usize = 34;
21
22/// FLAC parsing errors.
23#[derive(Debug, Clone, thiserror::Error)]
24#[non_exhaustive]
25pub enum Error {
26	/// The buffer ended before a full STREAMINFO (or its enclosing header) could be read.
27	#[error("buffer too short for FLAC STREAMINFO")]
28	Short,
29
30	/// A FLAC header did not begin with the `fLaC` stream marker.
31	#[error("invalid FLAC stream marker")]
32	InvalidMarker,
33
34	/// The first metadata block was not STREAMINFO, which RFC 9639 §8.1 requires.
35	#[error("first metadata block is not STREAMINFO")]
36	MissingStreamInfo,
37}
38
39/// A result using this module's error type.
40pub type Result<T> = std::result::Result<T, Error>;
41
42/// Typed FLAC configuration mirroring the fields of a STREAMINFO metadata block
43/// (RFC 9639 §8.2).
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Config {
46	/// Minimum block size in samples.
47	pub min_block_size: u16,
48	/// Maximum block size in samples.
49	pub max_block_size: u16,
50	/// Minimum frame size in bytes (0 = unknown).
51	pub min_frame_size: u32,
52	/// Maximum frame size in bytes (0 = unknown).
53	pub max_frame_size: u32,
54	/// Sample rate in Hz (20-bit field, so 1..=1_048_575).
55	pub sample_rate: u32,
56	/// Channel count (1..=8).
57	pub channel_count: u32,
58	/// Bits per sample (4..=32).
59	pub bits_per_sample: u32,
60	/// Total interchannel samples (36-bit field, 0 = unknown).
61	pub total_samples: u64,
62	/// MD5 of the unencoded audio (all-zero = unknown).
63	pub md5: [u8; 16],
64}
65
66impl Config {
67	/// Parse a 34-byte STREAMINFO body (RFC 9639 §8.2), without the `fLaC`
68	/// marker or metadata block header.
69	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		// Sample rate (20), channels-1 (3), bits-1 (5), and total samples (36) are
80		// packed into a single 64-bit field.
81		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	/// Parse a FLAC header: the `fLaC` stream marker followed by the STREAMINFO
104	/// metadata block. This is the Matroska `A_FLAC` CodecPrivate / WebCodecs
105	/// `description` layout. Trailing metadata blocks (Vorbis comments, etc.) are
106	/// ignored.
107	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		// Metadata block header: 1-bit last flag, 7-bit block type, 24-bit length.
121		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	/// Serialize the 34-byte STREAMINFO body.
131	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	/// Build the WebCodecs `description`: the `fLaC` stream marker, a metadata
149	/// block header flagged as the final block, and the STREAMINFO body. This is
150	/// the `description` a FLAC `AudioDecoder` expects per the WebCodecs FLAC
151	/// registration.
152	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		// Last-metadata-block flag (0x80) set, block type 0 (STREAMINFO).
157		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
164/// How many samples the FLAC frame at the start of `frame` codes, from its header (RFC 9639
165/// §9.1.1). `None` when the header doesn't parse.
166pub(crate) fn block_samples(frame: &[u8]) -> Option<u32> {
167	// The 14-bit sync code, a reserved zero bit, and the blocking strategy.
168	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		// The size minus one follows the UTF-8-style coded frame or sample number.
177		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		// Fixed blocking: 4096 samples (code 12), 1152 (code 3), and 192 (code 1).
201		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		// An 8-bit size after a one-byte frame number, and a 16-bit one after a two-byte number.
205		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		// No sync, a reserved size, and a header cut short.
211		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		// "fLaC" + 4-byte block header + 34-byte STREAMINFO.
244		assert_eq!(desc.len(), 4 + 4 + STREAMINFO_LEN);
245		assert_eq!(&desc[..4], b"fLaC");
246		// Final block flag set, block type 0 (STREAMINFO).
247		assert_eq!(desc[4], 0x80);
248
249		// The description parses back into the same config.
250		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		// Flip the block type away from 0 (STREAMINFO) while keeping the marker.
265		desc[4] = 0x80 | 0x04; // last block, type 4 (Vorbis comment)
266		assert!(matches!(
267			Config::parse(&mut desc.as_slice()),
268			Err(Error::MissingStreamInfo)
269		));
270	}
271}