diff --git a/crates/ec-flac/Cargo.toml b/crates/ec-flac/Cargo.toml new file mode 100644 index 00000000..6486649d --- /dev/null +++ b/crates/ec-flac/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-flac" +description = "FLAC decoder and encoder (RFC 9639), built on the edith_codecs IR." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core = { workspace = true } diff --git a/crates/ec-flac/src/checksum.rs b/crates/ec-flac/src/checksum.rs new file mode 100644 index 00000000..29592c5d --- /dev/null +++ b/crates/ec-flac/src/checksum.rs @@ -0,0 +1,263 @@ +//! The three integrity primitives FLAC streams carry: CRC-8 over a frame +//! header, CRC-16 over a whole frame, and the MD5 of the *unencoded* audio in +//! `STREAMINFO`. +//! +//! MD5 is here rather than pulled in as a dependency because the family ships +//! no third-party crates, and because FLAC needs exactly one thing from it: the +//! digest of interleaved little-endian samples. + +/// CRC-8, polynomial `x^8 + x^2 + x + 1` (0x07), initial value 0 — the frame +/// header check. +pub fn crc8(data: &[u8]) -> u8 { + let mut crc = 0u8; + for &b in data { + crc = CRC8[(crc ^ b) as usize]; + } + crc +} + +/// CRC-16, polynomial `x^16 + x^15 + x^2 + 1` (0x8005), initial value 0 — the +/// frame footer check, computed over the frame including its header. +pub fn crc16(data: &[u8]) -> u16 { + let mut crc = 0u16; + for &b in data { + crc = (crc << 8) ^ CRC16[(((crc >> 8) as u8) ^ b) as usize]; + } + crc +} + +const CRC8: [u8; 256] = { + let mut t = [0u8; 256]; + let mut i = 0; + while i < 256 { + let mut c = i as u8; + let mut b = 0; + while b < 8 { + c = if c & 0x80 != 0 { + (c << 1) ^ 0x07 + } else { + c << 1 + }; + b += 1; + } + t[i] = c; + i += 1; + } + t +}; + +const CRC16: [u16; 256] = { + let mut t = [0u16; 256]; + let mut i = 0; + while i < 256 { + let mut c = (i as u16) << 8; + let mut b = 0; + while b < 8 { + c = if c & 0x8000 != 0 { + (c << 1) ^ 0x8005 + } else { + c << 1 + }; + b += 1; + } + t[i] = c; + i += 1; + } + t +}; + +/// MD5 (RFC 1321), streaming. +#[derive(Debug, Clone)] +pub struct Md5 { + state: [u32; 4], + len: u64, + buf: [u8; 64], + used: usize, +} + +impl Default for Md5 { + fn default() -> Self { + Md5::new() + } +} + +impl Md5 { + /// A fresh digest. + pub fn new() -> Md5 { + Md5 { + state: [0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476], + len: 0, + buf: [0; 64], + used: 0, + } + } + + /// Feed bytes. + pub fn update(&mut self, mut data: &[u8]) { + self.len = self.len.wrapping_add(data.len() as u64); + if self.used > 0 { + let take = (64 - self.used).min(data.len()); + self.buf[self.used..self.used + take].copy_from_slice(&data[..take]); + self.used += take; + data = &data[take..]; + if self.used == 64 { + let block = self.buf; + self.compress(&block); + self.used = 0; + } + // The tail below overwrites `used`, so a call that only topped up + // the buffer has to stop here — otherwise the buffered bytes are + // silently forgotten. + if data.is_empty() { + return; + } + } + let mut chunks = data.chunks_exact(64); + for chunk in &mut chunks { + let mut block = [0u8; 64]; + block.copy_from_slice(chunk); + self.compress(&block); + } + let rest = chunks.remainder(); + self.buf[..rest.len()].copy_from_slice(rest); + self.used = rest.len(); + } + + /// Finish and return the 16-byte digest. + pub fn finish(mut self) -> [u8; 16] { + let bits = self.len.wrapping_mul(8); + self.update(&[0x80]); + while self.used != 56 { + self.update(&[0]); + } + self.update(&bits.to_le_bytes()); + debug_assert_eq!(self.used, 0); + let mut out = [0u8; 16]; + for (i, word) in self.state.iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&word.to_le_bytes()); + } + out + } + + fn compress(&mut self, block: &[u8; 64]) { + let mut m = [0u32; 16]; + for (i, word) in m.iter_mut().enumerate() { + *word = u32::from_le_bytes([ + block[i * 4], + block[i * 4 + 1], + block[i * 4 + 2], + block[i * 4 + 3], + ]); + } + let [mut a, mut b, mut c, mut d] = self.state; + for i in 0..64 { + let (f, g) = match i / 16 { + 0 => ((b & c) | (!b & d), i), + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), + 2 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | !d), (7 * i) % 16), + }; + let tmp = d; + d = c; + c = b; + let sum = a.wrapping_add(f).wrapping_add(MD5_K[i]).wrapping_add(m[g]); + b = b.wrapping_add(sum.rotate_left(MD5_S[i])); + a = tmp; + } + self.state[0] = self.state[0].wrapping_add(a); + self.state[1] = self.state[1].wrapping_add(b); + self.state[2] = self.state[2].wrapping_add(c); + self.state[3] = self.state[3].wrapping_add(d); + } +} + +/// MD5 of interleaved samples the way `STREAMINFO` defines it: each sample as +/// `bits_per_sample / 8` little-endian bytes, signed, in channel order. +pub fn md5_of_samples(samples: &[i32], bits_per_sample: u32) -> [u8; 16] { + let bytes = bits_per_sample.div_ceil(8) as usize; + let mut md5 = Md5::new(); + // One buffered pass: a per-sample `update` call costs more than the hash. + let mut buf = Vec::with_capacity(4096 * bytes); + for &s in samples { + buf.extend_from_slice(&s.to_le_bytes()[..bytes]); + if buf.len() >= 4096 * bytes { + md5.update(&buf); + buf.clear(); + } + } + md5.update(&buf); + md5.finish() +} + +const MD5_S: [u32; 64] = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, + 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, + 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, +]; + +#[rustfmt::skip] +const MD5_K: [u32; 64] = { + // K[i] = floor(2^32 * abs(sin(i + 1))), spelled out because `sin` is not + // available in a const context. + [ + 0xd76a_a478, 0xe8c7_b756, 0x2420_70db, 0xc1bd_ceee, 0xf57c_0faf, 0x4787_c62a, 0xa830_4613, + 0xfd46_9501, 0x6980_98d8, 0x8b44_f7af, 0xffff_5bb1, 0x895c_d7be, 0x6b90_1122, 0xfd98_7193, + 0xa679_438e, 0x49b4_0821, 0xf61e_2562, 0xc040_b340, 0x265e_5a51, 0xe9b6_c7aa, 0xd62f_105d, + 0x0244_1453, 0xd8a1_e681, 0xe7d3_fbc8, 0x21e1_cde6, 0xc337_07d6, 0xf4d5_0d87, 0x455a_14ed, + 0xa9e3_e905, 0xfcef_a3f8, 0x676f_02d9, 0x8d2a_4c8a, 0xfffa_3942, 0x8771_f681, 0x6d9d_6122, + 0xfde5_380c, 0xa4be_ea44, 0x4bde_cfa9, 0xf6bb_4b60, 0xbebf_bc70, 0x289b_7ec6, 0xeaa1_27fa, + 0xd4ef_3085, 0x0488_1d05, 0xd9d4_d039, 0xe6db_99e5, 0x1fa2_7cf8, 0xc4ac_5665, 0xf429_2244, + 0x432a_ff97, 0xab94_23a7, 0xfc93_a039, 0x655b_59c3, 0x8f0c_cc92, 0xffef_f47d, 0x8584_5dd1, + 0x6fa8_7e4f, 0xfe2c_e6e0, 0xa301_4314, 0x4e08_11a1, 0xf753_7e82, 0xbd3a_f235, 0x2ad7_d2bb, + 0xeb86_d391, + ] +}; + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(d: [u8; 16]) -> String { + d.iter().map(|b| format!("{b:02x}")).collect() + } + + #[test] + fn md5_matches_rfc1321_vectors() { + let cases: [(&str, &str); 5] = [ + ("", "d41d8cd98f00b204e9800998ecf8427e"), + ("a", "0cc175b9c0f1b6a831c399e269772661"), + ("abc", "900150983cd24fb0d6963f7d28e17f72"), + ("message digest", "f96b697d7cb7938d525a2f31aaf161d0"), + ( + "12345678901234567890123456789012345678901234567890123456789012345678901234567890", + "57edf4a22be3c955ac49da2e2107b67a", + ), + ]; + for (input, want) in cases { + let mut md5 = Md5::new(); + md5.update(input.as_bytes()); + assert_eq!(hex(md5.finish()), want, "md5({input:?})"); + } + } + + #[test] + fn md5_is_split_invariant() { + let data: Vec = (0..1000u32).map(|i| (i * 7) as u8).collect(); + let mut whole = Md5::new(); + whole.update(&data); + let mut split = Md5::new(); + for chunk in data.chunks(37) { + split.update(chunk); + } + assert_eq!(whole.finish(), split.finish()); + } + + #[test] + fn crcs_match_known_values() { + // CRC-8/SMBUS and CRC-16/UMTS check values, i.e. of "123456789". + assert_eq!(crc8(b"123456789"), 0xf4); + assert_eq!(crc16(b"123456789"), 0xfee8); + assert_eq!(crc8(&[]), 0); + assert_eq!(crc16(&[]), 0); + } +} diff --git a/crates/ec-flac/src/decode.rs b/crates/ec-flac/src/decode.rs new file mode 100644 index 00000000..9375611e --- /dev/null +++ b/crates/ec-flac/src/decode.rs @@ -0,0 +1,968 @@ +//! FLAC decoding: metadata blocks, frame headers, all four subframe kinds and +//! the three stereo decorrelations, per RFC 9639. +//! +//! Every parse routine takes a borrowed buffer and answers with +//! [`ec_core::Error`]: truncated input is `NeedMore`, a stream that breaks its +//! own rules is `Corrupt`. Nothing here panics on input — the only asserts are +//! in `ec_core::bitio`, and they fire on API misuse (`n > 64`), never on bytes. + +use ec_core::bitio::BitReader; +use ec_core::error::{Error, Result}; + +use crate::checksum::{crc8, crc16}; + +/// The four bytes every FLAC stream starts with. +pub const MAGIC: [u8; 4] = *b"fLaC"; + +/// Largest block size RFC 9639 can express (16-bit `block_size - 1`). +pub const MAX_BLOCK_SIZE: usize = 65536; + +/// The `STREAMINFO` metadata block: everything a player needs before the first +/// frame. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StreamInfo { + /// Smallest block size in the stream, in inter-channel samples. + pub min_block_size: u16, + /// Largest block size in the stream. Equal to `min_block_size` for a + /// fixed-block-size stream. + pub max_block_size: u16, + /// Smallest frame size in bytes; 0 when the encoder did not state it. + pub min_frame_size: u32, + /// Largest frame size in bytes; 0 when the encoder did not state it. + pub max_frame_size: u32, + /// Sample rate in Hz. 0 means "non-audio stream" and is refused here. + pub sample_rate: u32, + /// Channel count, 1..=8. + pub channels: u8, + /// Bits per sample, 4..=32. + pub bits_per_sample: u8, + /// Total inter-channel samples, or 0 when unknown. + pub total_samples: u64, + /// MD5 of the unencoded audio; all zero when the encoder did not compute it. + pub md5: [u8; 16], +} + +impl StreamInfo { + /// Parse the 34-byte `STREAMINFO` payload. + pub fn parse(data: &[u8]) -> Result { + if data.len() < 34 { + return Err(Error::NeedMore); + } + let mut r = BitReader::new(data); + let info = StreamInfo { + min_block_size: r.read_bits(16)? as u16, + max_block_size: r.read_bits(16)? as u16, + min_frame_size: r.read_bits(24)?, + max_frame_size: r.read_bits(24)?, + sample_rate: r.read_bits(20)?, + channels: (r.read_bits(3)? + 1) as u8, + bits_per_sample: (r.read_bits(5)? + 1) as u8, + total_samples: r.read_bits64(36)?, + md5: data[18..34].try_into().expect("18..34 is 16 bytes"), + }; + if info.sample_rate == 0 { + return Err(Error::corrupt("STREAMINFO: sample rate 0")); + } + if info.bits_per_sample < 4 { + return Err(Error::corrupt(format!( + "STREAMINFO: {} bits per sample", + info.bits_per_sample + ))); + } + if info.min_block_size < 16 || info.max_block_size < 16 { + return Err(Error::corrupt(format!( + "STREAMINFO: block sizes {}..{}", + info.min_block_size, info.max_block_size + ))); + } + Ok(info) + } + + /// The 34-byte `STREAMINFO` payload. + pub fn to_bytes(&self) -> [u8; 34] { + let mut out = [0u8; 34]; + out[0..2].copy_from_slice(&self.min_block_size.to_be_bytes()); + out[2..4].copy_from_slice(&self.max_block_size.to_be_bytes()); + out[4..7].copy_from_slice(&self.min_frame_size.to_be_bytes()[1..]); + out[7..10].copy_from_slice(&self.max_frame_size.to_be_bytes()[1..]); + let packed = (u64::from(self.sample_rate) << 44) + | (u64::from(self.channels - 1) << 41) + | (u64::from(self.bits_per_sample - 1) << 36) + | (self.total_samples & 0xf_ffff_ffff); + out[10..18].copy_from_slice(&packed.to_be_bytes()); + out[18..34].copy_from_slice(&self.md5); + out + } +} + +/// One entry of the `SEEKTABLE` block. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SeekPoint { + /// First sample of the target frame. + pub sample: u64, + /// Byte offset of that frame from the first byte of the first frame. + pub offset: u64, + /// Samples in the target frame. + pub frame_samples: u16, +} + +/// How the channels of one frame were decorrelated. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChannelAssignment { + /// `n` channels, each coded on its own. + Independent(u8), + /// Channel 0 is left, channel 1 is `left - right`. + LeftSide, + /// Channel 0 is `left - right`, channel 1 is right. + RightSide, + /// Channel 0 is `(left + right) >> 1`, channel 1 is `left - right`. + MidSide, +} + +impl ChannelAssignment { + /// Channels coded in the frame. + pub fn channel_count(&self) -> usize { + match self { + ChannelAssignment::Independent(n) => *n as usize, + _ => 2, + } + } +} + +/// A parsed frame header, with the `STREAMINFO` fallbacks already resolved. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FrameHeader { + /// Inter-channel samples in this frame. + pub block_size: usize, + /// Sample rate in Hz. + pub sample_rate: u32, + /// Channel coding of this frame. + pub channels: ChannelAssignment, + /// Bits per sample of the *decoded* audio. + pub bits_per_sample: u32, + /// Frame number for a fixed-block-size stream, first sample number for a + /// variable-block-size one. + pub number: u64, + /// True when the stream declares variable block sizes. + pub variable_block_size: bool, +} + +impl FrameHeader { + /// First inter-channel sample of this frame, when it can be known: a + /// variable-block-size stream states it, a fixed one implies it from the + /// frame number and the block size the stream was written with. + pub fn first_sample(&self, stream_block_size: Option) -> Option { + match self.variable_block_size { + true => Some(self.number), + false => stream_block_size.map(|bs| self.number * bs as u64), + } + } +} + +/// A decoded block: one `Vec` per channel, samples at the frame's own +/// bit depth (not shifted). +#[derive(Debug, Clone, Default)] +pub struct Block { + /// The header the samples came from. + pub header: Option, + /// Per-channel samples, already un-decorrelated. + pub channels: Vec>, +} + +impl Block { + /// Samples per channel. + pub fn len(&self) -> usize { + self.channels.first().map_or(0, Vec::len) + } + + /// True when no samples are held. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// The block interleaved into one buffer, samples shifted left so they fill + /// a 16- or 32-bit container the way ffmpeg and every mixer expect + /// (`s16` for depths up to 16, `s32` above). + pub fn to_interleaved(&self, shift: u32) -> Vec { + let channels = self.channels.len(); + let len = self.len(); + let mut out = vec![0i32; len * channels]; + for (c, plane) in self.channels.iter().enumerate() { + for (i, &s) in plane.iter().enumerate() { + out[i * channels + c] = s << shift; + } + } + out + } +} + +/// Bits the samples of a `bits_per_sample` stream are shifted left by to fill +/// their PCM container — the convention ffmpeg's decoder uses, so raw output +/// compares byte for byte. +pub fn container_shift(bits_per_sample: u32) -> u32 { + match bits_per_sample <= 16 { + true => 16 - bits_per_sample, + false => 32 - bits_per_sample, + } +} + +/// A FLAC stream over a complete in-memory buffer. +/// +/// Metadata is parsed on construction; frames are decoded one call at a time so +/// a caller can stop, seek and resume without decoding what it will discard. +#[derive(Debug)] +pub struct FlacReader<'a> { + data: &'a [u8], + stream_info: Option, + seek_table: Vec, + first_frame: usize, + pos: usize, + residual: Vec, +} + +impl<'a> FlacReader<'a> { + /// Open a stream: read the magic and metadata blocks, then stop at the + /// first frame. + /// + /// A buffer that does not start with `fLaC` is scanned for a frame sync + /// instead — some tools hand out FLAC that starts mid-stream, and the frame + /// headers carry enough to decode without `STREAMINFO`. + pub fn new(data: &'a [u8]) -> Result> { + let mut reader = FlacReader { + data, + stream_info: None, + seek_table: Vec::new(), + first_frame: 0, + pos: 0, + residual: Vec::new(), + }; + if data.len() >= 4 && data[..4] == MAGIC { + reader.read_metadata(4)?; + } else { + reader.first_frame = find_frame_sync(data, 0, None) + .ok_or_else(|| Error::corrupt("no fLaC magic and no frame sync"))?; + reader.pos = reader.first_frame; + } + Ok(reader) + } + + /// A reader over bare frames — what a container hands out, one packet at a + /// time, with the `STREAMINFO` it carried in its own headers. + pub fn frames(data: &'a [u8], info: Option) -> Result> { + let first_frame = find_frame_sync(data, 0, info.as_ref()) + .ok_or_else(|| Error::corrupt("no FLAC frame sync in this packet"))?; + Ok(FlacReader { + data, + stream_info: info, + seek_table: Vec::new(), + first_frame, + pos: first_frame, + residual: Vec::new(), + }) + } + + fn read_metadata(&mut self, mut at: usize) -> Result<()> { + let mut first = true; + loop { + let header = self.data.get(at..at + 4).ok_or(Error::NeedMore)?; + let last = header[0] & 0x80 != 0; + let kind = header[0] & 0x7f; + let len = u32::from_be_bytes([0, header[1], header[2], header[3]]) as usize; + let body = self.data.get(at + 4..at + 4 + len).ok_or(Error::NeedMore)?; + if first && kind != 0 { + return Err(Error::corrupt(format!( + "first metadata block is type {kind}, not STREAMINFO" + ))); + } + match kind { + 0 => self.stream_info = Some(StreamInfo::parse(body)?), + 3 => { + self.seek_table = body + .chunks_exact(18) + .map(|p| SeekPoint { + sample: u64::from_be_bytes(p[0..8].try_into().expect("8 bytes")), + offset: u64::from_be_bytes(p[8..16].try_into().expect("8 bytes")), + frame_samples: u16::from_be_bytes( + p[16..18].try_into().expect("2 bytes"), + ), + }) + // A placeholder point (sample == u64::MAX) indexes nothing. + .filter(|p| p.sample != u64::MAX) + .collect(); + } + 127 => return Err(Error::corrupt("metadata block type 127 is invalid")), + _ => {} + } + first = false; + at += 4 + len; + if last { + break; + } + } + self.first_frame = at; + self.pos = at; + Ok(()) + } + + /// The `STREAMINFO` block, when the stream had one. + pub fn stream_info(&self) -> Option<&StreamInfo> { + self.stream_info.as_ref() + } + + /// The seek table, empty when the stream carries none. + pub fn seek_table(&self) -> &[SeekPoint] { + &self.seek_table + } + + /// Byte offset of the next frame to be decoded. + pub fn position(&self) -> usize { + self.pos + } + + /// Position the reader at the last indexed frame at or before `sample` and + /// answer that frame's first sample; the caller decodes forward and + /// discards the difference (`SeekMode::SyncBefore`). + /// + /// Without a seek table the answer is the start of the stream: FLAC frames + /// are not self-indexing, so a blind scan would cost the same as decoding. + pub fn seek_to_sample(&mut self, sample: u64) -> u64 { + let point = self + .seek_table + .iter() + .filter(|p| p.sample <= sample) + .max_by_key(|p| p.sample); + match point { + Some(p) if self.first_frame + p.offset as usize <= self.data.len() => { + self.pos = self.first_frame + p.offset as usize; + p.sample + } + _ => { + self.pos = self.first_frame; + 0 + } + } + } + + /// Decode the next frame into `block`, reusing its buffers. + /// + /// Answers `false` at the end of the stream. Trailing bytes that are not a + /// frame (an ID3v1 tag, padding a container left) end the stream rather + /// than failing it; a frame that starts well and then breaks is `Corrupt`. + pub fn next_block(&mut self, block: &mut Block) -> Result { + if self.pos >= self.data.len() { + return Ok(false); + } + let start = match find_frame_sync(self.data, self.pos, self.stream_info.as_ref()) { + Some(at) => at, + None => { + self.pos = self.data.len(); + return Ok(false); + } + }; + self.pos = start; + let mut r = BitReader::new(&self.data[start..]); + let header = parse_frame_header(&mut r, self.stream_info.as_ref())?; + let header_bytes = (r.bit_position() / 8) as usize; + let want = crc8(&self.data[start..start + header_bytes - 1]); + if want != self.data[start + header_bytes - 1] { + return Err(Error::corrupt(format!( + "frame at {start}: header CRC-8 {:#04x}, expected {want:#04x}", + self.data[start + header_bytes - 1] + ))); + } + + let coded = header.channels.channel_count(); + block.channels.resize_with(coded, Vec::new); + for (c, plane) in block.channels.iter_mut().enumerate() { + let side = matches!( + (header.channels, c), + (ChannelAssignment::LeftSide, 1) + | (ChannelAssignment::MidSide, 1) + | (ChannelAssignment::RightSide, 0) + ); + let bps = header.bits_per_sample + u32::from(side); + decode_subframe(&mut r, bps, header.block_size, plane, &mut self.residual)?; + } + r.align_to_byte(); + let frame_bytes = (r.bit_position() / 8) as usize; + let stated = r.read_bits(16)? as u16; + let want = crc16(&self.data[start..start + frame_bytes]); + if stated != want { + return Err(Error::corrupt(format!( + "frame at {start}: CRC-16 {stated:#06x}, expected {want:#06x}" + ))); + } + undecorrelate(header.channels, &mut block.channels)?; + block.header = Some(header); + self.pos = start + frame_bytes + 2; + Ok(true) + } + + /// Decode the whole stream into per-channel planes, verifying the + /// `STREAMINFO` MD5 when the stream states one. + /// + /// Convenience over [`FlacReader::next_block`]: it holds the whole decoded + /// stream in memory, which is what a fixture test and a waveform pass want + /// and what a player does not. + pub fn decode_all(&mut self) -> Result { + let mut block = Block::default(); + let mut out: Vec> = Vec::new(); + let mut header: Option = None; + while self.next_block(&mut block)? { + let h = block.header.expect("a decoded block has a header"); + match header { + None => { + out.resize_with(block.channels.len(), Vec::new); + header = Some(h); + } + Some(prev) + if prev.bits_per_sample != h.bits_per_sample + || prev.sample_rate != h.sample_rate + || prev.channels.channel_count() != h.channels.channel_count() => + { + return Err(Error::unsupported( + "FLAC stream changing format mid-stream", + format!( + "{}ch/{}bit/{}Hz became {}ch/{}bit/{}Hz", + prev.channels.channel_count(), + prev.bits_per_sample, + prev.sample_rate, + h.channels.channel_count(), + h.bits_per_sample, + h.sample_rate + ), + )); + } + Some(_) => {} + } + for (dst, src) in out.iter_mut().zip(&block.channels) { + dst.extend_from_slice(src); + } + } + let header = header.ok_or(Error::Eof)?; + Ok(DecodedStream { + bits_per_sample: header.bits_per_sample, + sample_rate: header.sample_rate, + channels: out, + }) + } +} + +/// The result of [`FlacReader::decode_all`]. +#[derive(Debug, Clone)] +pub struct DecodedStream { + /// Bit depth of the samples. + pub bits_per_sample: u32, + /// Sample rate in Hz. + pub sample_rate: u32, + /// One plane per channel, samples at the stream's own bit depth. + pub channels: Vec>, +} + +impl DecodedStream { + /// Samples per channel. + pub fn len(&self) -> usize { + self.channels.first().map_or(0, Vec::len) + } + + /// True when nothing decoded. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Interleaved samples at the stream's own bit depth. + pub fn interleaved(&self) -> Vec { + let channels = self.channels.len(); + let mut out = vec![0i32; self.len() * channels]; + for (c, plane) in self.channels.iter().enumerate() { + for (i, &s) in plane.iter().enumerate() { + out[i * channels + c] = s; + } + } + out + } + + /// Interleaved samples shifted into their PCM container, as raw bytes: + /// `s16le` for depths up to 16 bits, `s32le` above. This is exactly what + /// `ffmpeg -f s16le/-f s32le` writes for the same file. + pub fn to_pcm_bytes(&self) -> Vec { + let shift = container_shift(self.bits_per_sample); + let narrow = self.bits_per_sample <= 16; + let mut out = Vec::with_capacity(self.len() * self.channels.len() * 4); + for i in 0..self.len() { + for plane in &self.channels { + let v = plane[i] << shift; + match narrow { + true => out.extend_from_slice(&(v as i16).to_le_bytes()), + false => out.extend_from_slice(&v.to_le_bytes()), + } + } + } + out + } +} + +/// Byte offset of the next plausible frame sync at or after `from`. +/// +/// "Plausible" is: the 14-bit sync code, a zero reserved bit, and a header that +/// both parses and matches its own CRC-8. That is what makes resynchronisation +/// after damage, and opening a buffer that starts mid-stream, safe. +pub fn find_frame_sync(data: &[u8], from: usize, info: Option<&StreamInfo>) -> Option { + let mut at = from; + while at + 2 <= data.len() { + if data[at] == 0xff && data[at + 1] & 0xfe == 0xf8 { + let mut r = BitReader::new(&data[at..]); + if let Ok(_header) = parse_frame_header(&mut r, info) { + let n = (r.bit_position() / 8) as usize; + if at + n <= data.len() && crc8(&data[at..at + n - 1]) == data[at + n - 1] { + return Some(at); + } + } + } + at += 1; + } + None +} + +/// Parse a frame header, resolving the "same as `STREAMINFO`" codes. +pub fn parse_frame_header(r: &mut BitReader<'_>, info: Option<&StreamInfo>) -> Result { + if r.read_bits(14)? != 0x3ffe { + return Err(Error::corrupt("frame header: bad sync code")); + } + if r.read_bit()? { + return Err(Error::corrupt("frame header: reserved bit set")); + } + let variable_block_size = r.read_bit()?; + let block_size_code = r.read_bits(4)?; + let sample_rate_code = r.read_bits(4)?; + let channel_code = r.read_bits(4)?; + let bps_code = r.read_bits(3)?; + if r.read_bit()? { + return Err(Error::corrupt("frame header: second reserved bit set")); + } + + let number = read_utf8_number(r, if variable_block_size { 36 } else { 31 })?; + + let block_size = match block_size_code { + 0 => return Err(Error::corrupt("frame header: block size code 0")), + 1 => 192, + 2..=5 => 576 << (block_size_code - 2), + 6 => r.read_bits(8)? as usize + 1, + 7 => r.read_bits(16)? as usize + 1, + _ => 256 << (block_size_code - 8), + }; + let sample_rate = match sample_rate_code { + 0 => info + .map(|i| i.sample_rate) + .ok_or_else(|| Error::corrupt("frame header: rate from a missing STREAMINFO"))?, + 1 => 88200, + 2 => 176_400, + 3 => 192_000, + 4 => 8000, + 5 => 16000, + 6 => 22050, + 7 => 24000, + 8 => 32000, + 9 => 44100, + 10 => 48000, + 11 => 96000, + 12 => r.read_bits(8)? * 1000, + 13 => r.read_bits(16)?, + 14 => r.read_bits(16)? * 10, + _ => return Err(Error::corrupt("frame header: sample rate code 15")), + }; + let channels = match channel_code { + 0..=7 => ChannelAssignment::Independent(channel_code as u8 + 1), + 8 => ChannelAssignment::LeftSide, + 9 => ChannelAssignment::RightSide, + 10 => ChannelAssignment::MidSide, + _ => { + return Err(Error::corrupt(format!( + "frame header: channel assignment {channel_code}" + ))); + } + }; + let bits_per_sample = match bps_code { + 0 => info + .map(|i| u32::from(i.bits_per_sample)) + .ok_or_else(|| Error::corrupt("frame header: depth from a missing STREAMINFO"))?, + 1 => 8, + 2 => 12, + 3 => return Err(Error::corrupt("frame header: bit depth code 3 is reserved")), + 4 => 16, + 5 => 20, + 6 => 24, + _ => 32, + }; + // The CRC-8 byte closes the header; callers check it against the bytes they + // hold, so it is only skipped here. + r.skip_bits(8)?; + Ok(FrameHeader { + block_size, + sample_rate, + channels, + bits_per_sample, + number, + variable_block_size, + }) +} + +/// The UTF-8-shaped coded number of a frame header (up to 36 bits, so wider +/// than real UTF-8). +pub(crate) fn read_utf8_number(r: &mut BitReader<'_>, max_bits: u32) -> Result { + let first = r.read_bits(8)?; + let extra = match first { + 0x00..=0x7f => 0, + 0xc0..=0xdf => 1, + 0xe0..=0xef => 2, + 0xf0..=0xf7 => 3, + 0xf8..=0xfb => 4, + 0xfc..=0xfd => 5, + 0xfe => 6, + _ => return Err(Error::corrupt("frame header: bad coded-number prefix")), + }; + // The lead byte carries `6 - extra` payload bits after its prefix. + let mut value = match extra { + 0 => u64::from(first), + _ => u64::from(first & ((1u32 << (6 - extra)) - 1)), + }; + for _ in 0..extra { + let byte = r.read_bits(8)?; + if byte & 0xc0 != 0x80 { + return Err(Error::corrupt( + "frame header: bad coded-number continuation", + )); + } + value = (value << 6) | u64::from(byte & 0x3f); + } + if max_bits < 64 && value >> max_bits != 0 { + return Err(Error::corrupt(format!( + "frame header: coded number {value} exceeds {max_bits} bits" + ))); + } + Ok(value) +} + +fn decode_subframe( + r: &mut BitReader<'_>, + bps: u32, + block_size: usize, + out: &mut Vec, + residual: &mut Vec, +) -> Result<()> { + if r.read_bit()? { + return Err(Error::corrupt("subframe: padding bit set")); + } + let kind = r.read_bits(6)?; + let mut wasted = 0u32; + if r.read_bit()? { + wasted = 1; + while !r.read_bit()? { + wasted += 1; + if wasted >= bps { + break; + } + } + } + if wasted >= bps { + return Err(Error::corrupt(format!( + "subframe: {wasted} wasted bits of {bps}" + ))); + } + let bps = bps - wasted; + if bps > 32 { + // Only a 32-bit stream that also decorrelates its stereo pair gets + // here: its side channel needs 33 bits, which does not fit the i32 + // sample planes this decoder (and ffmpeg's, and libFLAC's encoder) + // works in. Named rather than mangled. + return Err(Error::unsupported( + "33-bit side subframe", + "32-bit stereo decorrelation needs 33-bit sample planes", + )); + } + + out.clear(); + out.reserve(block_size); + match kind { + 0 => { + let value = r.read_signed(bps)?; + out.resize(block_size, value); + } + 1 => { + for _ in 0..block_size { + out.push(r.read_signed(bps)?); + } + } + 8..=12 => decode_fixed(r, (kind - 8) as usize, bps, block_size, out, residual)?, + 32..=63 => decode_lpc(r, (kind - 31) as usize, bps, block_size, out, residual)?, + _ => { + return Err(Error::corrupt(format!("subframe: type {kind} is reserved"))); + } + } + if wasted > 0 { + for s in out.iter_mut() { + *s <<= wasted; + } + } + Ok(()) +} + +fn decode_fixed( + r: &mut BitReader<'_>, + order: usize, + bps: u32, + block_size: usize, + out: &mut Vec, + residual: &mut Vec, +) -> Result<()> { + if order > block_size { + return Err(Error::corrupt(format!( + "fixed subframe: order {order} over a {block_size}-sample block" + ))); + } + for _ in 0..order { + out.push(r.read_signed(bps)?); + } + decode_residual(r, block_size, order, residual)?; + for (i, &res) in residual.iter().enumerate() { + let n = order + i; + let p = &out[n - order..n]; + // Fixed predictors are the first four differences of the signal. + let predicted: i64 = match order { + 0 => 0, + 1 => i64::from(p[0]), + 2 => 2 * i64::from(p[1]) - i64::from(p[0]), + 3 => 3 * i64::from(p[2]) - 3 * i64::from(p[1]) + i64::from(p[0]), + _ => 4 * i64::from(p[3]) - 6 * i64::from(p[2]) + 4 * i64::from(p[1]) - i64::from(p[0]), + }; + out.push((predicted as i32).wrapping_add(res)); + } + Ok(()) +} + +fn decode_lpc( + r: &mut BitReader<'_>, + order: usize, + bps: u32, + block_size: usize, + out: &mut Vec, + residual: &mut Vec, +) -> Result<()> { + if order > block_size { + return Err(Error::corrupt(format!( + "LPC subframe: order {order} over a {block_size}-sample block" + ))); + } + for _ in 0..order { + out.push(r.read_signed(bps)?); + } + let precision = r.read_bits(4)? + 1; + if precision == 16 { + return Err(Error::corrupt("LPC subframe: coefficient precision 15+1")); + } + let shift = r.read_signed(5)?; + if shift < 0 { + return Err(Error::corrupt(format!( + "LPC subframe: negative shift {shift}" + ))); + } + let mut coefs = [0i64; 32]; + for c in coefs.iter_mut().take(order) { + *c = i64::from(r.read_signed(precision)?); + } + decode_residual(r, block_size, order, residual)?; + let coefs = &coefs[..order]; + for (i, &res) in residual.iter().enumerate() { + let n = order + i; + let history = &out[n - order..n]; + // 64-bit accumulation: 32-bit samples with 15-bit coefficients at order + // 32 need 52 bits, and the "predictor overflow" streams exist to catch + // a decoder that accumulates narrower. + let mut sum = 0i64; + for (c, &s) in coefs.iter().zip(history.iter().rev()) { + sum += c * i64::from(s); + } + out.push(((sum >> shift) as i32).wrapping_add(res)); + } + Ok(()) +} + +fn decode_residual( + r: &mut BitReader<'_>, + block_size: usize, + order: usize, + out: &mut Vec, +) -> Result<()> { + let method = r.read_bits(2)?; + let param_bits = match method { + 0 => 4, + 1 => 5, + _ => { + return Err(Error::corrupt(format!( + "residual: coding method {method} is reserved" + ))); + } + }; + let escape = (1u32 << param_bits) - 1; + let partition_order = r.read_bits(4)?; + let partitions = 1usize << partition_order; + if !block_size.is_multiple_of(partitions) { + return Err(Error::corrupt(format!( + "residual: {partitions} partitions over a {block_size}-sample block" + ))); + } + let partition_len = block_size / partitions; + if partition_len < order { + return Err(Error::corrupt(format!( + "residual: order {order} over {partition_len}-sample partitions" + ))); + } + out.clear(); + out.reserve(block_size - order); + for p in 0..partitions { + let count = partition_len - if p == 0 { order } else { 0 }; + let param = r.read_bits(param_bits)?; + if param == escape { + let raw = r.read_bits(5)?; + for _ in 0..count { + out.push(match raw { + 0 => 0, + n => r.read_signed(n)?, + }); + } + } else { + for _ in 0..count { + out.push(read_rice(r, param)?); + } + } + } + Ok(()) +} + +/// One Rice-coded, zig-zag folded residual. +fn read_rice(r: &mut BitReader<'_>, param: u32) -> Result { + let mut quotient = 0u32; + while !r.read_bit()? { + quotient += 1; + // A quotient wider than the sample container is damage, not data; the + // cap is what keeps a fuzzed stream from spinning to the end of the + // buffer one bit at a time. + if quotient > 1 << 20 { + return Err(Error::corrupt("residual: Rice quotient over 2^20")); + } + } + let folded = match param { + 0 => quotient, + n => (quotient << n) | r.read_bits(n)?, + }; + Ok(((folded >> 1) as i32) ^ -((folded & 1) as i32)) +} + +fn undecorrelate(assignment: ChannelAssignment, channels: &mut [Vec]) -> Result<()> { + if matches!(assignment, ChannelAssignment::Independent(_)) { + return Ok(()); + } + let (a, b) = channels.split_at_mut(1); + let (a, b) = (&mut a[0], &mut b[0]); + if a.len() != b.len() { + return Err(Error::corrupt("stereo decorrelation over unequal channels")); + } + match assignment { + ChannelAssignment::LeftSide => { + // a = left, b = left - right. + for (l, s) in a.iter().zip(b.iter_mut()) { + *s = l.wrapping_sub(*s); + } + } + ChannelAssignment::RightSide => { + // a = left - right, b = right. + for (s, r) in a.iter_mut().zip(b.iter()) { + *s = s.wrapping_add(*r); + } + } + ChannelAssignment::MidSide => { + for (m, s) in a.iter_mut().zip(b.iter_mut()) { + // The low bit of the difference is carried in the mid channel. + let mid = (*m << 1) | (*s & 1); + let side = *s; + *m = mid.wrapping_add(side) >> 1; + *s = mid.wrapping_sub(side) >> 1; + } + } + ChannelAssignment::Independent(_) => unreachable!("returned above"), + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stream_info_round_trips() { + let info = StreamInfo { + min_block_size: 4096, + max_block_size: 4096, + min_frame_size: 14, + max_frame_size: 16384, + sample_rate: 44100, + channels: 2, + bits_per_sample: 16, + total_samples: 1_234_567, + md5: [7; 16], + }; + assert_eq!(StreamInfo::parse(&info.to_bytes()).unwrap(), info); + } + + #[test] + fn truncated_input_is_need_more_not_a_panic() { + let info = StreamInfo { + min_block_size: 16, + max_block_size: 16, + min_frame_size: 0, + max_frame_size: 0, + sample_rate: 8000, + channels: 1, + bits_per_sample: 8, + total_samples: 0, + md5: [0; 16], + }; + let bytes = info.to_bytes(); + for n in 0..34 { + assert!(StreamInfo::parse(&bytes[..n]).unwrap_err().is_need_more()); + } + } + + #[test] + fn garbage_never_panics_and_never_opens() { + for seed in 0..64u32 { + let junk: Vec = (0..512).map(|i| (i * 37 + seed * 11) as u8).collect(); + let _ = FlacReader::new(&junk).map(|mut r| { + let mut b = Block::default(); + let _ = r.next_block(&mut b); + }); + } + } + + #[test] + fn mid_side_inverts_the_encoder_transform() { + let left: Vec = (-8..8).collect(); + let right: Vec = (0..16).map(|i| i * 3 - 20).collect(); + let mid: Vec = left.iter().zip(&right).map(|(l, r)| (l + r) >> 1).collect(); + let side: Vec = left.iter().zip(&right).map(|(l, r)| l - r).collect(); + let mut planes = vec![mid, side]; + undecorrelate(ChannelAssignment::MidSide, &mut planes).unwrap(); + assert_eq!(planes[0], left); + assert_eq!(planes[1], right); + } + + #[test] + fn container_shift_matches_ffmpeg_layout() { + assert_eq!(container_shift(8), 8); + assert_eq!(container_shift(12), 4); + assert_eq!(container_shift(16), 0); + assert_eq!(container_shift(20), 12); + assert_eq!(container_shift(24), 8); + assert_eq!(container_shift(32), 0); + } +} diff --git a/crates/ec-flac/src/encode.rs b/crates/ec-flac/src/encode.rs new file mode 100644 index 00000000..67ad8ff9 --- /dev/null +++ b/crates/ec-flac/src/encode.rs @@ -0,0 +1,966 @@ +//! FLAC encoding: fixed-block-size streams with constant, fixed, LPC and +//! verbatim subframes, a Rice partition search per residual and a per-block +//! stereo decorrelation decision. +//! +//! The output is a complete `.flac` file: `fLaC`, one `STREAMINFO` (carrying +//! the MD5 of the input, so any decoder can check us), then the frames. + +use ec_core::bitio::BitWriter; +use ec_core::error::{Error, Result}; + +use crate::checksum::{crc8, crc16, md5_of_samples}; +use crate::decode::StreamInfo; + +/// Encoder settings. [`EncoderConfig::default`] is the level the family ships: +/// 4096-sample blocks, LPC to order 12, Rice partitions to order 6. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncoderConfig { + /// Inter-channel samples per frame. + pub block_size: usize, + /// Highest LPC order tried; 0 disables LPC and leaves the fixed predictors. + pub max_lpc_order: usize, + /// Bits each quantised LPC coefficient is stored in (5..=15). + pub qlp_precision: u32, + /// Highest Rice partition order tried. + pub max_partition_order: u32, + /// Try left/side, right/side and mid/side on stereo input. + pub stereo_decorrelation: bool, +} + +impl Default for EncoderConfig { + fn default() -> Self { + EncoderConfig { + block_size: 4096, + max_lpc_order: 12, + qlp_precision: 15, + max_partition_order: 6, + stereo_decorrelation: true, + } + } +} + +impl EncoderConfig { + /// Refuse settings that cannot produce a legal stream. + pub fn verify(&self) -> Result<()> { + if !(16..=65535).contains(&self.block_size) { + return Err(Error::unsupported( + format!("block size {}", self.block_size), + "RFC 9639 allows 16..=65535", + )); + } + if self.max_lpc_order > 32 { + return Err(Error::unsupported( + format!("LPC order {}", self.max_lpc_order), + "RFC 9639 allows up to 32", + )); + } + if !(5..=15).contains(&self.qlp_precision) { + return Err(Error::unsupported( + format!("coefficient precision {}", self.qlp_precision), + "RFC 9639 allows 1..=15; below 5 is never useful", + )); + } + if self.max_partition_order > 15 { + return Err(Error::unsupported( + format!("partition order {}", self.max_partition_order), + "RFC 9639 allows up to 15", + )); + } + Ok(()) + } +} + +/// Encode interleaved samples into a complete FLAC stream. +/// +/// `samples` are interleaved by channel and must already fit in +/// `bits_per_sample`: a sample outside that range is [`Error::Corrupt`], +/// because silently clipping the caller's audio would make a lossless codec +/// lossy. +pub fn encode( + config: &EncoderConfig, + samples: &[i32], + channels: usize, + bits_per_sample: u32, + sample_rate: u32, +) -> Result> { + config.verify()?; + if !(1..=8).contains(&channels) { + return Err(Error::unsupported( + format!("{channels} channels"), + "FLAC codes 1..=8 channels", + )); + } + if !(4..=32).contains(&bits_per_sample) { + return Err(Error::unsupported( + format!("{bits_per_sample} bits per sample"), + "FLAC codes 4..=32 bits", + )); + } + if sample_rate == 0 || sample_rate > 655_350 { + return Err(Error::unsupported( + format!("{sample_rate} Hz"), + "FLAC codes 1..=655350 Hz", + )); + } + if !samples.len().is_multiple_of(channels) { + return Err(Error::corrupt(format!( + "{} samples do not divide into {channels} channels", + samples.len() + ))); + } + let (low, high) = match bits_per_sample { + 32 => (i32::MIN, i32::MAX), + n => (-(1i32 << (n - 1)), (1i32 << (n - 1)) - 1), + }; + if let Some(bad) = samples.iter().find(|&&s| s < low || s > high) { + return Err(Error::corrupt(format!( + "sample {bad} does not fit in {bits_per_sample} bits" + ))); + } + + let frames = samples.len() / channels; + let mut info = StreamInfo { + min_block_size: config.block_size as u16, + max_block_size: config.block_size as u16, + min_frame_size: 0, + max_frame_size: 0, + sample_rate, + channels: channels as u8, + bits_per_sample: bits_per_sample as u8, + total_samples: frames as u64, + md5: md5_of_samples(samples, bits_per_sample), + }; + + let mut out = Vec::with_capacity(samples.len() * bits_per_sample as usize / 8); + out.extend_from_slice(&crate::decode::MAGIC); + out.push(0x80); // last metadata block, type 0 (STREAMINFO) + out.extend_from_slice(&[0, 0, 34]); + let streaminfo_at = out.len(); + out.extend_from_slice(&info.to_bytes()); + + let mut planes: Vec> = (0..channels) + .map(|_| Vec::with_capacity(config.block_size)) + .collect(); + let mut scratch = Scratch::default(); + let mut min_frame = u32::MAX; + let mut max_frame = 0u32; + for (number, block) in samples.chunks(config.block_size * channels).enumerate() { + let block_size = block.len() / channels; + for (c, plane) in planes.iter_mut().enumerate() { + plane.clear(); + plane.extend(block.iter().skip(c).step_by(channels).copied()); + } + let frame = encode_frame( + config, + &planes, + block_size, + bits_per_sample, + sample_rate, + number as u64, + &mut scratch, + ); + min_frame = min_frame.min(frame.len() as u32); + max_frame = max_frame.max(frame.len() as u32); + out.extend_from_slice(&frame); + } + if frames > 0 { + info.min_frame_size = min_frame; + info.max_frame_size = max_frame; + out[streaminfo_at..streaminfo_at + 34].copy_from_slice(&info.to_bytes()); + } + Ok(out) +} + +/// Buffers reused across blocks: the two stereo candidates and the analysis +/// window, which depends only on the block size and so is built once. +#[derive(Debug, Default)] +struct Scratch { + mid: Vec, + side: Vec, + window: Vec, +} + +impl Scratch { + fn ensure_window(&mut self, n: usize) { + if self.window.len() != n { + self.window = tukey_window(n); + } + } +} + +#[allow(clippy::too_many_arguments)] +fn encode_frame( + config: &EncoderConfig, + planes: &[Vec], + block_size: usize, + bits_per_sample: u32, + sample_rate: u32, + number: u64, + scratch: &mut Scratch, +) -> Vec { + let channels = planes.len(); + // Channel assignment: 0..7 = that many independent channels, 8 = left/side, + // 9 = right/side, 10 = mid/side. Each candidate signal is planned once and + // the cheapest pairing wins — planning carries all the search cost, writing + // carries none. + let stereo = channels == 2 && config.stereo_decorrelation && bits_per_sample < 32; + if stereo { + scratch.mid.clear(); + scratch.side.clear(); + for (&l, &r) in planes[0].iter().zip(&planes[1]) { + // i64 first: `l - r` of two full-depth samples does not fit in i32. + scratch + .mid + .push(((i64::from(l) + i64::from(r)) >> 1) as i32); + scratch.side.push((i64::from(l) - i64::from(r)) as i32); + } + } + scratch.ensure_window(block_size); + let window = &scratch.window; + + let mut plans: Vec = planes + .iter() + .map(|plane| plan_subframe(config, plane, bits_per_sample, window)) + .collect(); + let mut assignment = channels as u32 - 1; + if stereo { + let mid = plan_subframe(config, &scratch.mid, bits_per_sample, window); + // The side channel needs one bit more than the stream's depth, which is + // why a 32-bit stream cannot be decorrelated at all. + let side = plan_subframe(config, &scratch.side, bits_per_sample + 1, window); + let (l, r) = (plans[0].bits, plans[1].bits); + let (_, best) = [ + (l + r, 1u32), + (l + side.bits, 8), + (side.bits + r, 9), + (mid.bits + side.bits, 10), + ] + .into_iter() + .min() + .expect("four candidates"); + assignment = best; + match best { + 8 => plans[1] = side, + 9 => plans[0] = side, + 10 => { + plans[0] = mid; + plans[1] = side; + } + _ => {} + } + } + + let mut w = BitWriter::with_capacity(block_size * channels * 2); + write_frame_header( + &mut w, + block_size, + sample_rate, + assignment, + bits_per_sample, + number, + ); + debug_assert!(w.is_byte_aligned()); + let crc = crc8(w.as_bytes()); + w.write_bits(u32::from(crc), 8); + for (c, plan) in plans.iter().enumerate() { + let side = matches!((assignment, c), (8, 1) | (10, 1) | (9, 0)); + write_subframe(&mut w, plan, bits_per_sample + u32::from(side)); + } + w.align_to_byte(); + let crc = crc16(w.as_bytes()); + w.write_bits(u32::from(crc), 16); + w.into_bytes() +} + +fn write_frame_header( + w: &mut BitWriter, + block_size: usize, + sample_rate: u32, + assignment: u32, + bits_per_sample: u32, + number: u64, +) { + let (bs_code, bs_extra) = match block_size { + 192 => (1, None), + 576 => (2, None), + 1152 => (3, None), + 2304 => (4, None), + 4608 => (5, None), + 256 => (8, None), + 512 => (9, None), + 1024 => (10, None), + 2048 => (11, None), + 4096 => (12, None), + 8192 => (13, None), + 16384 => (14, None), + 32768 => (15, None), + n if n <= 256 => (6, Some((n as u32 - 1, 8))), + n => (7, Some((n as u32 - 1, 16))), + }; + let (sr_code, sr_extra) = match sample_rate { + 88200 => (1, None), + 176_400 => (2, None), + 192_000 => (3, None), + 8000 => (4, None), + 16000 => (5, None), + 22050 => (6, None), + 24000 => (7, None), + 32000 => (8, None), + 44100 => (9, None), + 48000 => (10, None), + 96000 => (11, None), + n if n.is_multiple_of(1000) && n / 1000 <= 255 => (12, Some((n / 1000, 8))), + n if n <= 65535 => (13, Some((n, 16))), + n if n.is_multiple_of(10) && n / 10 <= 65535 => (14, Some((n / 10, 16))), + // Every rate `encode` accepts is covered above; code 0 (take the rate + // from STREAMINFO) is the honest fallback rather than a panic. + _ => (0, None), + }; + let bps_code = match bits_per_sample { + 8 => 1, + 12 => 2, + 16 => 4, + 20 => 5, + 24 => 6, + 32 => 7, + _ => 0, + }; + w.write_bits(0x3ffe, 14); + w.write_bit(false); // reserved + w.write_bit(false); // fixed block size: the coded number is a frame number + w.write_bits(bs_code, 4); + w.write_bits(sr_code, 4); + w.write_bits(assignment, 4); + w.write_bits(bps_code, 3); + w.write_bit(false); // reserved + write_utf8_number(w, number); + if let Some((value, bits)) = bs_extra { + w.write_bits(value, bits); + } + if let Some((value, bits)) = sr_extra { + w.write_bits(value, bits); + } +} + +/// The UTF-8-shaped coded number of a frame header (up to 36 bits, so wider +/// than real UTF-8 ever goes). +fn write_utf8_number(w: &mut BitWriter, value: u64) { + if value < 0x80 { + w.write_bits(value as u32, 8); + return; + } + // `extra` continuation bytes carry 6 bits each; the lead byte carries + // `6 - extra` after its prefix of `extra + 1` ones and a zero. + let mut extra = 1usize; + while extra < 6 && value >= 1u64 << (6 * extra + (6 - extra)) { + extra += 1; + } + let lead_bits = 6 - extra as u32; + let prefix = (0xffu32 << (7 - extra)) & 0xff; + let lead = prefix | ((value >> (6 * extra)) as u32 & ((1 << lead_bits) - 1)); + w.write_bits(lead, 8); + for i in (0..extra).rev() { + w.write_bits(0x80 | ((value >> (6 * i)) as u32 & 0x3f), 8); + } +} + +/// What a subframe will be written as, with its exact cost in bits. +#[derive(Debug, Clone)] +struct SubframePlan { + bits: usize, + wasted: u32, + kind: PlanKind, +} + +#[derive(Debug, Clone)] +enum PlanKind { + Constant(i32), + Verbatim(Vec), + Fixed { + warmup: Vec, + residual: Vec, + rice: RicePlan, + }, + Lpc { + warmup: Vec, + precision: u32, + shift: u32, + coefs: Vec, + residual: Vec, + rice: RicePlan, + }, +} + +#[derive(Debug, Clone, Default)] +struct RicePlan { + /// 4 or 5: the width of a partition's Rice parameter field. + param_bits: u32, + partition_order: u32, + /// Predictor order, which is what makes partition 0 shorter than the rest. + order: usize, + params: Vec, +} + +fn plan_subframe(config: &EncoderConfig, signal: &[i32], bps: u32, window: &[f64]) -> SubframePlan { + // Wasted bits: when every sample shares trailing zeros, state them once in + // the subframe header instead of once per sample. + let any_set = signal.iter().fold(0u32, |acc, &s| acc | s as u32); + let wasted = match any_set { + 0 => 0, + n => n.trailing_zeros().min(bps - 1), + }; + let shifted: Vec; + let signal = match wasted { + 0 => signal, + n => { + shifted = signal.iter().map(|&s| s >> n).collect(); + &shifted + } + }; + let bps = bps - wasted; + let header_bits = 8 + wasted as usize; + + if signal.is_empty() { + return SubframePlan { + bits: header_bits + bps as usize, + wasted, + kind: PlanKind::Constant(0), + }; + } + if signal.iter().all(|&s| s == signal[0]) { + return SubframePlan { + bits: header_bits + bps as usize, + wasted, + kind: PlanKind::Constant(signal[0]), + }; + } + + let mut best = SubframePlan { + bits: header_bits + signal.len() * bps as usize, + wasted, + kind: PlanKind::Verbatim(signal.to_vec()), + }; + if let Some(plan) = plan_fixed(config, signal, bps, header_bits) + && plan.bits < best.bits + { + best = SubframePlan { wasted, ..plan }; + } + if config.max_lpc_order > 0 + && signal.len() > config.max_lpc_order + && window.len() == signal.len() + && let Some(plan) = plan_lpc(config, signal, bps, header_bits, window) + && plan.bits < best.bits + { + best = SubframePlan { wasted, ..plan }; + } + best +} + +/// The five fixed predictors, the order chosen by the sum of absolute +/// residuals — the standard estimate; the Rice search then costs it exactly. +fn plan_fixed( + config: &EncoderConfig, + signal: &[i32], + bps: u32, + header_bits: usize, +) -> Option { + let max_order = 4.min(signal.len().saturating_sub(1)); + let mut diffs: Vec> = Vec::with_capacity(max_order + 1); + diffs.push(signal.iter().map(|&s| i64::from(s)).collect()); + for order in 1..=max_order { + diffs.push(diffs[order - 1].windows(2).map(|w| w[1] - w[0]).collect()); + } + // Compare orders over the same samples, so the estimate is not biased by a + // higher order simply covering fewer of them. + let order = (0..=max_order).min_by_key(|&o| { + let tail: u64 = diffs[o][max_order - o..] + .iter() + .map(|&d| d.unsigned_abs()) + .sum(); + tail + (o as u64) * u64::from(bps) + })?; + let residual: Vec = diffs[order] + .iter() + .map(|&d| i32::try_from(d)) + .collect::>() + .ok()?; // 32-bit input can overflow the residual; verbatim wins then. + let rice = plan_rice(config, &residual, signal.len(), order); + Some(SubframePlan { + bits: header_bits + order * bps as usize + rice.bits, + wasted: 0, + kind: PlanKind::Fixed { + warmup: signal[..order].to_vec(), + residual, + rice: rice.plan, + }, + }) +} + +fn plan_lpc( + config: &EncoderConfig, + signal: &[i32], + bps: u32, + header_bits: usize, + window: &[f64], +) -> Option { + let max_order = config.max_lpc_order.min(signal.len() - 1).min(32); + if max_order == 0 { + return None; + } + let windowed: Vec = window + .iter() + .zip(signal) + .map(|(w, &s)| w * f64::from(s)) + .collect(); + let autoc = autocorrelation(&windowed, max_order); + if autoc[0] == 0.0 { + return None; + } + let (coefs_by_order, errors) = levinson_durbin(&autoc, max_order); + + // Order choice by the usual estimate: every order costs its coefficients + // and saves half a bit per sample per halving of the prediction error. + let n = signal.len() as f64; + let cost = |o: usize| { + n / 2.0 * errors[o].max(1e-9).log2() + (o as f64) * f64::from(config.qlp_precision) + }; + let order = (1..=max_order) + .filter(|&o| !coefs_by_order[o].is_empty()) + .min_by(|&a, &b| cost(a).total_cmp(&cost(b)))?; + + let (coefs, shift) = quantize_coefficients(&coefs_by_order[order], config.qlp_precision)?; + let mut residual = Vec::with_capacity(signal.len() - order); + for i in order..signal.len() { + let mut sum = 0i64; + for (k, &c) in coefs.iter().enumerate() { + sum += i64::from(c) * i64::from(signal[i - 1 - k]); + } + let r = i64::from(signal[i]) - (sum >> shift); + residual.push(i32::try_from(r).ok()?); + } + let rice = plan_rice(config, &residual, signal.len(), order); + Some(SubframePlan { + bits: header_bits + + order * bps as usize + + 4 + + 5 + + order * config.qlp_precision as usize + + rice.bits, + wasted: 0, + kind: PlanKind::Lpc { + warmup: signal[..order].to_vec(), + precision: config.qlp_precision, + shift, + coefs, + residual, + rice: rice.plan, + }, + }) +} + +struct RiceChoice { + bits: usize, + plan: RicePlan, +} + +/// Choose the partition order and per-partition Rice parameters. +/// +/// Parameters come from partition sums with the usual estimate, then the whole +/// configuration is costed exactly — so orders are compared by real bit counts +/// rather than by two estimates. +fn plan_rice( + config: &EncoderConfig, + residual: &[i32], + block_size: usize, + order: usize, +) -> RiceChoice { + let folded: Vec = residual.iter().map(|&r| fold(r)).collect(); + let mut best: Option = None; + for partition_order in 0..=config.max_partition_order { + let partitions = 1usize << partition_order; + if !block_size.is_multiple_of(partitions) { + break; + } + let partition_len = block_size / partitions; + if partition_len <= order { + break; + } + let mut params = Vec::with_capacity(partitions); + let mut bits = 0usize; + let mut at = 0usize; + let mut max_param = 0u32; + for p in 0..partitions { + let count = partition_len - if p == 0 { order } else { 0 }; + let part = &folded[at..at + count]; + at += count; + let sum: u64 = part.iter().map(|&v| u64::from(v)).sum(); + let param = best_rice_param(sum, count as u64); + bits += part + .iter() + .map(|&v| (v >> param) as usize + 1 + param as usize) + .sum::(); + max_param = max_param.max(param); + params.push(param); + } + let param_bits = if max_param > 14 { 5 } else { 4 }; + bits += 2 + 4 + partitions * param_bits as usize; + let choice = RiceChoice { + bits, + plan: RicePlan { + param_bits, + partition_order, + order, + params, + }, + }; + if best.as_ref().is_none_or(|b| choice.bits < b.bits) { + best = Some(choice); + } + } + best.expect("partition order 0 is always legal") +} + +/// Zig-zag fold: FLAC codes residuals as unsigned with the sign in bit 0. +fn fold(r: i32) -> u32 { + ((r << 1) ^ (r >> 31)) as u32 +} + +/// The Rice parameter whose quotients cost least for a partition of `count` +/// folded values summing to `sum`, capped at 30 (31 is the escape code). +fn best_rice_param(sum: u64, count: u64) -> u32 { + if count == 0 { + return 0; + } + let mean = sum / count; + let mut param = 0u32; + while param < 30 && (1u64 << (param + 1)) <= mean { + param += 1; + } + let cost = |k: u32| count * (1 + u64::from(k)) + (sum >> k); + let mut best = param; + for k in param.saturating_sub(1)..=(param + 1).min(30) { + if cost(k) < cost(best) { + best = k; + } + } + best +} + +fn write_subframe(w: &mut BitWriter, plan: &SubframePlan, bps: u32) { + let kind_code = match &plan.kind { + PlanKind::Constant(_) => 0, + PlanKind::Verbatim(_) => 1, + PlanKind::Fixed { warmup, .. } => 8 + warmup.len() as u32, + PlanKind::Lpc { warmup, .. } => 31 + warmup.len() as u32, + }; + w.write_bit(false); + w.write_bits(kind_code, 6); + w.write_bit(plan.wasted > 0); + if plan.wasted > 0 { + // Unary: `wasted - 1` zeroes then a one. + for _ in 0..plan.wasted - 1 { + w.write_bit(false); + } + w.write_bit(true); + } + let bps = bps - plan.wasted; + match &plan.kind { + PlanKind::Constant(v) => w.write_signed(*v, bps), + PlanKind::Verbatim(samples) => { + for &s in samples { + w.write_signed(s, bps); + } + } + PlanKind::Fixed { + warmup, + residual, + rice, + } => { + for &s in warmup { + w.write_signed(s, bps); + } + write_residual(w, residual, rice); + } + PlanKind::Lpc { + warmup, + precision, + shift, + coefs, + residual, + rice, + } => { + for &s in warmup { + w.write_signed(s, bps); + } + w.write_bits(precision - 1, 4); + w.write_bits(*shift, 5); + for &c in coefs { + w.write_signed(c, *precision); + } + write_residual(w, residual, rice); + } + } +} + +fn write_residual(w: &mut BitWriter, residual: &[i32], rice: &RicePlan) { + w.write_bits(u32::from(rice.param_bits == 5), 2); + w.write_bits(rice.partition_order, 4); + let partitions = 1usize << rice.partition_order; + let partition_len = (residual.len() + rice.order) / partitions; + let mut at = 0usize; + for (p, ¶m) in rice.params.iter().enumerate() { + let count = partition_len - if p == 0 { rice.order } else { 0 }; + w.write_bits(param, rice.param_bits); + for &r in &residual[at..at + count] { + let folded = fold(r); + for _ in 0..folded >> param { + w.write_bit(false); + } + w.write_bit(true); + if param > 0 { + w.write_bits(folded & ((1 << param) - 1), param); + } + } + at += count; + } + debug_assert_eq!(at, residual.len()); +} + +fn tukey_window(n: usize) -> Vec { + // Tukey(0.5): a Hann taper over the outer quarter at each end, flat between. + const P: f64 = 0.5; + let taper = (P * (n as f64 - 1.0) / 2.0).max(1.0); + (0..n) + .map(|i| { + let i = i as f64; + let last = n as f64 - 1.0; + if i < taper { + 0.5 * (1.0 - (std::f64::consts::PI * i / taper).cos()) + } else if i > last - taper { + 0.5 * (1.0 - (std::f64::consts::PI * (last - i) / taper).cos()) + } else { + 1.0 + } + }) + .collect() +} + +fn autocorrelation(signal: &[f64], max_order: usize) -> Vec { + (0..=max_order) + .map(|lag| { + signal[lag..] + .iter() + .zip(signal) + .map(|(a, b)| a * b) + .sum::() + }) + .collect() +} + +/// Levinson-Durbin: predictor coefficients for every order up to `max_order`, +/// plus the prediction error each order leaves. +/// +/// The returned coefficients are in FLAC's sense — `x[n] ~ sum c[k]*x[n-1-k]` — +/// which is the negation of the recursion's internal ones. +fn levinson_durbin(autoc: &[f64], max_order: usize) -> (Vec>, Vec) { + let mut coefs = vec![Vec::new(); max_order + 1]; + let mut errors = vec![autoc[0]; max_order + 1]; + let mut a = vec![0.0f64; max_order]; + let mut err = autoc[0]; + for i in 0..max_order { + if err <= 0.0 { + break; + } + let mut r = -autoc[i + 1]; + for j in 0..i { + r -= a[j] * autoc[i - j]; + } + r /= err; + a[i] = r; + for j in 0..i / 2 { + let tmp = a[j]; + a[j] += r * a[i - 1 - j]; + a[i - 1 - j] += r * tmp; + } + if i % 2 == 1 { + let j = i / 2; + a[j] += a[j] * r; + } + err *= 1.0 - r * r; + errors[i + 1] = err; + coefs[i + 1] = a[..=i].iter().map(|&v| -v).collect(); + } + (coefs, errors) +} + +/// Quantise predictor coefficients to `precision` bits and a shift, carrying +/// the rounding error forward. +fn quantize_coefficients(coefs: &[f64], precision: u32) -> Option<(Vec, u32)> { + const MAX_SHIFT: i32 = 15; + let cmax = coefs.iter().fold(0.0f64, |m, c| m.max(c.abs())); + if cmax <= 0.0 || !cmax.is_finite() { + return None; + } + let log2cmax = cmax.log2().floor() as i32; + let shift = (precision as i32 - 1 - log2cmax - 1).min(MAX_SHIFT); + if shift < 0 { + return None; // coefficients too large to quantise; fixed predictors win. + } + let limit = 1i32 << (precision - 1); + let scale = f64::from(1i32 << shift); + let mut error = 0.0f64; + let mut out = Vec::with_capacity(coefs.len()); + for &c in coefs { + error += c * scale; + let q = error.round().clamp(f64::from(-limit), f64::from(limit - 1)) as i32; + error -= f64::from(q); + out.push(q); + } + Some((out, shift as u32)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::decode::{Block, FlacReader, read_utf8_number}; + use ec_core::bitio::BitReader; + + fn tone(frames: usize, channels: usize, bps: u32) -> Vec { + let amp = f64::from(1i32 << (bps - 2)); + (0..frames * channels) + .map(|i| { + let t = (i / channels) as f64; + let c = (i % channels) as f64; + (amp * ((t * 0.031 + c * 0.7).sin() + 0.2 * (t * 0.29).sin())) as i32 + }) + .collect() + } + + fn round_trip(samples: &[i32], channels: usize, bps: u32, rate: u32) { + let config = EncoderConfig::default(); + let bytes = encode(&config, samples, channels, bps, rate).expect("encode"); + let mut reader = FlacReader::new(&bytes).expect("open"); + let info = reader.stream_info().expect("streaminfo").clone(); + assert_eq!(info.sample_rate, rate); + assert_eq!(usize::from(info.channels), channels); + assert_eq!(u32::from(info.bits_per_sample), bps); + assert_eq!(info.total_samples, (samples.len() / channels) as u64); + let decoded = reader.decode_all().expect("decode"); + assert_eq!( + decoded.interleaved(), + samples, + "{channels}ch/{bps}bit/{rate}Hz did not round-trip" + ); + assert_eq!( + info.md5, + md5_of_samples(&decoded.interleaved(), bps), + "STREAMINFO MD5 must match the decoded audio" + ); + } + + #[test] + fn round_trips_every_shape_the_family_uses() { + for (channels, bps, rate) in [ + (1usize, 16u32, 44100u32), + (2, 16, 44100), + (2, 16, 48000), + (2, 24, 96000), + (6, 16, 48000), + (8, 24, 48000), + (1, 8, 8000), + (2, 20, 192_000), + ] { + round_trip(&tone(5000, channels, bps), channels, bps, rate); + } + } + + #[test] + fn round_trips_the_awkward_signals() { + let config = EncoderConfig::default(); + let cases: Vec> = vec![ + vec![0; 4096 * 2], // digital silence + vec![i32::from(i16::MIN); 100], // constant full scale + (0..8192) + .map(|i| if i % 64 < 32 { 3000 } else { -3000 }) + .collect(), // square + vec![-1], // one sample + (0..4096).map(|i| (i % 7) * 256).collect(), // wasted bits + (0..4096) + .map(|i| ((i * 2654435761u64 % 65536) as i32) - 32768) + .collect(), // noise + ]; + for samples in cases { + let bytes = encode(&config, &samples, 1, 16, 44100).expect("encode"); + let decoded = FlacReader::new(&bytes) + .expect("open") + .decode_all() + .expect("decode"); + assert_eq!(decoded.interleaved(), samples); + } + } + + #[test] + fn a_short_last_block_still_decodes() { + let config = EncoderConfig { + block_size: 512, + ..EncoderConfig::default() + }; + let samples = tone(1300, 2, 16); + let bytes = encode(&config, &samples, 2, 16, 44100).expect("encode"); + let mut reader = FlacReader::new(&bytes).expect("open"); + let mut block = Block::default(); + let mut sizes = Vec::new(); + while reader.next_block(&mut block).expect("frame") { + sizes.push(block.len()); + } + assert_eq!(sizes, vec![512, 512, 276]); + } + + #[test] + fn refuses_input_it_cannot_encode_losslessly() { + let config = EncoderConfig::default(); + assert!(encode(&config, &[1 << 20], 1, 16, 44100).is_err()); + assert!(encode(&config, &[1, 2, 3], 2, 16, 44100).is_err()); + assert!(encode(&config, &[0; 16], 9, 16, 44100).is_err()); + assert!(encode(&config, &[0; 16], 1, 33, 44100).is_err()); + assert!(encode(&config, &[0; 16], 1, 16, 0).is_err()); + } + + #[test] + fn utf8_coded_numbers_round_trip() { + for value in [ + 0u64, + 1, + 0x7f, + 0x80, + 0x7ff, + 0x800, + 0xffff, + 0x10_ffff, + 0x3ff_ffff, + 0x7fff_ffff, + ] { + let mut w = BitWriter::new(); + write_utf8_number(&mut w, value); + let bytes = w.into_bytes(); + let mut r = BitReader::new(&bytes); + assert_eq!( + read_utf8_number(&mut r, 36).unwrap(), + value, + "number {value}" + ); + } + } + + #[test] + fn compresses_better_than_raw_pcm() { + let samples = tone(44100, 2, 16); + let raw = samples.len() * 2; + let bytes = encode(&EncoderConfig::default(), &samples, 2, 16, 44100).unwrap(); + assert!( + bytes.len() < raw / 2, + "{} bytes from {raw} of PCM is not compression", + bytes.len() + ); + } +} diff --git a/crates/ec-flac/src/lib.rs b/crates/ec-flac/src/lib.rs new file mode 100644 index 00000000..11f5d585 --- /dev/null +++ b/crates/ec-flac/src/lib.rs @@ -0,0 +1,191 @@ +//! FLAC (RFC 9639) decoding and encoding for the edith_codecs family. +//! +//! Three ways in, smallest first: +//! +//! - [`decode::FlacReader`] over a whole `.flac` buffer — metadata, frames, +//! seek table, and [`decode::FlacReader::decode_all`] for the common case. +//! - [`FlacDecoder`], the [`ec_core::Decoder`] contract, for a container that +//! hands out one FLAC frame per packet. +//! - [`encode::encode`], interleaved samples in, a complete stream out, with +//! the `STREAMINFO` MD5 filled in so any decoder can prove we were lossless. +//! +//! Decoded samples keep their own bit depth in [`decode::Block`] and +//! [`decode::DecodedStream`]; the PCM views ([`decode::DecodedStream::to_pcm_bytes`], +//! [`FlacDecoder`]) shift them left into an `s16`/`s32` container the way +//! ffmpeg and the family's mixer expect. +//! +//! Nothing here panics on malformed input: truncation is `NeedMore`, a broken +//! stream is `Corrupt`, and both CRCs are checked on every frame. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +pub mod checksum; +pub mod decode; +pub mod encode; + +use ec_core::error::{Error, Result}; +use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; +use ec_core::packet::{Buf, Packet}; +use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters}; + +pub use decode::{Block, DecodedStream, FlacReader, StreamInfo}; +pub use encode::{EncoderConfig, encode}; + +/// The [`ec_core::Decoder`] seat for FLAC: one packet is one FLAC frame, which +/// is how Matroska, Ogg and the family's own probe deliver them. +#[derive(Debug)] +pub struct FlacDecoder { + params: CodecParameters, + stream_info: Option, + block: Block, + pending: Option, + drained: bool, +} + +impl FlacDecoder { + /// A decoder for a stream whose `extradata`, when present, is the 34-byte + /// `STREAMINFO` payload every container carries for FLAC. + pub fn new(params: CodecParameters) -> Result { + let stream_info = match ¶ms.extradata { + Some(bytes) if bytes.len() >= 34 => Some(StreamInfo::parse(&bytes[..34])?), + _ => None, + }; + Ok(FlacDecoder { + params, + stream_info, + block: Block::default(), + pending: None, + drained: false, + }) + } +} + +impl Decoder for FlacDecoder { + fn codec_parameters(&self) -> &CodecParameters { + &self.params + } + + fn send_packet(&mut self, packet: &Packet) -> Result<()> { + let mut reader = FlacReader::frames(&packet.data, self.stream_info.clone())?; + if !reader.next_block(&mut self.block)? { + return Err(Error::NeedMore); + } + let header = self.block.header.expect("a decoded block has a header"); + let shift = decode::container_shift(header.bits_per_sample); + let format = match header.bits_per_sample <= 16 { + true => SampleFormat::S16, + false => SampleFormat::S32, + }; + let samples = self.block.len(); + let interleaved = self.block.to_interleaved(shift); + let mut bytes = Vec::with_capacity(interleaved.len() * format.bytes_per_sample()); + for s in interleaved { + match format { + SampleFormat::S16 => bytes.extend_from_slice(&(s as i16).to_ne_bytes()), + _ => bytes.extend_from_slice(&s.to_ne_bytes()), + } + } + let layout = ChannelLayout::from_count(self.block.channels.len()); + let mut frame = AudioFrame::try_new( + format, + false, + layout.clone(), + header.sample_rate, + samples, + vec![Buf::from_vec(bytes)], + )?; + frame.pts = None; + self.params.media = MediaParameters::Audio(AudioParameters { + sample_rate: header.sample_rate, + layout, + format: Some(format), + bits_per_sample: Some(header.bits_per_sample), + }); + self.pending = Some(frame); + Ok(()) + } + + fn receive_frame(&mut self) -> Result { + match self.pending.take() { + Some(frame) => Ok(Frame::Audio(frame)), + None if self.drained => Err(Error::Eof), + None => Err(Error::NeedMore), + } + } + + fn flush(&mut self) -> Result<()> { + self.drained = true; + Ok(()) + } + + fn reset(&mut self) { + self.pending = None; + self.drained = false; + } +} + +/// Codec parameters for a FLAC stream described by its `STREAMINFO`. +pub fn codec_parameters(info: &StreamInfo) -> CodecParameters { + let mut params = CodecParameters::new(CodecId::Flac); + params.extradata = Some(Buf::from_vec(info.to_bytes().to_vec())); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate: info.sample_rate, + layout: ChannelLayout::from_count(usize::from(info.channels)), + format: Some(match info.bits_per_sample <= 16 { + true => SampleFormat::S16, + false => SampleFormat::S32, + }), + bits_per_sample: Some(u32::from(info.bits_per_sample)), + }); + params +} + +#[cfg(test)] +mod tests { + use super::*; + use ec_core::timebase::TimeBase; + + /// The container path: encode, hand each frame over as its own packet, and + /// get the same audio back through the family's `Decoder` trait. + #[test] + fn decoder_trait_round_trips_packet_by_packet() { + let samples: Vec = (0..8000) + .map(|i| ((i as f64 * 0.05).sin() * 8000.0) as i32) + .collect(); + let config = EncoderConfig { + block_size: 1024, + ..EncoderConfig::default() + }; + let stream = encode(&config, &samples, 2, 16, 44100).expect("encode"); + + let mut reader = FlacReader::new(&stream).expect("open"); + let info = reader.stream_info().expect("streaminfo").clone(); + let mut decoder = FlacDecoder::new(codec_parameters(&info)).expect("decoder"); + + // Slice the stream back into frames the way a demuxer would. + let mut block = Block::default(); + let mut bounds = vec![reader.position()]; + while reader.next_block(&mut block).expect("frame") { + bounds.push(reader.position()); + } + let time_base = TimeBase::new(1, 44100); + let mut got = Vec::new(); + for w in bounds.windows(2) { + let packet = Packet::new(0, time_base, &stream[w[0]..w[1]]); + decoder.send_packet(&packet).expect("send"); + let Frame::Audio(frame) = decoder.receive_frame().expect("receive") else { + panic!("FLAC decoded to a video frame"); + }; + assert_eq!(frame.format, SampleFormat::S16); + assert_eq!(frame.channels(), 2); + for chunk in frame.data[0].chunks_exact(2).take(frame.samples * 2) { + got.push(i16::from_ne_bytes([chunk[0], chunk[1]]) as i32); + } + } + assert_eq!(got, samples); + assert!(decoder.receive_frame().unwrap_err().is_need_more()); + decoder.flush().unwrap(); + assert!(decoder.receive_frame().unwrap_err().is_eof()); + } +} diff --git a/crates/ec-flac/tests/encode_matrix.rs b/crates/ec-flac/tests/encode_matrix.rs new file mode 100644 index 00000000..8eebeabf --- /dev/null +++ b/crates/ec-flac/tests/encode_matrix.rs @@ -0,0 +1,263 @@ +//! Our encoder against the fixture matrix, proven the only way a lossless +//! codec can be: encode, decode the result with ffmpeg, compare with the input +//! byte for byte. +//! +//! The size column is informational — it is the same corpus measured against +//! `ffmpeg -c:a flac` at its default compression level. +//! +//! Run the table: +//! cargo test -p ec-flac --release --test encode_matrix -- --nocapture + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_flac::encode::{EncoderConfig, encode}; + +struct Source { + path: PathBuf, + channels: usize, + rate: u32, + bits: u32, +} + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") +} + +/// A working directory keyed by test name: these tests are threads of one +/// process, so a shared temp directory would have them deleting each other's +/// files. +fn workdir(test: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ec-flac-{}-{test}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create work dir"); + dir +} + +fn probe(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a:0", + "-show_entries", + "stream=channels,sample_rate,bits_per_raw_sample,sample_fmt", + "-of", + "default=noprint_wrappers=1", + ]) + .arg(path) + .output() + .ok()?; + // Key=value, because ffprobe prints its own field order, not the requested + // one — a positional parse silently swaps rate and channels. + let text = String::from_utf8_lossy(&out.stdout); + let field = |key: &str| { + text.lines() + .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) + .map(str::trim) + }; + let bits = match field("bits_per_raw_sample").and_then(|v| v.parse::().ok()) { + Some(n) => n, + // WAV states no `bits_per_raw_sample`; its sample format carries it. + None => match field("sample_fmt")? { + "s16" | "s16p" => 16, + "s32" | "s32p" => 32, + "u8" | "u8p" => 8, + _ => return None, + }, + }; + Some(Source { + path: path.to_path_buf(), + channels: field("channels")?.parse().ok()?, + rate: field("sample_rate")?.parse().ok()?, + bits, + }) +} + +fn ffmpeg_pcm(path: &Path, bits: u32) -> Vec { + let format = if bits <= 16 { "s16le" } else { "s32le" }; + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", format, "-"]) + .output() + .expect("run ffmpeg"); + assert!( + out.status.success(), + "ffmpeg failed on {}: {}", + path.display(), + String::from_utf8_lossy(&out.stderr) + ); + out.stdout +} + +/// Raw PCM as the samples FLAC codes: the container shift undone. +fn samples_from_pcm(pcm: &[u8], bits: u32) -> Vec { + match bits <= 16 { + true => pcm + .chunks_exact(2) + .map(|c| i32::from(i16::from_le_bytes([c[0], c[1]])) >> (16 - bits)) + .collect(), + false => pcm + .chunks_exact(4) + .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) >> (32 - bits)) + .collect(), + } +} + +fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option { + let _ = std::fs::remove_file(out); + let status = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-i"]) + .arg(src) + .args(["-c:a", "flac"]) + .arg(out) + .status() + .ok()?; + match status.success() { + true => std::fs::metadata(out).ok().map(|m| m.len()), + false => None, + } +} + +fn matrix() -> Vec { + let audio = fixtures().join("audio"); + let vectors = fixtures().join("vectors/flac-xiph/flac-test-files-main/subset"); + let mut paths: Vec = Vec::new(); + if let Ok(entries) = std::fs::read_dir(&audio) { + let mut found: Vec = entries + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| { + let name = p.file_name().unwrap_or_default().to_string_lossy(); + name.starts_with("flac-") || name.starts_with("wav16-") + }) + .collect(); + found.sort(); + paths.append(&mut found); + } + // Depth coverage the generated fixtures do not have: 24- and 20-bit. + for name in [ + "28 - high resolution audio, default settings.flac", + "37 - 20 bit per sample.flac", + ] { + let p = vectors.join(name); + if p.exists() { + paths.push(p); + } + } + paths.iter().filter_map(|p| probe(p)).collect() +} + +#[test] +fn encoded_streams_decode_back_bit_exact_through_ffmpeg() { + let sources = matrix(); + if sources.is_empty() { + eprintln!("skipped: fixtures not generated"); + return; + } + let dir = workdir("roundtrip"); + let config = EncoderConfig::default(); + let mut failures = Vec::new(); + let (mut ours_total, mut theirs_total) = (0u64, 0u64); + println!( + "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}", + "fixture", "ch", "bit", "rate", "ours", "ffmpeg", "ratio" + ); + for source in &sources { + let name = source + .path + .file_name() + .unwrap_or_default() + .to_string_lossy() + .to_string(); + let pcm = ffmpeg_pcm(&source.path, source.bits); + let samples = samples_from_pcm(&pcm, source.bits); + let encoded = match encode(&config, &samples, source.channels, source.bits, source.rate) { + Ok(bytes) => bytes, + Err(e) => { + failures.push(format!("{name}: encode failed: {e}")); + continue; + } + }; + let out = dir.join(format!("{name}.ours.flac")); + std::fs::write(&out, &encoded).expect("write encoded"); + let decoded = ffmpeg_pcm(&out, source.bits); + if decoded != pcm { + let at = decoded + .iter() + .zip(&pcm) + .position(|(a, b)| a != b) + .map_or_else(|| "length only".to_string(), |i| format!("byte {i}")); + failures.push(format!( + "{name}: ffmpeg decoded our stream differently at {at} ({} vs {} bytes)", + decoded.len(), + pcm.len() + )); + continue; + } + let theirs = ffmpeg_flac_size(&source.path, &dir.join(format!("{name}.ffmpeg.flac"))); + ours_total += encoded.len() as u64; + theirs_total += theirs.unwrap_or(0); + println!( + "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}", + name, + source.channels, + source.bits, + source.rate, + encoded.len(), + theirs.map_or("-".to_string(), |n| n.to_string()), + theirs.map_or("-".to_string(), |n| format!( + "{:.3}", + encoded.len() as f64 / n as f64 + )), + ); + } + println!( + "totals: ours {ours_total}, ffmpeg {theirs_total}, ratio {:.3}", + ours_total as f64 / theirs_total.max(1) as f64 + ); + assert!(failures.is_empty(), "{}", failures.join("\n")); + // Informational bar from the slice charter: within 10% of ffmpeg's default. + assert!( + ours_total as f64 <= theirs_total as f64 * 1.10, + "corpus is {:.1}% larger than ffmpeg's default FLAC", + (ours_total as f64 / theirs_total as f64 - 1.0) * 100.0 + ); +} + +#[test] +fn our_streams_survive_a_probe_and_state_their_shape() { + let Some(source) = matrix().into_iter().find(|s| s.channels == 6) else { + eprintln!("skipped: no 5.1 fixture"); + return; + }; + let dir = workdir("probe"); + let pcm = ffmpeg_pcm(&source.path, source.bits); + let samples = samples_from_pcm(&pcm, source.bits); + let encoded = encode( + &EncoderConfig::default(), + &samples, + source.channels, + source.bits, + source.rate, + ) + .expect("encode"); + let out = dir.join("surround.flac"); + std::fs::write(&out, &encoded).expect("write"); + let probed = probe(&out).expect("ffprobe our own output"); + assert_eq!(probed.channels, source.channels); + assert_eq!(probed.rate, source.rate); + assert_eq!(probed.bits, source.bits); + // `-v error` clean: ffmpeg must find nothing to complain about. + let out_err = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(&out) + .args(["-f", "null", "-"]) + .output() + .expect("run ffmpeg"); + assert!( + out_err.stderr.is_empty(), + "ffmpeg complained: {}", + String::from_utf8_lossy(&out_err.stderr) + ); +} diff --git a/crates/ec-flac/tests/xiph_vectors.rs b/crates/ec-flac/tests/xiph_vectors.rs new file mode 100644 index 00000000..dcbbef53 --- /dev/null +++ b/crates/ec-flac/tests/xiph_vectors.rs @@ -0,0 +1,229 @@ +//! The Xiph FLAC test corpus, decoded and compared with ffmpeg byte for byte. +//! +//! ffmpeg is oracle tooling, driven through a pipe: it decodes the same file to +//! raw PCM (`s16le` up to 16 bits, `s32le` above, which is the layout +//! [`ec_flac::decode::DecodedStream::to_pcm_bytes`] writes) and the two buffers +//! must be identical. Lossless codec, no tolerance. +//! +//! The corpus is fetched by `scripts/fetch-vectors.sh`; without it every test +//! here skips rather than fails, so a fresh clone still runs green. +//! +//! Run the tables: +//! cargo test -p ec-flac --release --test xiph_vectors -- --nocapture + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_flac::checksum::md5_of_samples; +use ec_flac::decode::FlacReader; + +fn corpus(kind: &str) -> Option> { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures/vectors/flac-xiph/flac-test-files-main") + .join(kind); + let mut files: Vec = std::fs::read_dir(dir) + .ok()? + .filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.extension().is_some_and(|e| e == "flac")) + .collect(); + files.sort(); + match files.is_empty() { + true => None, + false => Some(files), + } +} + +/// Decode `path` with ffmpeg into the same raw layout our decoder writes. +fn ffmpeg_pcm(path: &Path, bits_per_sample: u32) -> Result, String> { + let format = match bits_per_sample <= 16 { + true => "s16le", + false => "s32le", + }; + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", format, "-"]) + .output() + .map_err(|e| format!("ffmpeg: {e}"))?; + match out.status.success() { + true => Ok(out.stdout), + false => Err(String::from_utf8_lossy(&out.stderr).trim().to_string()), + } +} + +fn name(path: &Path) -> String { + path.file_name() + .unwrap_or_default() + .to_string_lossy() + .into() +} + +#[test] +fn subset_vectors_decode_bit_exact_against_ffmpeg() { + let Some(files) = corpus("subset") else { + eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); + return; + }; + let mut failures = Vec::new(); + let mut passed = 0; + for path in &files { + let bytes = std::fs::read(path).expect("read fixture"); + let mut reader = match FlacReader::new(&bytes) { + Ok(r) => r, + Err(e) => { + failures.push(format!("{}: open failed: {e}", name(path))); + continue; + } + }; + let info = reader.stream_info().cloned(); + let decoded = match reader.decode_all() { + Ok(d) => d, + Err(e) => { + failures.push(format!("{}: decode failed: {e}", name(path))); + continue; + } + }; + let ours = decoded.to_pcm_bytes(); + let theirs = match ffmpeg_pcm(path, decoded.bits_per_sample) { + Ok(p) => p, + Err(e) => { + failures.push(format!("{}: ffmpeg failed: {e}", name(path))); + continue; + } + }; + if ours != theirs { + let at = ours + .iter() + .zip(&theirs) + .position(|(a, b)| a != b) + .map_or_else(|| "length only".to_string(), |i| format!("byte {i}")); + failures.push(format!( + "{}: differs at {at} ({} vs {} bytes)", + name(path), + ours.len(), + theirs.len() + )); + continue; + } + // Every subset file states an MD5; it must match what we decoded. + if let Some(info) = &info + && info.md5 != [0; 16] + { + let ours = md5_of_samples(&decoded.interleaved(), decoded.bits_per_sample); + if ours != info.md5 { + failures.push(format!("{}: STREAMINFO MD5 mismatch", name(path))); + continue; + } + } + passed += 1; + println!( + "PASS {:<70} {}ch {}bit {}Hz {} samples", + name(path), + decoded.channels.len(), + decoded.bits_per_sample, + decoded.sample_rate, + decoded.len() + ); + } + println!("subset: {passed}/{} bit-exact vs ffmpeg", files.len()); + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +#[test] +fn uncommon_vectors_decode_bit_exact_or_refuse_by_name() { + let Some(files) = corpus("uncommon") else { + eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); + return; + }; + let mut failures = Vec::new(); + for path in &files { + let bytes = std::fs::read(path).expect("read fixture"); + let outcome = FlacReader::new(&bytes).and_then(|mut r| r.decode_all()); + match outcome { + Ok(decoded) => { + let ours = decoded.to_pcm_bytes(); + match ffmpeg_pcm(path, decoded.bits_per_sample) { + Ok(theirs) if theirs == ours => { + println!("PASS {:<50} bit-exact", name(path)); + } + Ok(theirs) => failures.push(format!( + "{}: differs from ffmpeg ({} vs {} bytes)", + name(path), + ours.len(), + theirs.len() + )), + Err(e) => failures.push(format!("{}: ffmpeg failed: {e}", name(path))), + } + } + // A stream that changes channel count, depth or rate mid-way has no + // single PCM shape to answer with; refusing it by name is the + // contract (`Error::Unsupported` states what and why). + Err(e) => println!("REFUSED {:<46} {e}", name(path)), + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +#[test] +fn faulty_vectors_error_and_never_panic() { + let Some(files) = corpus("faulty") else { + eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); + return; + }; + // Faults our reader is expected to catch outright rather than decode past: + // these break the structure a decoder must trust. + let must_reject = ["06 - ", "07 - ", "08 - ", "09 - ", "11 - "]; + let mut failures = Vec::new(); + for path in &files { + let bytes = std::fs::read(path).expect("read fixture"); + let outcome = FlacReader::new(&bytes).and_then(|mut r| r.decode_all()); + let file = name(path); + let rejected = outcome.is_err(); + match &outcome { + Ok(d) => println!("DECODED {file:<58} {} samples", d.len()), + Err(e) => println!("ERROR {file:<58} {e}"), + } + if must_reject.iter().any(|p| file.starts_with(p)) && !rejected { + failures.push(format!("{file}: decoded a structurally broken stream")); + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +#[test] +fn seek_table_positions_the_reader_at_a_frame() { + let Some(files) = corpus("subset") else { + eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); + return; + }; + // "48 - Extremely large SEEKTABLE" is the file with a seek table worth + // exercising; any file carrying one proves the hook. + let mut checked = 0; + for path in files.iter() { + let bytes = std::fs::read(path).expect("read fixture"); + let mut reader = FlacReader::new(&bytes).expect("open"); + if reader.seek_table().is_empty() { + continue; + } + let target = reader.seek_table()[reader.seek_table().len() / 2]; + let landed = reader.seek_to_sample(target.sample + 1); + assert_eq!(landed, target.sample, "{}", name(path)); + let mut block = ec_flac::decode::Block::default(); + assert!( + reader.next_block(&mut block).expect("frame"), + "{}", + name(path) + ); + assert_eq!( + block.len(), + usize::from(target.frame_samples), + "{}", + name(path) + ); + checked += 1; + if checked == 3 { + break; + } + } + println!("seek: {checked} files with a seek table exercised"); +} diff --git a/shims/flacenc/Cargo.toml b/shims/flacenc/Cargo.toml new file mode 100644 index 00000000..add20396 --- /dev/null +++ b/shims/flacenc/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "flacenc" +description = "Compatibility shim: the flacenc 0.5.1 surface edith consumes, served by ec-flac." +version = "0.5.1" +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +ec-flac = { path = "../../crates/ec-flac", version = "0.1.0" } diff --git a/shims/flacenc/src/bitsink.rs b/shims/flacenc/src/bitsink.rs new file mode 100644 index 00000000..ab5160dc --- /dev/null +++ b/shims/flacenc/src/bitsink.rs @@ -0,0 +1,71 @@ +//! `flacenc::bitsink`: where a written stream lands. + +use std::convert::Infallible; + +/// Somewhere bits can be written. +/// +/// Only the part the replica needs: it constructs a [`ByteSink`], hands it to +/// `Stream::write` and reads the bytes back. +pub trait BitSink: Sized { + /// What writing can fail with. + type Error: std::error::Error; + + /// Append whole bytes. + fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Self::Error>; + + /// Bits written so far. + fn bit_len(&self) -> usize; +} + +/// A `Vec` sink — `flacenc::bitsink::ByteSink`. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ByteSink { + storage: Vec, +} + +impl ByteSink { + /// An empty sink. + pub fn new() -> Self { + ByteSink::default() + } + + /// An empty sink with room for `bits`. + pub fn with_capacity(bits: usize) -> Self { + ByteSink { + storage: Vec::with_capacity(bits.div_ceil(8)), + } + } + + /// The bytes written so far. + pub fn as_slice(&self) -> &[u8] { + &self.storage + } + + /// Take the bytes. + pub fn into_inner(self) -> Vec { + self.storage + } + + /// Bytes written so far. + pub fn len(&self) -> usize { + self.storage.len() + } + + /// True when nothing has been written. + pub fn is_empty(&self) -> bool { + self.storage.is_empty() + } +} + +impl BitSink for ByteSink { + type Error = Infallible; + + fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Infallible> { + self.storage.extend_from_slice(bytes); + Ok(()) + } + + fn bit_len(&self) -> usize { + self.storage.len() * 8 + } +} diff --git a/shims/flacenc/src/component.rs b/shims/flacenc/src/component.rs new file mode 100644 index 00000000..deff23a6 --- /dev/null +++ b/shims/flacenc/src/component.rs @@ -0,0 +1,112 @@ +//! `flacenc::component`: the encoded stream and its `STREAMINFO`. +//! +//! The incumbent models every FLAC component as an addressable value and +//! writes them out on demand. Ours holds the encoded bytes and the header +//! fields a caller is allowed to correct afterwards — which is the whole of +//! what the replica does with the tree. + +use crate::bitsink::BitSink; +use crate::error::{OutputError, VerifyError}; + +/// Something that can state its size and write itself to a [`BitSink`]. +pub trait BitRepr { + /// Bits this component occupies. + fn count_bits(&self) -> usize; + + /// Write the component out. + /// + /// # Errors + /// When the sink fails, or the component holds a value FLAC cannot express. + fn write(&self, dest: &mut S) -> Result<(), OutputError>; +} + +/// A complete encoded FLAC stream. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Stream { + bytes: Vec, + stream_info: StreamInfo, +} + +/// Offset of the `STREAMINFO` payload: `fLaC` plus the 4-byte block header. +const STREAM_INFO_AT: usize = 8; + +impl Stream { + pub(crate) fn from_bytes(bytes: Vec) -> Stream { + let min = u16::from_be_bytes([bytes[STREAM_INFO_AT], bytes[STREAM_INFO_AT + 1]]); + let max = u16::from_be_bytes([bytes[STREAM_INFO_AT + 2], bytes[STREAM_INFO_AT + 3]]); + Stream { + bytes, + stream_info: StreamInfo { + min_block_size: min, + max_block_size: max, + }, + } + } + + /// The stream's `STREAMINFO`, mutable. + pub fn stream_info_mut(&mut self) -> &mut StreamInfo { + &mut self.stream_info + } + + /// The stream's `STREAMINFO`. + pub fn stream_info(&self) -> &StreamInfo { + &self.stream_info + } +} + +impl BitRepr for Stream { + fn count_bits(&self) -> usize { + self.bytes.len() * 8 + } + + fn write(&self, dest: &mut S) -> Result<(), OutputError> { + // The declared block sizes are the one field a caller may have changed + // after encoding, so they are patched in on the way out. + let mut bytes = self.bytes.clone(); + bytes[STREAM_INFO_AT..STREAM_INFO_AT + 2] + .copy_from_slice(&self.stream_info.min_block_size.to_be_bytes()); + bytes[STREAM_INFO_AT + 2..STREAM_INFO_AT + 4] + .copy_from_slice(&self.stream_info.max_block_size.to_be_bytes()); + dest.write_bytes(&bytes) + .map_err(|e| OutputError::new(e.to_string())) + } +} + +/// The `STREAMINFO` fields a caller may correct after encoding. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StreamInfo { + min_block_size: u16, + max_block_size: u16, +} + +impl StreamInfo { + /// State the stream's block sizes. + /// + /// # Errors + /// When either value is not a legal block size. + pub fn set_block_sizes( + &mut self, + min_value: usize, + max_value: usize, + ) -> Result<(), VerifyError> { + self.min_block_size = u16::try_from(min_value) + .ok() + .filter(|&n| n >= 16) + .ok_or_else(|| VerifyError::new("min_block_size", "must be a valid block size."))?; + self.max_block_size = u16::try_from(max_value) + .ok() + .filter(|&n| n >= 16) + .ok_or_else(|| VerifyError::new("max_block_size", "must be a valid block size."))?; + Ok(()) + } + + /// Smallest block size stated by the stream. + pub fn min_block_size(&self) -> usize { + usize::from(self.min_block_size) + } + + /// Largest block size stated by the stream. + pub fn max_block_size(&self) -> usize { + usize::from(self.max_block_size) + } +} diff --git a/shims/flacenc/src/config.rs b/shims/flacenc/src/config.rs new file mode 100644 index 00000000..c539d68e --- /dev/null +++ b/shims/flacenc/src/config.rs @@ -0,0 +1,92 @@ +//! `flacenc::config`: the encoder configuration tree. +//! +//! The fields the replica reads (`block_size`) and the ones its `Default` +//! walks are kept; the knobs that only steer the incumbent's own search +//! (window functions, per-order caps) are not reproduced, because a value set +//! there would silently do nothing. + +use crate::error::{Verify, VerifyError}; + +/// Encoder configuration — `flacenc::config::Encoder`. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct Encoder { + /// Encoder block size. + pub block_size: usize, + /// Whether the encoder may use several threads. + pub multithread: bool, + /// Stereo coding switches. + pub stereo_coding: StereoCoding, + /// Per-channel coding switches. + pub subframe_coding: SubFrameCoding, +} + +impl Default for Encoder { + fn default() -> Self { + Encoder { + block_size: 4096, + multithread: false, + stereo_coding: StereoCoding::default(), + subframe_coding: SubFrameCoding::default(), + } + } +} + +impl Verify for Encoder { + fn verify(&self) -> Result<(), VerifyError> { + if !(16..=65535).contains(&self.block_size) { + return Err(VerifyError::new( + "block_size", + "must be in the range of 16..=65535.", + )); + } + Ok(()) + } +} + +/// Stereo coding switches — `flacenc::config::StereoCoding`. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct StereoCoding { + /// Allow left/side coding. + pub use_leftside: bool, + /// Allow right/side coding. + pub use_rightside: bool, + /// Allow mid/side coding. + pub use_midside: bool, +} + +impl Default for StereoCoding { + fn default() -> Self { + StereoCoding { + use_leftside: true, + use_rightside: true, + use_midside: true, + } + } +} + +/// Per-channel coding switches — `flacenc::config::SubFrameCoding`. +/// +/// Verbatim coding is deliberately not switchable: it is the representation +/// that always exists, so turning it off could leave a signal unencodable. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct SubFrameCoding { + /// Allow constant subframes. + pub use_constant: bool, + /// Allow fixed-predictor subframes. + pub use_fixed: bool, + /// Allow LPC subframes. + pub use_lpc: bool, +} + +impl Default for SubFrameCoding { + fn default() -> Self { + SubFrameCoding { + use_constant: true, + use_fixed: true, + use_lpc: true, + } + } +} diff --git a/shims/flacenc/src/error.rs b/shims/flacenc/src/error.rs new file mode 100644 index 00000000..e73ecdba --- /dev/null +++ b/shims/flacenc/src/error.rs @@ -0,0 +1,110 @@ +//! `flacenc::error`: verification wrappers and the error types the encoder +//! hands back. + +use std::fmt; +use std::marker::PhantomData; + +use crate::bitsink::BitSink; + +/// A value that has passed [`Verify::verify`]. +/// +/// Derefs to the value, which is how callers read `config.block_size` off a +/// verified config. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Verified(T); + +impl std::ops::Deref for Verified { + type Target = T; + fn deref(&self) -> &T { + &self.0 + } +} + +/// Configuration structs that can check their own consistency. +pub trait Verify: Sized { + /// Check every field; [`VerifyError`] names the first bad one. + fn verify(&self) -> Result<(), VerifyError>; + + /// Wrap into [`Verified`], or hand the value back with the reason. + fn into_verified(self) -> Result, (Self, VerifyError)> { + match self.verify() { + Ok(()) => Ok(Verified(self)), + Err(e) => Err((self, e)), + } + } +} + +/// A configuration field that is out of range, with the path to it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VerifyError { + components: Vec, + reason: String, +} + +impl VerifyError { + /// An error for an invalid field `component`. + pub fn new(component: &str, reason: &str) -> Self { + VerifyError { + components: vec![component.to_owned()], + reason: reason.to_owned(), + } + } + + /// Prefix the field path with an enclosing struct's field name. + pub fn within(mut self, component: &str) -> Self { + self.components.insert(0, component.to_owned()); + self + } +} + +impl fmt::Display for VerifyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "verification error: `{}` is not valid. reason: {}", + self.components.join("."), + self.reason + ) + } +} + +impl std::error::Error for VerifyError {} + +/// Encoding failed: either the source or the configuration. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncodeError(pub(crate) String); + +impl fmt::Display for EncodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for EncodeError {} + +/// Writing a component to a [`BitSink`] failed. +/// +/// Generic over the sink, as the incumbent is, so `write` signatures match; our +/// only sink is infallible, so this is never constructed in practice. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OutputError { + reason: String, + sink: PhantomData S>, +} + +impl OutputError { + pub(crate) fn new(reason: impl Into) -> Self { + OutputError { + reason: reason.into(), + sink: PhantomData, + } + } +} + +impl fmt::Display for OutputError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.reason) + } +} + +impl std::error::Error for OutputError {} diff --git a/shims/flacenc/src/lib.rs b/shims/flacenc/src/lib.rs new file mode 100644 index 00000000..dc49964c --- /dev/null +++ b/shims/flacenc/src/lib.rs @@ -0,0 +1,135 @@ +//! Drop-in replacement for the `flacenc` 0.5.1 surface the replica consumes, +//! implemented over [`ec_flac`]. +//! +//! It carries the incumbent's package name and version so the swap is a +//! `[patch.crates-io]` entry and nothing else. The scope is exactly the API +//! `engine/src/export.rs` calls (`export.rs:67-68,2930-2954`): +//! +//! ```no_run +//! use flacenc::component::BitRepr; +//! use flacenc::error::Verify; +//! +//! let config = flacenc::config::Encoder::default().into_verified().unwrap(); +//! let source = flacenc::source::MemSource::from_samples(&[0i32; 32], 2, 16, 44100); +//! let mut stream = +//! flacenc::encode_with_fixed_block_size(&config, source, config.block_size).unwrap(); +//! stream +//! .stream_info_mut() +//! .set_block_sizes(config.block_size, config.block_size) +//! .unwrap(); +//! let mut sink = flacenc::bitsink::ByteSink::new(); +//! stream.write(&mut sink).unwrap(); +//! let _bytes: &[u8] = sink.as_slice(); +//! ``` +//! +//! Signatures match the incumbent's (types, argument order, error shapes) so +//! call sites compile unchanged; the implementation behind them is ours. +//! Deliberately *not* covered: the `par` feature knobs, `serde` config +//! round-tripping and the component tree (`Frame`/`SubFrame`/`Residual` as +//! addressable values) — the replica constructs none of them. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +pub mod bitsink; +pub mod component; +pub mod config; +pub mod error; +pub mod source; + +pub use component::Stream; +pub use error::EncodeError; + +use error::Verified; +use source::Source; + +/// Encode `src` into a stream of fixed-size blocks. +/// +/// Mirrors `flacenc::encode_with_fixed_block_size`: the verified config, a +/// source, and the block size (which the caller reads off the config). +pub fn encode_with_fixed_block_size( + config: &Verified, + src: T, + block_size: usize, +) -> Result { + let encoder = ec_flac::EncoderConfig { + block_size, + stereo_decorrelation: config.stereo_coding.use_midside + || config.stereo_coding.use_leftside + || config.stereo_coding.use_rightside, + ..ec_flac::EncoderConfig::default() + }; + let bytes = ec_flac::encode( + &encoder, + src.as_raw_slice(), + src.channels(), + src.bits_per_sample() as u32, + src.sample_rate() as u32, + ) + .map_err(|e| EncodeError(e.to_string()))?; + Ok(Stream::from_bytes(bytes)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::component::BitRepr; + use crate::error::Verify; + + /// The replica's own call sequence, verbatim from `export.rs:2994-3025`, + /// with the result decoded back to prove it is a real FLAC stream. + #[test] + fn the_replica_call_sequence_produces_a_decodable_stream() { + let samples: Vec = (0..8192) + .map(|i| ((i as f64 * 0.07).sin() * 12000.0) as i32) + .collect(); + + let config = config::Encoder::default() + .into_verified() + .map_err(|(_, e)| format!("flac encoder config: {e}")) + .unwrap(); + let source = source::MemSource::from_samples(&samples, 2, 16, 44100); + let mut stream = encode_with_fixed_block_size(&config, source, config.block_size) + .map_err(|e| format!("flac encode: {e}")) + .unwrap(); + stream + .stream_info_mut() + .set_block_sizes(config.block_size, config.block_size) + .map_err(|e| format!("flac block size: {e}")) + .unwrap(); + let mut sink = bitsink::ByteSink::new(); + stream + .write(&mut sink) + .map_err(|e| format!("flac write: {e}")) + .unwrap(); + + let bytes = sink.as_slice(); + assert_eq!(&bytes[..4], b"fLaC"); + assert_eq!(stream.count_bits(), bytes.len() * 8); + let mut reader = ec_flac::FlacReader::new(bytes).expect("our own output opens"); + let info = reader.stream_info().expect("streaminfo").clone(); + assert_eq!(info.min_block_size, config.block_size as u16); + assert_eq!(info.max_block_size, config.block_size as u16); + let decoded = reader.decode_all().expect("decode"); + assert_eq!(decoded.interleaved(), samples, "the shim must be lossless"); + } + + #[test] + fn a_block_size_the_stream_cannot_hold_is_an_error_not_a_panic() { + let config = config::Encoder::default().into_verified().unwrap(); + let source = source::MemSource::from_samples(&[0i32; 64], 2, 16, 44100); + let mut stream = encode_with_fixed_block_size(&config, source, 32).unwrap(); + assert!(stream.stream_info_mut().set_block_sizes(0, 70000).is_err()); + } + + #[test] + fn an_invalid_config_is_refused_with_its_original_value() { + let config = config::Encoder { + block_size: 4, + ..config::Encoder::default() + }; + let (returned, error) = config.into_verified().unwrap_err(); + assert_eq!(returned.block_size, 4); + assert!(format!("{error}").contains("block_size")); + } +} diff --git a/shims/flacenc/src/source.rs b/shims/flacenc/src/source.rs new file mode 100644 index 00000000..d364ca54 --- /dev/null +++ b/shims/flacenc/src/source.rs @@ -0,0 +1,79 @@ +//! `flacenc::source`: where samples come from. + +/// A signal the encoder can read. +/// +/// The incumbent's trait is a pull interface with a reusable context; the +/// replica only ever hands over a [`MemSource`] it built from a `Vec`, so this +/// is the whole-buffer shape of the same thing. +pub trait Source { + /// Channel count. + fn channels(&self) -> usize; + /// Bits per sample. + fn bits_per_sample(&self) -> usize; + /// Sample rate in Hz. + fn sample_rate(&self) -> usize; + /// The interleaved samples. + fn as_raw_slice(&self) -> &[i32]; +} + +/// Samples already in memory — `flacenc::source::MemSource`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MemSource { + channels: usize, + bits_per_sample: usize, + sample_rate: usize, + samples: Vec, +} + +impl MemSource { + /// Build from interleaved samples. + pub fn from_samples( + samples: &[i32], + channels: usize, + bits_per_sample: usize, + sample_rate: usize, + ) -> Self { + MemSource { + channels, + bits_per_sample, + sample_rate, + samples: samples.to_owned(), + } + } + + /// The samples, interleaved. + pub fn as_raw_slice(&self) -> &[i32] { + &self.samples + } + + /// Inter-channel samples held. + pub fn len(&self) -> usize { + match self.channels { + 0 => 0, + n => self.samples.len() / n, + } + } + + /// True when the source holds no samples. + pub fn is_empty(&self) -> bool { + self.samples.is_empty() + } +} + +impl Source for MemSource { + fn channels(&self) -> usize { + self.channels + } + + fn bits_per_sample(&self) -> usize { + self.bits_per_sample + } + + fn sample_rate(&self) -> usize { + self.sample_rate + } + + fn as_raw_slice(&self) -> &[i32] { + &self.samples + } +}