Ec-flac decoder + encoder and the flacenc shim
Browse files at this commit339321d29ce3182bbfdb92318c9e1efb65fcd71cParent: 47772cb- feat
- ec-flac decoder + encoder and the flacenc shim
14 changed files +3500 -0
- crates/ec-flac/Cargo.toml +10 -0
- crates/ec-flac/src/checksum.rs +263 -0
- crates/ec-flac/src/decode.rs +968 -0
- crates/ec-flac/src/encode.rs +966 -0
- crates/ec-flac/src/lib.rs +191 -0
- crates/ec-flac/tests/encode_matrix.rs +263 -0
- crates/ec-flac/tests/xiph_vectors.rs +229 -0
- shims/flacenc/Cargo.toml +11 -0
- shims/flacenc/src/bitsink.rs +71 -0
- shims/flacenc/src/component.rs +112 -0
- shims/flacenc/src/config.rs +92 -0
- shims/flacenc/src/error.rs +110 -0
- shims/flacenc/src/lib.rs +135 -0
- shims/flacenc/src/source.rs +79 -0
crates/ec-flac/Cargo.tomladded+10 -0
| @@ -0,0 +1,10 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-flac" | ||
| 3 | +description = "FLAC decoder and encoder (RFC 9639), built on the edith_codecs IR." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
| 10 | +ec-core = { workspace = true } | ||
crates/ec-flac/src/checksum.rsadded+263 -0
| @@ -0,0 +1,263 @@ | |||
| 1 | +//! The three integrity primitives FLAC streams carry: CRC-8 over a frame | ||
| 2 | +//! header, CRC-16 over a whole frame, and the MD5 of the *unencoded* audio in | ||
| 3 | +//! `STREAMINFO`. | ||
| 4 | +//! | ||
| 5 | +//! MD5 is here rather than pulled in as a dependency because the family ships | ||
| 6 | +//! no third-party crates, and because FLAC needs exactly one thing from it: the | ||
| 7 | +//! digest of interleaved little-endian samples. | ||
| 8 | + | ||
| 9 | +/// CRC-8, polynomial `x^8 + x^2 + x + 1` (0x07), initial value 0 — the frame | ||
| 10 | +/// header check. | ||
| 11 | +pub fn crc8(data: &[u8]) -> u8 { | ||
| 12 | + let mut crc = 0u8; | ||
| 13 | + for &b in data { | ||
| 14 | + crc = CRC8[(crc ^ b) as usize]; | ||
| 15 | + } | ||
| 16 | + crc | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +/// CRC-16, polynomial `x^16 + x^15 + x^2 + 1` (0x8005), initial value 0 — the | ||
| 20 | +/// frame footer check, computed over the frame including its header. | ||
| 21 | +pub fn crc16(data: &[u8]) -> u16 { | ||
| 22 | + let mut crc = 0u16; | ||
| 23 | + for &b in data { | ||
| 24 | + crc = (crc << 8) ^ CRC16[(((crc >> 8) as u8) ^ b) as usize]; | ||
| 25 | + } | ||
| 26 | + crc | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +const CRC8: [u8; 256] = { | ||
| 30 | + let mut t = [0u8; 256]; | ||
| 31 | + let mut i = 0; | ||
| 32 | + while i < 256 { | ||
| 33 | + let mut c = i as u8; | ||
| 34 | + let mut b = 0; | ||
| 35 | + while b < 8 { | ||
| 36 | + c = if c & 0x80 != 0 { | ||
| 37 | + (c << 1) ^ 0x07 | ||
| 38 | + } else { | ||
| 39 | + c << 1 | ||
| 40 | + }; | ||
| 41 | + b += 1; | ||
| 42 | + } | ||
| 43 | + t[i] = c; | ||
| 44 | + i += 1; | ||
| 45 | + } | ||
| 46 | + t | ||
| 47 | +}; | ||
| 48 | + | ||
| 49 | +const CRC16: [u16; 256] = { | ||
| 50 | + let mut t = [0u16; 256]; | ||
| 51 | + let mut i = 0; | ||
| 52 | + while i < 256 { | ||
| 53 | + let mut c = (i as u16) << 8; | ||
| 54 | + let mut b = 0; | ||
| 55 | + while b < 8 { | ||
| 56 | + c = if c & 0x8000 != 0 { | ||
| 57 | + (c << 1) ^ 0x8005 | ||
| 58 | + } else { | ||
| 59 | + c << 1 | ||
| 60 | + }; | ||
| 61 | + b += 1; | ||
| 62 | + } | ||
| 63 | + t[i] = c; | ||
| 64 | + i += 1; | ||
| 65 | + } | ||
| 66 | + t | ||
| 67 | +}; | ||
| 68 | + | ||
| 69 | +/// MD5 (RFC 1321), streaming. | ||
| 70 | +#[derive(Debug, Clone)] | ||
| 71 | +pub struct Md5 { | ||
| 72 | + state: [u32; 4], | ||
| 73 | + len: u64, | ||
| 74 | + buf: [u8; 64], | ||
| 75 | + used: usize, | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +impl Default for Md5 { | ||
| 79 | + fn default() -> Self { | ||
| 80 | + Md5::new() | ||
| 81 | + } | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +impl Md5 { | ||
| 85 | + /// A fresh digest. | ||
| 86 | + pub fn new() -> Md5 { | ||
| 87 | + Md5 { | ||
| 88 | + state: [0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476], | ||
| 89 | + len: 0, | ||
| 90 | + buf: [0; 64], | ||
| 91 | + used: 0, | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + /// Feed bytes. | ||
| 96 | + pub fn update(&mut self, mut data: &[u8]) { | ||
| 97 | + self.len = self.len.wrapping_add(data.len() as u64); | ||
| 98 | + if self.used > 0 { | ||
| 99 | + let take = (64 - self.used).min(data.len()); | ||
| 100 | + self.buf[self.used..self.used + take].copy_from_slice(&data[..take]); | ||
| 101 | + self.used += take; | ||
| 102 | + data = &data[take..]; | ||
| 103 | + if self.used == 64 { | ||
| 104 | + let block = self.buf; | ||
| 105 | + self.compress(&block); | ||
| 106 | + self.used = 0; | ||
| 107 | + } | ||
| 108 | + // The tail below overwrites `used`, so a call that only topped up | ||
| 109 | + // the buffer has to stop here — otherwise the buffered bytes are | ||
| 110 | + // silently forgotten. | ||
| 111 | + if data.is_empty() { | ||
| 112 | + return; | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | + let mut chunks = data.chunks_exact(64); | ||
| 116 | + for chunk in &mut chunks { | ||
| 117 | + let mut block = [0u8; 64]; | ||
| 118 | + block.copy_from_slice(chunk); | ||
| 119 | + self.compress(&block); | ||
| 120 | + } | ||
| 121 | + let rest = chunks.remainder(); | ||
| 122 | + self.buf[..rest.len()].copy_from_slice(rest); | ||
| 123 | + self.used = rest.len(); | ||
| 124 | + } | ||
| 125 | + | ||
| 126 | + /// Finish and return the 16-byte digest. | ||
| 127 | + pub fn finish(mut self) -> [u8; 16] { | ||
| 128 | + let bits = self.len.wrapping_mul(8); | ||
| 129 | + self.update(&[0x80]); | ||
| 130 | + while self.used != 56 { | ||
| 131 | + self.update(&[0]); | ||
| 132 | + } | ||
| 133 | + self.update(&bits.to_le_bytes()); | ||
| 134 | + debug_assert_eq!(self.used, 0); | ||
| 135 | + let mut out = [0u8; 16]; | ||
| 136 | + for (i, word) in self.state.iter().enumerate() { | ||
| 137 | + out[i * 4..i * 4 + 4].copy_from_slice(&word.to_le_bytes()); | ||
| 138 | + } | ||
| 139 | + out | ||
| 140 | + } | ||
| 141 | + | ||
| 142 | + fn compress(&mut self, block: &[u8; 64]) { | ||
| 143 | + let mut m = [0u32; 16]; | ||
| 144 | + for (i, word) in m.iter_mut().enumerate() { | ||
| 145 | + *word = u32::from_le_bytes([ | ||
| 146 | + block[i * 4], | ||
| 147 | + block[i * 4 + 1], | ||
| 148 | + block[i * 4 + 2], | ||
| 149 | + block[i * 4 + 3], | ||
| 150 | + ]); | ||
| 151 | + } | ||
| 152 | + let [mut a, mut b, mut c, mut d] = self.state; | ||
| 153 | + for i in 0..64 { | ||
| 154 | + let (f, g) = match i / 16 { | ||
| 155 | + 0 => ((b & c) | (!b & d), i), | ||
| 156 | + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), | ||
| 157 | + 2 => (b ^ c ^ d, (3 * i + 5) % 16), | ||
| 158 | + _ => (c ^ (b | !d), (7 * i) % 16), | ||
| 159 | + }; | ||
| 160 | + let tmp = d; | ||
| 161 | + d = c; | ||
| 162 | + c = b; | ||
| 163 | + let sum = a.wrapping_add(f).wrapping_add(MD5_K[i]).wrapping_add(m[g]); | ||
| 164 | + b = b.wrapping_add(sum.rotate_left(MD5_S[i])); | ||
| 165 | + a = tmp; | ||
| 166 | + } | ||
| 167 | + self.state[0] = self.state[0].wrapping_add(a); | ||
| 168 | + self.state[1] = self.state[1].wrapping_add(b); | ||
| 169 | + self.state[2] = self.state[2].wrapping_add(c); | ||
| 170 | + self.state[3] = self.state[3].wrapping_add(d); | ||
| 171 | + } | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +/// MD5 of interleaved samples the way `STREAMINFO` defines it: each sample as | ||
| 175 | +/// `bits_per_sample / 8` little-endian bytes, signed, in channel order. | ||
| 176 | +pub fn md5_of_samples(samples: &[i32], bits_per_sample: u32) -> [u8; 16] { | ||
| 177 | + let bytes = bits_per_sample.div_ceil(8) as usize; | ||
| 178 | + let mut md5 = Md5::new(); | ||
| 179 | + // One buffered pass: a per-sample `update` call costs more than the hash. | ||
| 180 | + let mut buf = Vec::with_capacity(4096 * bytes); | ||
| 181 | + for &s in samples { | ||
| 182 | + buf.extend_from_slice(&s.to_le_bytes()[..bytes]); | ||
| 183 | + if buf.len() >= 4096 * bytes { | ||
| 184 | + md5.update(&buf); | ||
| 185 | + buf.clear(); | ||
| 186 | + } | ||
| 187 | + } | ||
| 188 | + md5.update(&buf); | ||
| 189 | + md5.finish() | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +const MD5_S: [u32; 64] = [ | ||
| 193 | + 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, | ||
| 194 | + 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, | ||
| 195 | + 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, | ||
| 196 | +]; | ||
| 197 | + | ||
| 198 | +#[rustfmt::skip] | ||
| 199 | +const MD5_K: [u32; 64] = { | ||
| 200 | + // K[i] = floor(2^32 * abs(sin(i + 1))), spelled out because `sin` is not | ||
| 201 | + // available in a const context. | ||
| 202 | + [ | ||
| 203 | + 0xd76a_a478, 0xe8c7_b756, 0x2420_70db, 0xc1bd_ceee, 0xf57c_0faf, 0x4787_c62a, 0xa830_4613, | ||
| 204 | + 0xfd46_9501, 0x6980_98d8, 0x8b44_f7af, 0xffff_5bb1, 0x895c_d7be, 0x6b90_1122, 0xfd98_7193, | ||
| 205 | + 0xa679_438e, 0x49b4_0821, 0xf61e_2562, 0xc040_b340, 0x265e_5a51, 0xe9b6_c7aa, 0xd62f_105d, | ||
| 206 | + 0x0244_1453, 0xd8a1_e681, 0xe7d3_fbc8, 0x21e1_cde6, 0xc337_07d6, 0xf4d5_0d87, 0x455a_14ed, | ||
| 207 | + 0xa9e3_e905, 0xfcef_a3f8, 0x676f_02d9, 0x8d2a_4c8a, 0xfffa_3942, 0x8771_f681, 0x6d9d_6122, | ||
| 208 | + 0xfde5_380c, 0xa4be_ea44, 0x4bde_cfa9, 0xf6bb_4b60, 0xbebf_bc70, 0x289b_7ec6, 0xeaa1_27fa, | ||
| 209 | + 0xd4ef_3085, 0x0488_1d05, 0xd9d4_d039, 0xe6db_99e5, 0x1fa2_7cf8, 0xc4ac_5665, 0xf429_2244, | ||
| 210 | + 0x432a_ff97, 0xab94_23a7, 0xfc93_a039, 0x655b_59c3, 0x8f0c_cc92, 0xffef_f47d, 0x8584_5dd1, | ||
| 211 | + 0x6fa8_7e4f, 0xfe2c_e6e0, 0xa301_4314, 0x4e08_11a1, 0xf753_7e82, 0xbd3a_f235, 0x2ad7_d2bb, | ||
| 212 | + 0xeb86_d391, | ||
| 213 | + ] | ||
| 214 | +}; | ||
| 215 | + | ||
| 216 | +#[cfg(test)] | ||
| 217 | +mod tests { | ||
| 218 | + use super::*; | ||
| 219 | + | ||
| 220 | + fn hex(d: [u8; 16]) -> String { | ||
| 221 | + d.iter().map(|b| format!("{b:02x}")).collect() | ||
| 222 | + } | ||
| 223 | + | ||
| 224 | + #[test] | ||
| 225 | + fn md5_matches_rfc1321_vectors() { | ||
| 226 | + let cases: [(&str, &str); 5] = [ | ||
| 227 | + ("", "d41d8cd98f00b204e9800998ecf8427e"), | ||
| 228 | + ("a", "0cc175b9c0f1b6a831c399e269772661"), | ||
| 229 | + ("abc", "900150983cd24fb0d6963f7d28e17f72"), | ||
| 230 | + ("message digest", "f96b697d7cb7938d525a2f31aaf161d0"), | ||
| 231 | + ( | ||
| 232 | + "12345678901234567890123456789012345678901234567890123456789012345678901234567890", | ||
| 233 | + "57edf4a22be3c955ac49da2e2107b67a", | ||
| 234 | + ), | ||
| 235 | + ]; | ||
| 236 | + for (input, want) in cases { | ||
| 237 | + let mut md5 = Md5::new(); | ||
| 238 | + md5.update(input.as_bytes()); | ||
| 239 | + assert_eq!(hex(md5.finish()), want, "md5({input:?})"); | ||
| 240 | + } | ||
| 241 | + } | ||
| 242 | + | ||
| 243 | + #[test] | ||
| 244 | + fn md5_is_split_invariant() { | ||
| 245 | + let data: Vec<u8> = (0..1000u32).map(|i| (i * 7) as u8).collect(); | ||
| 246 | + let mut whole = Md5::new(); | ||
| 247 | + whole.update(&data); | ||
| 248 | + let mut split = Md5::new(); | ||
| 249 | + for chunk in data.chunks(37) { | ||
| 250 | + split.update(chunk); | ||
| 251 | + } | ||
| 252 | + assert_eq!(whole.finish(), split.finish()); | ||
| 253 | + } | ||
| 254 | + | ||
| 255 | + #[test] | ||
| 256 | + fn crcs_match_known_values() { | ||
| 257 | + // CRC-8/SMBUS and CRC-16/UMTS check values, i.e. of "123456789". | ||
| 258 | + assert_eq!(crc8(b"123456789"), 0xf4); | ||
| 259 | + assert_eq!(crc16(b"123456789"), 0xfee8); | ||
| 260 | + assert_eq!(crc8(&[]), 0); | ||
| 261 | + assert_eq!(crc16(&[]), 0); | ||
| 262 | + } | ||
| 263 | +} | ||
crates/ec-flac/src/decode.rsadded+968 -0
| @@ -0,0 +1,968 @@ | |||
| 1 | +//! FLAC decoding: metadata blocks, frame headers, all four subframe kinds and | ||
| 2 | +//! the three stereo decorrelations, per RFC 9639. | ||
| 3 | +//! | ||
| 4 | +//! Every parse routine takes a borrowed buffer and answers with | ||
| 5 | +//! [`ec_core::Error`]: truncated input is `NeedMore`, a stream that breaks its | ||
| 6 | +//! own rules is `Corrupt`. Nothing here panics on input — the only asserts are | ||
| 7 | +//! in `ec_core::bitio`, and they fire on API misuse (`n > 64`), never on bytes. | ||
| 8 | + | ||
| 9 | +use ec_core::bitio::BitReader; | ||
| 10 | +use ec_core::error::{Error, Result}; | ||
| 11 | + | ||
| 12 | +use crate::checksum::{crc8, crc16}; | ||
| 13 | + | ||
| 14 | +/// The four bytes every FLAC stream starts with. | ||
| 15 | +pub const MAGIC: [u8; 4] = *b"fLaC"; | ||
| 16 | + | ||
| 17 | +/// Largest block size RFC 9639 can express (16-bit `block_size - 1`). | ||
| 18 | +pub const MAX_BLOCK_SIZE: usize = 65536; | ||
| 19 | + | ||
| 20 | +/// The `STREAMINFO` metadata block: everything a player needs before the first | ||
| 21 | +/// frame. | ||
| 22 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 23 | +pub struct StreamInfo { | ||
| 24 | + /// Smallest block size in the stream, in inter-channel samples. | ||
| 25 | + pub min_block_size: u16, | ||
| 26 | + /// Largest block size in the stream. Equal to `min_block_size` for a | ||
| 27 | + /// fixed-block-size stream. | ||
| 28 | + pub max_block_size: u16, | ||
| 29 | + /// Smallest frame size in bytes; 0 when the encoder did not state it. | ||
| 30 | + pub min_frame_size: u32, | ||
| 31 | + /// Largest frame size in bytes; 0 when the encoder did not state it. | ||
| 32 | + pub max_frame_size: u32, | ||
| 33 | + /// Sample rate in Hz. 0 means "non-audio stream" and is refused here. | ||
| 34 | + pub sample_rate: u32, | ||
| 35 | + /// Channel count, 1..=8. | ||
| 36 | + pub channels: u8, | ||
| 37 | + /// Bits per sample, 4..=32. | ||
| 38 | + pub bits_per_sample: u8, | ||
| 39 | + /// Total inter-channel samples, or 0 when unknown. | ||
| 40 | + pub total_samples: u64, | ||
| 41 | + /// MD5 of the unencoded audio; all zero when the encoder did not compute it. | ||
| 42 | + pub md5: [u8; 16], | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +impl StreamInfo { | ||
| 46 | + /// Parse the 34-byte `STREAMINFO` payload. | ||
| 47 | + pub fn parse(data: &[u8]) -> Result<StreamInfo> { | ||
| 48 | + if data.len() < 34 { | ||
| 49 | + return Err(Error::NeedMore); | ||
| 50 | + } | ||
| 51 | + let mut r = BitReader::new(data); | ||
| 52 | + let info = StreamInfo { | ||
| 53 | + min_block_size: r.read_bits(16)? as u16, | ||
| 54 | + max_block_size: r.read_bits(16)? as u16, | ||
| 55 | + min_frame_size: r.read_bits(24)?, | ||
| 56 | + max_frame_size: r.read_bits(24)?, | ||
| 57 | + sample_rate: r.read_bits(20)?, | ||
| 58 | + channels: (r.read_bits(3)? + 1) as u8, | ||
| 59 | + bits_per_sample: (r.read_bits(5)? + 1) as u8, | ||
| 60 | + total_samples: r.read_bits64(36)?, | ||
| 61 | + md5: data[18..34].try_into().expect("18..34 is 16 bytes"), | ||
| 62 | + }; | ||
| 63 | + if info.sample_rate == 0 { | ||
| 64 | + return Err(Error::corrupt("STREAMINFO: sample rate 0")); | ||
| 65 | + } | ||
| 66 | + if info.bits_per_sample < 4 { | ||
| 67 | + return Err(Error::corrupt(format!( | ||
| 68 | + "STREAMINFO: {} bits per sample", | ||
| 69 | + info.bits_per_sample | ||
| 70 | + ))); | ||
| 71 | + } | ||
| 72 | + if info.min_block_size < 16 || info.max_block_size < 16 { | ||
| 73 | + return Err(Error::corrupt(format!( | ||
| 74 | + "STREAMINFO: block sizes {}..{}", | ||
| 75 | + info.min_block_size, info.max_block_size | ||
| 76 | + ))); | ||
| 77 | + } | ||
| 78 | + Ok(info) | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + /// The 34-byte `STREAMINFO` payload. | ||
| 82 | + pub fn to_bytes(&self) -> [u8; 34] { | ||
| 83 | + let mut out = [0u8; 34]; | ||
| 84 | + out[0..2].copy_from_slice(&self.min_block_size.to_be_bytes()); | ||
| 85 | + out[2..4].copy_from_slice(&self.max_block_size.to_be_bytes()); | ||
| 86 | + out[4..7].copy_from_slice(&self.min_frame_size.to_be_bytes()[1..]); | ||
| 87 | + out[7..10].copy_from_slice(&self.max_frame_size.to_be_bytes()[1..]); | ||
| 88 | + let packed = (u64::from(self.sample_rate) << 44) | ||
| 89 | + | (u64::from(self.channels - 1) << 41) | ||
| 90 | + | (u64::from(self.bits_per_sample - 1) << 36) | ||
| 91 | + | (self.total_samples & 0xf_ffff_ffff); | ||
| 92 | + out[10..18].copy_from_slice(&packed.to_be_bytes()); | ||
| 93 | + out[18..34].copy_from_slice(&self.md5); | ||
| 94 | + out | ||
| 95 | + } | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// One entry of the `SEEKTABLE` block. | ||
| 99 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 100 | +pub struct SeekPoint { | ||
| 101 | + /// First sample of the target frame. | ||
| 102 | + pub sample: u64, | ||
| 103 | + /// Byte offset of that frame from the first byte of the first frame. | ||
| 104 | + pub offset: u64, | ||
| 105 | + /// Samples in the target frame. | ||
| 106 | + pub frame_samples: u16, | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +/// How the channels of one frame were decorrelated. | ||
| 110 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 111 | +pub enum ChannelAssignment { | ||
| 112 | + /// `n` channels, each coded on its own. | ||
| 113 | + Independent(u8), | ||
| 114 | + /// Channel 0 is left, channel 1 is `left - right`. | ||
| 115 | + LeftSide, | ||
| 116 | + /// Channel 0 is `left - right`, channel 1 is right. | ||
| 117 | + RightSide, | ||
| 118 | + /// Channel 0 is `(left + right) >> 1`, channel 1 is `left - right`. | ||
| 119 | + MidSide, | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +impl ChannelAssignment { | ||
| 123 | + /// Channels coded in the frame. | ||
| 124 | + pub fn channel_count(&self) -> usize { | ||
| 125 | + match self { | ||
| 126 | + ChannelAssignment::Independent(n) => *n as usize, | ||
| 127 | + _ => 2, | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +/// A parsed frame header, with the `STREAMINFO` fallbacks already resolved. | ||
| 133 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 134 | +pub struct FrameHeader { | ||
| 135 | + /// Inter-channel samples in this frame. | ||
| 136 | + pub block_size: usize, | ||
| 137 | + /// Sample rate in Hz. | ||
| 138 | + pub sample_rate: u32, | ||
| 139 | + /// Channel coding of this frame. | ||
| 140 | + pub channels: ChannelAssignment, | ||
| 141 | + /// Bits per sample of the *decoded* audio. | ||
| 142 | + pub bits_per_sample: u32, | ||
| 143 | + /// Frame number for a fixed-block-size stream, first sample number for a | ||
| 144 | + /// variable-block-size one. | ||
| 145 | + pub number: u64, | ||
| 146 | + /// True when the stream declares variable block sizes. | ||
| 147 | + pub variable_block_size: bool, | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +impl FrameHeader { | ||
| 151 | + /// First inter-channel sample of this frame, when it can be known: a | ||
| 152 | + /// variable-block-size stream states it, a fixed one implies it from the | ||
| 153 | + /// frame number and the block size the stream was written with. | ||
| 154 | + pub fn first_sample(&self, stream_block_size: Option<usize>) -> Option<u64> { | ||
| 155 | + match self.variable_block_size { | ||
| 156 | + true => Some(self.number), | ||
| 157 | + false => stream_block_size.map(|bs| self.number * bs as u64), | ||
| 158 | + } | ||
| 159 | + } | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// A decoded block: one `Vec<i32>` per channel, samples at the frame's own | ||
| 163 | +/// bit depth (not shifted). | ||
| 164 | +#[derive(Debug, Clone, Default)] | ||
| 165 | +pub struct Block { | ||
| 166 | + /// The header the samples came from. | ||
| 167 | + pub header: Option<FrameHeader>, | ||
| 168 | + /// Per-channel samples, already un-decorrelated. | ||
| 169 | + pub channels: Vec<Vec<i32>>, | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +impl Block { | ||
| 173 | + /// Samples per channel. | ||
| 174 | + pub fn len(&self) -> usize { | ||
| 175 | + self.channels.first().map_or(0, Vec::len) | ||
| 176 | + } | ||
| 177 | + | ||
| 178 | + /// True when no samples are held. | ||
| 179 | + pub fn is_empty(&self) -> bool { | ||
| 180 | + self.len() == 0 | ||
| 181 | + } | ||
| 182 | + | ||
| 183 | + /// The block interleaved into one buffer, samples shifted left so they fill | ||
| 184 | + /// a 16- or 32-bit container the way ffmpeg and every mixer expect | ||
| 185 | + /// (`s16` for depths up to 16, `s32` above). | ||
| 186 | + pub fn to_interleaved(&self, shift: u32) -> Vec<i32> { | ||
| 187 | + let channels = self.channels.len(); | ||
| 188 | + let len = self.len(); | ||
| 189 | + let mut out = vec![0i32; len * channels]; | ||
| 190 | + for (c, plane) in self.channels.iter().enumerate() { | ||
| 191 | + for (i, &s) in plane.iter().enumerate() { | ||
| 192 | + out[i * channels + c] = s << shift; | ||
| 193 | + } | ||
| 194 | + } | ||
| 195 | + out | ||
| 196 | + } | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +/// Bits the samples of a `bits_per_sample` stream are shifted left by to fill | ||
| 200 | +/// their PCM container — the convention ffmpeg's decoder uses, so raw output | ||
| 201 | +/// compares byte for byte. | ||
| 202 | +pub fn container_shift(bits_per_sample: u32) -> u32 { | ||
| 203 | + match bits_per_sample <= 16 { | ||
| 204 | + true => 16 - bits_per_sample, | ||
| 205 | + false => 32 - bits_per_sample, | ||
| 206 | + } | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +/// A FLAC stream over a complete in-memory buffer. | ||
| 210 | +/// | ||
| 211 | +/// Metadata is parsed on construction; frames are decoded one call at a time so | ||
| 212 | +/// a caller can stop, seek and resume without decoding what it will discard. | ||
| 213 | +#[derive(Debug)] | ||
| 214 | +pub struct FlacReader<'a> { | ||
| 215 | + data: &'a [u8], | ||
| 216 | + stream_info: Option<StreamInfo>, | ||
| 217 | + seek_table: Vec<SeekPoint>, | ||
| 218 | + first_frame: usize, | ||
| 219 | + pos: usize, | ||
| 220 | + residual: Vec<i32>, | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +impl<'a> FlacReader<'a> { | ||
| 224 | + /// Open a stream: read the magic and metadata blocks, then stop at the | ||
| 225 | + /// first frame. | ||
| 226 | + /// | ||
| 227 | + /// A buffer that does not start with `fLaC` is scanned for a frame sync | ||
| 228 | + /// instead — some tools hand out FLAC that starts mid-stream, and the frame | ||
| 229 | + /// headers carry enough to decode without `STREAMINFO`. | ||
| 230 | + pub fn new(data: &'a [u8]) -> Result<FlacReader<'a>> { | ||
| 231 | + let mut reader = FlacReader { | ||
| 232 | + data, | ||
| 233 | + stream_info: None, | ||
| 234 | + seek_table: Vec::new(), | ||
| 235 | + first_frame: 0, | ||
| 236 | + pos: 0, | ||
| 237 | + residual: Vec::new(), | ||
| 238 | + }; | ||
| 239 | + if data.len() >= 4 && data[..4] == MAGIC { | ||
| 240 | + reader.read_metadata(4)?; | ||
| 241 | + } else { | ||
| 242 | + reader.first_frame = find_frame_sync(data, 0, None) | ||
| 243 | + .ok_or_else(|| Error::corrupt("no fLaC magic and no frame sync"))?; | ||
| 244 | + reader.pos = reader.first_frame; | ||
| 245 | + } | ||
| 246 | + Ok(reader) | ||
| 247 | + } | ||
| 248 | + | ||
| 249 | + /// A reader over bare frames — what a container hands out, one packet at a | ||
| 250 | + /// time, with the `STREAMINFO` it carried in its own headers. | ||
| 251 | + pub fn frames(data: &'a [u8], info: Option<StreamInfo>) -> Result<FlacReader<'a>> { | ||
| 252 | + let first_frame = find_frame_sync(data, 0, info.as_ref()) | ||
| 253 | + .ok_or_else(|| Error::corrupt("no FLAC frame sync in this packet"))?; | ||
| 254 | + Ok(FlacReader { | ||
| 255 | + data, | ||
| 256 | + stream_info: info, | ||
| 257 | + seek_table: Vec::new(), | ||
| 258 | + first_frame, | ||
| 259 | + pos: first_frame, | ||
| 260 | + residual: Vec::new(), | ||
| 261 | + }) | ||
| 262 | + } | ||
| 263 | + | ||
| 264 | + fn read_metadata(&mut self, mut at: usize) -> Result<()> { | ||
| 265 | + let mut first = true; | ||
| 266 | + loop { | ||
| 267 | + let header = self.data.get(at..at + 4).ok_or(Error::NeedMore)?; | ||
| 268 | + let last = header[0] & 0x80 != 0; | ||
| 269 | + let kind = header[0] & 0x7f; | ||
| 270 | + let len = u32::from_be_bytes([0, header[1], header[2], header[3]]) as usize; | ||
| 271 | + let body = self.data.get(at + 4..at + 4 + len).ok_or(Error::NeedMore)?; | ||
| 272 | + if first && kind != 0 { | ||
| 273 | + return Err(Error::corrupt(format!( | ||
| 274 | + "first metadata block is type {kind}, not STREAMINFO" | ||
| 275 | + ))); | ||
| 276 | + } | ||
| 277 | + match kind { | ||
| 278 | + 0 => self.stream_info = Some(StreamInfo::parse(body)?), | ||
| 279 | + 3 => { | ||
| 280 | + self.seek_table = body | ||
| 281 | + .chunks_exact(18) | ||
| 282 | + .map(|p| SeekPoint { | ||
| 283 | + sample: u64::from_be_bytes(p[0..8].try_into().expect("8 bytes")), | ||
| 284 | + offset: u64::from_be_bytes(p[8..16].try_into().expect("8 bytes")), | ||
| 285 | + frame_samples: u16::from_be_bytes( | ||
| 286 | + p[16..18].try_into().expect("2 bytes"), | ||
| 287 | + ), | ||
| 288 | + }) | ||
| 289 | + // A placeholder point (sample == u64::MAX) indexes nothing. | ||
| 290 | + .filter(|p| p.sample != u64::MAX) | ||
| 291 | + .collect(); | ||
| 292 | + } | ||
| 293 | + 127 => return Err(Error::corrupt("metadata block type 127 is invalid")), | ||
| 294 | + _ => {} | ||
| 295 | + } | ||
| 296 | + first = false; | ||
| 297 | + at += 4 + len; | ||
| 298 | + if last { | ||
| 299 | + break; | ||
| 300 | + } | ||
| 301 | + } | ||
| 302 | + self.first_frame = at; | ||
| 303 | + self.pos = at; | ||
| 304 | + Ok(()) | ||
| 305 | + } | ||
| 306 | + | ||
| 307 | + /// The `STREAMINFO` block, when the stream had one. | ||
| 308 | + pub fn stream_info(&self) -> Option<&StreamInfo> { | ||
| 309 | + self.stream_info.as_ref() | ||
| 310 | + } | ||
| 311 | + | ||
| 312 | + /// The seek table, empty when the stream carries none. | ||
| 313 | + pub fn seek_table(&self) -> &[SeekPoint] { | ||
| 314 | + &self.seek_table | ||
| 315 | + } | ||
| 316 | + | ||
| 317 | + /// Byte offset of the next frame to be decoded. | ||
| 318 | + pub fn position(&self) -> usize { | ||
| 319 | + self.pos | ||
| 320 | + } | ||
| 321 | + | ||
| 322 | + /// Position the reader at the last indexed frame at or before `sample` and | ||
| 323 | + /// answer that frame's first sample; the caller decodes forward and | ||
| 324 | + /// discards the difference (`SeekMode::SyncBefore`). | ||
| 325 | + /// | ||
| 326 | + /// Without a seek table the answer is the start of the stream: FLAC frames | ||
| 327 | + /// are not self-indexing, so a blind scan would cost the same as decoding. | ||
| 328 | + pub fn seek_to_sample(&mut self, sample: u64) -> u64 { | ||
| 329 | + let point = self | ||
| 330 | + .seek_table | ||
| 331 | + .iter() | ||
| 332 | + .filter(|p| p.sample <= sample) | ||
| 333 | + .max_by_key(|p| p.sample); | ||
| 334 | + match point { | ||
| 335 | + Some(p) if self.first_frame + p.offset as usize <= self.data.len() => { | ||
| 336 | + self.pos = self.first_frame + p.offset as usize; | ||
| 337 | + p.sample | ||
| 338 | + } | ||
| 339 | + _ => { | ||
| 340 | + self.pos = self.first_frame; | ||
| 341 | + 0 | ||
| 342 | + } | ||
| 343 | + } | ||
| 344 | + } | ||
| 345 | + | ||
| 346 | + /// Decode the next frame into `block`, reusing its buffers. | ||
| 347 | + /// | ||
| 348 | + /// Answers `false` at the end of the stream. Trailing bytes that are not a | ||
| 349 | + /// frame (an ID3v1 tag, padding a container left) end the stream rather | ||
| 350 | + /// than failing it; a frame that starts well and then breaks is `Corrupt`. | ||
| 351 | + pub fn next_block(&mut self, block: &mut Block) -> Result<bool> { | ||
| 352 | + if self.pos >= self.data.len() { | ||
| 353 | + return Ok(false); | ||
| 354 | + } | ||
| 355 | + let start = match find_frame_sync(self.data, self.pos, self.stream_info.as_ref()) { | ||
| 356 | + Some(at) => at, | ||
| 357 | + None => { | ||
| 358 | + self.pos = self.data.len(); | ||
| 359 | + return Ok(false); | ||
| 360 | + } | ||
| 361 | + }; | ||
| 362 | + self.pos = start; | ||
| 363 | + let mut r = BitReader::new(&self.data[start..]); | ||
| 364 | + let header = parse_frame_header(&mut r, self.stream_info.as_ref())?; | ||
| 365 | + let header_bytes = (r.bit_position() / 8) as usize; | ||
| 366 | + let want = crc8(&self.data[start..start + header_bytes - 1]); | ||
| 367 | + if want != self.data[start + header_bytes - 1] { | ||
| 368 | + return Err(Error::corrupt(format!( | ||
| 369 | + "frame at {start}: header CRC-8 {:#04x}, expected {want:#04x}", | ||
| 370 | + self.data[start + header_bytes - 1] | ||
| 371 | + ))); | ||
| 372 | + } | ||
| 373 | + | ||
| 374 | + let coded = header.channels.channel_count(); | ||
| 375 | + block.channels.resize_with(coded, Vec::new); | ||
| 376 | + for (c, plane) in block.channels.iter_mut().enumerate() { | ||
| 377 | + let side = matches!( | ||
| 378 | + (header.channels, c), | ||
| 379 | + (ChannelAssignment::LeftSide, 1) | ||
| 380 | + | (ChannelAssignment::MidSide, 1) | ||
| 381 | + | (ChannelAssignment::RightSide, 0) | ||
| 382 | + ); | ||
| 383 | + let bps = header.bits_per_sample + u32::from(side); | ||
| 384 | + decode_subframe(&mut r, bps, header.block_size, plane, &mut self.residual)?; | ||
| 385 | + } | ||
| 386 | + r.align_to_byte(); | ||
| 387 | + let frame_bytes = (r.bit_position() / 8) as usize; | ||
| 388 | + let stated = r.read_bits(16)? as u16; | ||
| 389 | + let want = crc16(&self.data[start..start + frame_bytes]); | ||
| 390 | + if stated != want { | ||
| 391 | + return Err(Error::corrupt(format!( | ||
| 392 | + "frame at {start}: CRC-16 {stated:#06x}, expected {want:#06x}" | ||
| 393 | + ))); | ||
| 394 | + } | ||
| 395 | + undecorrelate(header.channels, &mut block.channels)?; | ||
| 396 | + block.header = Some(header); | ||
| 397 | + self.pos = start + frame_bytes + 2; | ||
| 398 | + Ok(true) | ||
| 399 | + } | ||
| 400 | + | ||
| 401 | + /// Decode the whole stream into per-channel planes, verifying the | ||
| 402 | + /// `STREAMINFO` MD5 when the stream states one. | ||
| 403 | + /// | ||
| 404 | + /// Convenience over [`FlacReader::next_block`]: it holds the whole decoded | ||
| 405 | + /// stream in memory, which is what a fixture test and a waveform pass want | ||
| 406 | + /// and what a player does not. | ||
| 407 | + pub fn decode_all(&mut self) -> Result<DecodedStream> { | ||
| 408 | + let mut block = Block::default(); | ||
| 409 | + let mut out: Vec<Vec<i32>> = Vec::new(); | ||
| 410 | + let mut header: Option<FrameHeader> = None; | ||
| 411 | + while self.next_block(&mut block)? { | ||
| 412 | + let h = block.header.expect("a decoded block has a header"); | ||
| 413 | + match header { | ||
| 414 | + None => { | ||
| 415 | + out.resize_with(block.channels.len(), Vec::new); | ||
| 416 | + header = Some(h); | ||
| 417 | + } | ||
| 418 | + Some(prev) | ||
| 419 | + if prev.bits_per_sample != h.bits_per_sample | ||
| 420 | + || prev.sample_rate != h.sample_rate | ||
| 421 | + || prev.channels.channel_count() != h.channels.channel_count() => | ||
| 422 | + { | ||
| 423 | + return Err(Error::unsupported( | ||
| 424 | + "FLAC stream changing format mid-stream", | ||
| 425 | + format!( | ||
| 426 | + "{}ch/{}bit/{}Hz became {}ch/{}bit/{}Hz", | ||
| 427 | + prev.channels.channel_count(), | ||
| 428 | + prev.bits_per_sample, | ||
| 429 | + prev.sample_rate, | ||
| 430 | + h.channels.channel_count(), | ||
| 431 | + h.bits_per_sample, | ||
| 432 | + h.sample_rate | ||
| 433 | + ), | ||
| 434 | + )); | ||
| 435 | + } | ||
| 436 | + Some(_) => {} | ||
| 437 | + } | ||
| 438 | + for (dst, src) in out.iter_mut().zip(&block.channels) { | ||
| 439 | + dst.extend_from_slice(src); | ||
| 440 | + } | ||
| 441 | + } | ||
| 442 | + let header = header.ok_or(Error::Eof)?; | ||
| 443 | + Ok(DecodedStream { | ||
| 444 | + bits_per_sample: header.bits_per_sample, | ||
| 445 | + sample_rate: header.sample_rate, | ||
| 446 | + channels: out, | ||
| 447 | + }) | ||
| 448 | + } | ||
| 449 | +} | ||
| 450 | + | ||
| 451 | +/// The result of [`FlacReader::decode_all`]. | ||
| 452 | +#[derive(Debug, Clone)] | ||
| 453 | +pub struct DecodedStream { | ||
| 454 | + /// Bit depth of the samples. | ||
| 455 | + pub bits_per_sample: u32, | ||
| 456 | + /// Sample rate in Hz. | ||
| 457 | + pub sample_rate: u32, | ||
| 458 | + /// One plane per channel, samples at the stream's own bit depth. | ||
| 459 | + pub channels: Vec<Vec<i32>>, | ||
| 460 | +} | ||
| 461 | + | ||
| 462 | +impl DecodedStream { | ||
| 463 | + /// Samples per channel. | ||
| 464 | + pub fn len(&self) -> usize { | ||
| 465 | + self.channels.first().map_or(0, Vec::len) | ||
| 466 | + } | ||
| 467 | + | ||
| 468 | + /// True when nothing decoded. | ||
| 469 | + pub fn is_empty(&self) -> bool { | ||
| 470 | + self.len() == 0 | ||
| 471 | + } | ||
| 472 | + | ||
| 473 | + /// Interleaved samples at the stream's own bit depth. | ||
| 474 | + pub fn interleaved(&self) -> Vec<i32> { | ||
| 475 | + let channels = self.channels.len(); | ||
| 476 | + let mut out = vec![0i32; self.len() * channels]; | ||
| 477 | + for (c, plane) in self.channels.iter().enumerate() { | ||
| 478 | + for (i, &s) in plane.iter().enumerate() { | ||
| 479 | + out[i * channels + c] = s; | ||
| 480 | + } | ||
| 481 | + } | ||
| 482 | + out | ||
| 483 | + } | ||
| 484 | + | ||
| 485 | + /// Interleaved samples shifted into their PCM container, as raw bytes: | ||
| 486 | + /// `s16le` for depths up to 16 bits, `s32le` above. This is exactly what | ||
| 487 | + /// `ffmpeg -f s16le/-f s32le` writes for the same file. | ||
| 488 | + pub fn to_pcm_bytes(&self) -> Vec<u8> { | ||
| 489 | + let shift = container_shift(self.bits_per_sample); | ||
| 490 | + let narrow = self.bits_per_sample <= 16; | ||
| 491 | + let mut out = Vec::with_capacity(self.len() * self.channels.len() * 4); | ||
| 492 | + for i in 0..self.len() { | ||
| 493 | + for plane in &self.channels { | ||
| 494 | + let v = plane[i] << shift; | ||
| 495 | + match narrow { | ||
| 496 | + true => out.extend_from_slice(&(v as i16).to_le_bytes()), | ||
| 497 | + false => out.extend_from_slice(&v.to_le_bytes()), | ||
| 498 | + } | ||
| 499 | + } | ||
| 500 | + } | ||
| 501 | + out | ||
| 502 | + } | ||
| 503 | +} | ||
| 504 | + | ||
| 505 | +/// Byte offset of the next plausible frame sync at or after `from`. | ||
| 506 | +/// | ||
| 507 | +/// "Plausible" is: the 14-bit sync code, a zero reserved bit, and a header that | ||
| 508 | +/// both parses and matches its own CRC-8. That is what makes resynchronisation | ||
| 509 | +/// after damage, and opening a buffer that starts mid-stream, safe. | ||
| 510 | +pub fn find_frame_sync(data: &[u8], from: usize, info: Option<&StreamInfo>) -> Option<usize> { | ||
| 511 | + let mut at = from; | ||
| 512 | + while at + 2 <= data.len() { | ||
| 513 | + if data[at] == 0xff && data[at + 1] & 0xfe == 0xf8 { | ||
| 514 | + let mut r = BitReader::new(&data[at..]); | ||
| 515 | + if let Ok(_header) = parse_frame_header(&mut r, info) { | ||
| 516 | + let n = (r.bit_position() / 8) as usize; | ||
| 517 | + if at + n <= data.len() && crc8(&data[at..at + n - 1]) == data[at + n - 1] { | ||
| 518 | + return Some(at); | ||
| 519 | + } | ||
| 520 | + } | ||
| 521 | + } | ||
| 522 | + at += 1; | ||
| 523 | + } | ||
| 524 | + None | ||
| 525 | +} | ||
| 526 | + | ||
| 527 | +/// Parse a frame header, resolving the "same as `STREAMINFO`" codes. | ||
| 528 | +pub fn parse_frame_header(r: &mut BitReader<'_>, info: Option<&StreamInfo>) -> Result<FrameHeader> { | ||
| 529 | + if r.read_bits(14)? != 0x3ffe { | ||
| 530 | + return Err(Error::corrupt("frame header: bad sync code")); | ||
| 531 | + } | ||
| 532 | + if r.read_bit()? { | ||
| 533 | + return Err(Error::corrupt("frame header: reserved bit set")); | ||
| 534 | + } | ||
| 535 | + let variable_block_size = r.read_bit()?; | ||
| 536 | + let block_size_code = r.read_bits(4)?; | ||
| 537 | + let sample_rate_code = r.read_bits(4)?; | ||
| 538 | + let channel_code = r.read_bits(4)?; | ||
| 539 | + let bps_code = r.read_bits(3)?; | ||
| 540 | + if r.read_bit()? { | ||
| 541 | + return Err(Error::corrupt("frame header: second reserved bit set")); | ||
| 542 | + } | ||
| 543 | + | ||
| 544 | + let number = read_utf8_number(r, if variable_block_size { 36 } else { 31 })?; | ||
| 545 | + | ||
| 546 | + let block_size = match block_size_code { | ||
| 547 | + 0 => return Err(Error::corrupt("frame header: block size code 0")), | ||
| 548 | + 1 => 192, | ||
| 549 | + 2..=5 => 576 << (block_size_code - 2), | ||
| 550 | + 6 => r.read_bits(8)? as usize + 1, | ||
| 551 | + 7 => r.read_bits(16)? as usize + 1, | ||
| 552 | + _ => 256 << (block_size_code - 8), | ||
| 553 | + }; | ||
| 554 | + let sample_rate = match sample_rate_code { | ||
| 555 | + 0 => info | ||
| 556 | + .map(|i| i.sample_rate) | ||
| 557 | + .ok_or_else(|| Error::corrupt("frame header: rate from a missing STREAMINFO"))?, | ||
| 558 | + 1 => 88200, | ||
| 559 | + 2 => 176_400, | ||
| 560 | + 3 => 192_000, | ||
| 561 | + 4 => 8000, | ||
| 562 | + 5 => 16000, | ||
| 563 | + 6 => 22050, | ||
| 564 | + 7 => 24000, | ||
| 565 | + 8 => 32000, | ||
| 566 | + 9 => 44100, | ||
| 567 | + 10 => 48000, | ||
| 568 | + 11 => 96000, | ||
| 569 | + 12 => r.read_bits(8)? * 1000, | ||
| 570 | + 13 => r.read_bits(16)?, | ||
| 571 | + 14 => r.read_bits(16)? * 10, | ||
| 572 | + _ => return Err(Error::corrupt("frame header: sample rate code 15")), | ||
| 573 | + }; | ||
| 574 | + let channels = match channel_code { | ||
| 575 | + 0..=7 => ChannelAssignment::Independent(channel_code as u8 + 1), | ||
| 576 | + 8 => ChannelAssignment::LeftSide, | ||
| 577 | + 9 => ChannelAssignment::RightSide, | ||
| 578 | + 10 => ChannelAssignment::MidSide, | ||
| 579 | + _ => { | ||
| 580 | + return Err(Error::corrupt(format!( | ||
| 581 | + "frame header: channel assignment {channel_code}" | ||
| 582 | + ))); | ||
| 583 | + } | ||
| 584 | + }; | ||
| 585 | + let bits_per_sample = match bps_code { | ||
| 586 | + 0 => info | ||
| 587 | + .map(|i| u32::from(i.bits_per_sample)) | ||
| 588 | + .ok_or_else(|| Error::corrupt("frame header: depth from a missing STREAMINFO"))?, | ||
| 589 | + 1 => 8, | ||
| 590 | + 2 => 12, | ||
| 591 | + 3 => return Err(Error::corrupt("frame header: bit depth code 3 is reserved")), | ||
| 592 | + 4 => 16, | ||
| 593 | + 5 => 20, | ||
| 594 | + 6 => 24, | ||
| 595 | + _ => 32, | ||
| 596 | + }; | ||
| 597 | + // The CRC-8 byte closes the header; callers check it against the bytes they | ||
| 598 | + // hold, so it is only skipped here. | ||
| 599 | + r.skip_bits(8)?; | ||
| 600 | + Ok(FrameHeader { | ||
| 601 | + block_size, | ||
| 602 | + sample_rate, | ||
| 603 | + channels, | ||
| 604 | + bits_per_sample, | ||
| 605 | + number, | ||
| 606 | + variable_block_size, | ||
| 607 | + }) | ||
| 608 | +} | ||
| 609 | + | ||
| 610 | +/// The UTF-8-shaped coded number of a frame header (up to 36 bits, so wider | ||
| 611 | +/// than real UTF-8). | ||
| 612 | +pub(crate) fn read_utf8_number(r: &mut BitReader<'_>, max_bits: u32) -> Result<u64> { | ||
| 613 | + let first = r.read_bits(8)?; | ||
| 614 | + let extra = match first { | ||
| 615 | + 0x00..=0x7f => 0, | ||
| 616 | + 0xc0..=0xdf => 1, | ||
| 617 | + 0xe0..=0xef => 2, | ||
| 618 | + 0xf0..=0xf7 => 3, | ||
| 619 | + 0xf8..=0xfb => 4, | ||
| 620 | + 0xfc..=0xfd => 5, | ||
| 621 | + 0xfe => 6, | ||
| 622 | + _ => return Err(Error::corrupt("frame header: bad coded-number prefix")), | ||
| 623 | + }; | ||
| 624 | + // The lead byte carries `6 - extra` payload bits after its prefix. | ||
| 625 | + let mut value = match extra { | ||
| 626 | + 0 => u64::from(first), | ||
| 627 | + _ => u64::from(first & ((1u32 << (6 - extra)) - 1)), | ||
| 628 | + }; | ||
| 629 | + for _ in 0..extra { | ||
| 630 | + let byte = r.read_bits(8)?; | ||
| 631 | + if byte & 0xc0 != 0x80 { | ||
| 632 | + return Err(Error::corrupt( | ||
| 633 | + "frame header: bad coded-number continuation", | ||
| 634 | + )); | ||
| 635 | + } | ||
| 636 | + value = (value << 6) | u64::from(byte & 0x3f); | ||
| 637 | + } | ||
| 638 | + if max_bits < 64 && value >> max_bits != 0 { | ||
| 639 | + return Err(Error::corrupt(format!( | ||
| 640 | + "frame header: coded number {value} exceeds {max_bits} bits" | ||
| 641 | + ))); | ||
| 642 | + } | ||
| 643 | + Ok(value) | ||
| 644 | +} | ||
| 645 | + | ||
| 646 | +fn decode_subframe( | ||
| 647 | + r: &mut BitReader<'_>, | ||
| 648 | + bps: u32, | ||
| 649 | + block_size: usize, | ||
| 650 | + out: &mut Vec<i32>, | ||
| 651 | + residual: &mut Vec<i32>, | ||
| 652 | +) -> Result<()> { | ||
| 653 | + if r.read_bit()? { | ||
| 654 | + return Err(Error::corrupt("subframe: padding bit set")); | ||
| 655 | + } | ||
| 656 | + let kind = r.read_bits(6)?; | ||
| 657 | + let mut wasted = 0u32; | ||
| 658 | + if r.read_bit()? { | ||
| 659 | + wasted = 1; | ||
| 660 | + while !r.read_bit()? { | ||
| 661 | + wasted += 1; | ||
| 662 | + if wasted >= bps { | ||
| 663 | + break; | ||
| 664 | + } | ||
| 665 | + } | ||
| 666 | + } | ||
| 667 | + if wasted >= bps { | ||
| 668 | + return Err(Error::corrupt(format!( | ||
| 669 | + "subframe: {wasted} wasted bits of {bps}" | ||
| 670 | + ))); | ||
| 671 | + } | ||
| 672 | + let bps = bps - wasted; | ||
| 673 | + if bps > 32 { | ||
| 674 | + // Only a 32-bit stream that also decorrelates its stereo pair gets | ||
| 675 | + // here: its side channel needs 33 bits, which does not fit the i32 | ||
| 676 | + // sample planes this decoder (and ffmpeg's, and libFLAC's encoder) | ||
| 677 | + // works in. Named rather than mangled. | ||
| 678 | + return Err(Error::unsupported( | ||
| 679 | + "33-bit side subframe", | ||
| 680 | + "32-bit stereo decorrelation needs 33-bit sample planes", | ||
| 681 | + )); | ||
| 682 | + } | ||
| 683 | + | ||
| 684 | + out.clear(); | ||
| 685 | + out.reserve(block_size); | ||
| 686 | + match kind { | ||
| 687 | + 0 => { | ||
| 688 | + let value = r.read_signed(bps)?; | ||
| 689 | + out.resize(block_size, value); | ||
| 690 | + } | ||
| 691 | + 1 => { | ||
| 692 | + for _ in 0..block_size { | ||
| 693 | + out.push(r.read_signed(bps)?); | ||
| 694 | + } | ||
| 695 | + } | ||
| 696 | + 8..=12 => decode_fixed(r, (kind - 8) as usize, bps, block_size, out, residual)?, | ||
| 697 | + 32..=63 => decode_lpc(r, (kind - 31) as usize, bps, block_size, out, residual)?, | ||
| 698 | + _ => { | ||
| 699 | + return Err(Error::corrupt(format!("subframe: type {kind} is reserved"))); | ||
| 700 | + } | ||
| 701 | + } | ||
| 702 | + if wasted > 0 { | ||
| 703 | + for s in out.iter_mut() { | ||
| 704 | + *s <<= wasted; | ||
| 705 | + } | ||
| 706 | + } | ||
| 707 | + Ok(()) | ||
| 708 | +} | ||
| 709 | + | ||
| 710 | +fn decode_fixed( | ||
| 711 | + r: &mut BitReader<'_>, | ||
| 712 | + order: usize, | ||
| 713 | + bps: u32, | ||
| 714 | + block_size: usize, | ||
| 715 | + out: &mut Vec<i32>, | ||
| 716 | + residual: &mut Vec<i32>, | ||
| 717 | +) -> Result<()> { | ||
| 718 | + if order > block_size { | ||
| 719 | + return Err(Error::corrupt(format!( | ||
| 720 | + "fixed subframe: order {order} over a {block_size}-sample block" | ||
| 721 | + ))); | ||
| 722 | + } | ||
| 723 | + for _ in 0..order { | ||
| 724 | + out.push(r.read_signed(bps)?); | ||
| 725 | + } | ||
| 726 | + decode_residual(r, block_size, order, residual)?; | ||
| 727 | + for (i, &res) in residual.iter().enumerate() { | ||
| 728 | + let n = order + i; | ||
| 729 | + let p = &out[n - order..n]; | ||
| 730 | + // Fixed predictors are the first four differences of the signal. | ||
| 731 | + let predicted: i64 = match order { | ||
| 732 | + 0 => 0, | ||
| 733 | + 1 => i64::from(p[0]), | ||
| 734 | + 2 => 2 * i64::from(p[1]) - i64::from(p[0]), | ||
| 735 | + 3 => 3 * i64::from(p[2]) - 3 * i64::from(p[1]) + i64::from(p[0]), | ||
| 736 | + _ => 4 * i64::from(p[3]) - 6 * i64::from(p[2]) + 4 * i64::from(p[1]) - i64::from(p[0]), | ||
| 737 | + }; | ||
| 738 | + out.push((predicted as i32).wrapping_add(res)); | ||
| 739 | + } | ||
| 740 | + Ok(()) | ||
| 741 | +} | ||
| 742 | + | ||
| 743 | +fn decode_lpc( | ||
| 744 | + r: &mut BitReader<'_>, | ||
| 745 | + order: usize, | ||
| 746 | + bps: u32, | ||
| 747 | + block_size: usize, | ||
| 748 | + out: &mut Vec<i32>, | ||
| 749 | + residual: &mut Vec<i32>, | ||
| 750 | +) -> Result<()> { | ||
| 751 | + if order > block_size { | ||
| 752 | + return Err(Error::corrupt(format!( | ||
| 753 | + "LPC subframe: order {order} over a {block_size}-sample block" | ||
| 754 | + ))); | ||
| 755 | + } | ||
| 756 | + for _ in 0..order { | ||
| 757 | + out.push(r.read_signed(bps)?); | ||
| 758 | + } | ||
| 759 | + let precision = r.read_bits(4)? + 1; | ||
| 760 | + if precision == 16 { | ||
| 761 | + return Err(Error::corrupt("LPC subframe: coefficient precision 15+1")); | ||
| 762 | + } | ||
| 763 | + let shift = r.read_signed(5)?; | ||
| 764 | + if shift < 0 { | ||
| 765 | + return Err(Error::corrupt(format!( | ||
| 766 | + "LPC subframe: negative shift {shift}" | ||
| 767 | + ))); | ||
| 768 | + } | ||
| 769 | + let mut coefs = [0i64; 32]; | ||
| 770 | + for c in coefs.iter_mut().take(order) { | ||
| 771 | + *c = i64::from(r.read_signed(precision)?); | ||
| 772 | + } | ||
| 773 | + decode_residual(r, block_size, order, residual)?; | ||
| 774 | + let coefs = &coefs[..order]; | ||
| 775 | + for (i, &res) in residual.iter().enumerate() { | ||
| 776 | + let n = order + i; | ||
| 777 | + let history = &out[n - order..n]; | ||
| 778 | + // 64-bit accumulation: 32-bit samples with 15-bit coefficients at order | ||
| 779 | + // 32 need 52 bits, and the "predictor overflow" streams exist to catch | ||
| 780 | + // a decoder that accumulates narrower. | ||
| 781 | + let mut sum = 0i64; | ||
| 782 | + for (c, &s) in coefs.iter().zip(history.iter().rev()) { | ||
| 783 | + sum += c * i64::from(s); | ||
| 784 | + } | ||
| 785 | + out.push(((sum >> shift) as i32).wrapping_add(res)); | ||
| 786 | + } | ||
| 787 | + Ok(()) | ||
| 788 | +} | ||
| 789 | + | ||
| 790 | +fn decode_residual( | ||
| 791 | + r: &mut BitReader<'_>, | ||
| 792 | + block_size: usize, | ||
| 793 | + order: usize, | ||
| 794 | + out: &mut Vec<i32>, | ||
| 795 | +) -> Result<()> { | ||
| 796 | + let method = r.read_bits(2)?; | ||
| 797 | + let param_bits = match method { | ||
| 798 | + 0 => 4, | ||
| 799 | + 1 => 5, | ||
| 800 | + _ => { | ||
| 801 | + return Err(Error::corrupt(format!( | ||
| 802 | + "residual: coding method {method} is reserved" | ||
| 803 | + ))); | ||
| 804 | + } | ||
| 805 | + }; | ||
| 806 | + let escape = (1u32 << param_bits) - 1; | ||
| 807 | + let partition_order = r.read_bits(4)?; | ||
| 808 | + let partitions = 1usize << partition_order; | ||
| 809 | + if !block_size.is_multiple_of(partitions) { | ||
| 810 | + return Err(Error::corrupt(format!( | ||
| 811 | + "residual: {partitions} partitions over a {block_size}-sample block" | ||
| 812 | + ))); | ||
| 813 | + } | ||
| 814 | + let partition_len = block_size / partitions; | ||
| 815 | + if partition_len < order { | ||
| 816 | + return Err(Error::corrupt(format!( | ||
| 817 | + "residual: order {order} over {partition_len}-sample partitions" | ||
| 818 | + ))); | ||
| 819 | + } | ||
| 820 | + out.clear(); | ||
| 821 | + out.reserve(block_size - order); | ||
| 822 | + for p in 0..partitions { | ||
| 823 | + let count = partition_len - if p == 0 { order } else { 0 }; | ||
| 824 | + let param = r.read_bits(param_bits)?; | ||
| 825 | + if param == escape { | ||
| 826 | + let raw = r.read_bits(5)?; | ||
| 827 | + for _ in 0..count { | ||
| 828 | + out.push(match raw { | ||
| 829 | + 0 => 0, | ||
| 830 | + n => r.read_signed(n)?, | ||
| 831 | + }); | ||
| 832 | + } | ||
| 833 | + } else { | ||
| 834 | + for _ in 0..count { | ||
| 835 | + out.push(read_rice(r, param)?); | ||
| 836 | + } | ||
| 837 | + } | ||
| 838 | + } | ||
| 839 | + Ok(()) | ||
| 840 | +} | ||
| 841 | + | ||
| 842 | +/// One Rice-coded, zig-zag folded residual. | ||
| 843 | +fn read_rice(r: &mut BitReader<'_>, param: u32) -> Result<i32> { | ||
| 844 | + let mut quotient = 0u32; | ||
| 845 | + while !r.read_bit()? { | ||
| 846 | + quotient += 1; | ||
| 847 | + // A quotient wider than the sample container is damage, not data; the | ||
| 848 | + // cap is what keeps a fuzzed stream from spinning to the end of the | ||
| 849 | + // buffer one bit at a time. | ||
| 850 | + if quotient > 1 << 20 { | ||
| 851 | + return Err(Error::corrupt("residual: Rice quotient over 2^20")); | ||
| 852 | + } | ||
| 853 | + } | ||
| 854 | + let folded = match param { | ||
| 855 | + 0 => quotient, | ||
| 856 | + n => (quotient << n) | r.read_bits(n)?, | ||
| 857 | + }; | ||
| 858 | + Ok(((folded >> 1) as i32) ^ -((folded & 1) as i32)) | ||
| 859 | +} | ||
| 860 | + | ||
| 861 | +fn undecorrelate(assignment: ChannelAssignment, channels: &mut [Vec<i32>]) -> Result<()> { | ||
| 862 | + if matches!(assignment, ChannelAssignment::Independent(_)) { | ||
| 863 | + return Ok(()); | ||
| 864 | + } | ||
| 865 | + let (a, b) = channels.split_at_mut(1); | ||
| 866 | + let (a, b) = (&mut a[0], &mut b[0]); | ||
| 867 | + if a.len() != b.len() { | ||
| 868 | + return Err(Error::corrupt("stereo decorrelation over unequal channels")); | ||
| 869 | + } | ||
| 870 | + match assignment { | ||
| 871 | + ChannelAssignment::LeftSide => { | ||
| 872 | + // a = left, b = left - right. | ||
| 873 | + for (l, s) in a.iter().zip(b.iter_mut()) { | ||
| 874 | + *s = l.wrapping_sub(*s); | ||
| 875 | + } | ||
| 876 | + } | ||
| 877 | + ChannelAssignment::RightSide => { | ||
| 878 | + // a = left - right, b = right. | ||
| 879 | + for (s, r) in a.iter_mut().zip(b.iter()) { | ||
| 880 | + *s = s.wrapping_add(*r); | ||
| 881 | + } | ||
| 882 | + } | ||
| 883 | + ChannelAssignment::MidSide => { | ||
| 884 | + for (m, s) in a.iter_mut().zip(b.iter_mut()) { | ||
| 885 | + // The low bit of the difference is carried in the mid channel. | ||
| 886 | + let mid = (*m << 1) | (*s & 1); | ||
| 887 | + let side = *s; | ||
| 888 | + *m = mid.wrapping_add(side) >> 1; | ||
| 889 | + *s = mid.wrapping_sub(side) >> 1; | ||
| 890 | + } | ||
| 891 | + } | ||
| 892 | + ChannelAssignment::Independent(_) => unreachable!("returned above"), | ||
| 893 | + } | ||
| 894 | + Ok(()) | ||
| 895 | +} | ||
| 896 | + | ||
| 897 | +#[cfg(test)] | ||
| 898 | +mod tests { | ||
| 899 | + use super::*; | ||
| 900 | + | ||
| 901 | + #[test] | ||
| 902 | + fn stream_info_round_trips() { | ||
| 903 | + let info = StreamInfo { | ||
| 904 | + min_block_size: 4096, | ||
| 905 | + max_block_size: 4096, | ||
| 906 | + min_frame_size: 14, | ||
| 907 | + max_frame_size: 16384, | ||
| 908 | + sample_rate: 44100, | ||
| 909 | + channels: 2, | ||
| 910 | + bits_per_sample: 16, | ||
| 911 | + total_samples: 1_234_567, | ||
| 912 | + md5: [7; 16], | ||
| 913 | + }; | ||
| 914 | + assert_eq!(StreamInfo::parse(&info.to_bytes()).unwrap(), info); | ||
| 915 | + } | ||
| 916 | + | ||
| 917 | + #[test] | ||
| 918 | + fn truncated_input_is_need_more_not_a_panic() { | ||
| 919 | + let info = StreamInfo { | ||
| 920 | + min_block_size: 16, | ||
| 921 | + max_block_size: 16, | ||
| 922 | + min_frame_size: 0, | ||
| 923 | + max_frame_size: 0, | ||
| 924 | + sample_rate: 8000, | ||
| 925 | + channels: 1, | ||
| 926 | + bits_per_sample: 8, | ||
| 927 | + total_samples: 0, | ||
| 928 | + md5: [0; 16], | ||
| 929 | + }; | ||
| 930 | + let bytes = info.to_bytes(); | ||
| 931 | + for n in 0..34 { | ||
| 932 | + assert!(StreamInfo::parse(&bytes[..n]).unwrap_err().is_need_more()); | ||
| 933 | + } | ||
| 934 | + } | ||
| 935 | + | ||
| 936 | + #[test] | ||
| 937 | + fn garbage_never_panics_and_never_opens() { | ||
| 938 | + for seed in 0..64u32 { | ||
| 939 | + let junk: Vec<u8> = (0..512).map(|i| (i * 37 + seed * 11) as u8).collect(); | ||
| 940 | + let _ = FlacReader::new(&junk).map(|mut r| { | ||
| 941 | + let mut b = Block::default(); | ||
| 942 | + let _ = r.next_block(&mut b); | ||
| 943 | + }); | ||
| 944 | + } | ||
| 945 | + } | ||
| 946 | + | ||
| 947 | + #[test] | ||
| 948 | + fn mid_side_inverts_the_encoder_transform() { | ||
| 949 | + let left: Vec<i32> = (-8..8).collect(); | ||
| 950 | + let right: Vec<i32> = (0..16).map(|i| i * 3 - 20).collect(); | ||
| 951 | + let mid: Vec<i32> = left.iter().zip(&right).map(|(l, r)| (l + r) >> 1).collect(); | ||
| 952 | + let side: Vec<i32> = left.iter().zip(&right).map(|(l, r)| l - r).collect(); | ||
| 953 | + let mut planes = vec![mid, side]; | ||
| 954 | + undecorrelate(ChannelAssignment::MidSide, &mut planes).unwrap(); | ||
| 955 | + assert_eq!(planes[0], left); | ||
| 956 | + assert_eq!(planes[1], right); | ||
| 957 | + } | ||
| 958 | + | ||
| 959 | + #[test] | ||
| 960 | + fn container_shift_matches_ffmpeg_layout() { | ||
| 961 | + assert_eq!(container_shift(8), 8); | ||
| 962 | + assert_eq!(container_shift(12), 4); | ||
| 963 | + assert_eq!(container_shift(16), 0); | ||
| 964 | + assert_eq!(container_shift(20), 12); | ||
| 965 | + assert_eq!(container_shift(24), 8); | ||
| 966 | + assert_eq!(container_shift(32), 0); | ||
| 967 | + } | ||
| 968 | +} | ||
crates/ec-flac/src/encode.rsadded+966 -0
| @@ -0,0 +1,966 @@ | |||
| 1 | +//! FLAC encoding: fixed-block-size streams with constant, fixed, LPC and | ||
| 2 | +//! verbatim subframes, a Rice partition search per residual and a per-block | ||
| 3 | +//! stereo decorrelation decision. | ||
| 4 | +//! | ||
| 5 | +//! The output is a complete `.flac` file: `fLaC`, one `STREAMINFO` (carrying | ||
| 6 | +//! the MD5 of the input, so any decoder can check us), then the frames. | ||
| 7 | + | ||
| 8 | +use ec_core::bitio::BitWriter; | ||
| 9 | +use ec_core::error::{Error, Result}; | ||
| 10 | + | ||
| 11 | +use crate::checksum::{crc8, crc16, md5_of_samples}; | ||
| 12 | +use crate::decode::StreamInfo; | ||
| 13 | + | ||
| 14 | +/// Encoder settings. [`EncoderConfig::default`] is the level the family ships: | ||
| 15 | +/// 4096-sample blocks, LPC to order 12, Rice partitions to order 6. | ||
| 16 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 17 | +pub struct EncoderConfig { | ||
| 18 | + /// Inter-channel samples per frame. | ||
| 19 | + pub block_size: usize, | ||
| 20 | + /// Highest LPC order tried; 0 disables LPC and leaves the fixed predictors. | ||
| 21 | + pub max_lpc_order: usize, | ||
| 22 | + /// Bits each quantised LPC coefficient is stored in (5..=15). | ||
| 23 | + pub qlp_precision: u32, | ||
| 24 | + /// Highest Rice partition order tried. | ||
| 25 | + pub max_partition_order: u32, | ||
| 26 | + /// Try left/side, right/side and mid/side on stereo input. | ||
| 27 | + pub stereo_decorrelation: bool, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +impl Default for EncoderConfig { | ||
| 31 | + fn default() -> Self { | ||
| 32 | + EncoderConfig { | ||
| 33 | + block_size: 4096, | ||
| 34 | + max_lpc_order: 12, | ||
| 35 | + qlp_precision: 15, | ||
| 36 | + max_partition_order: 6, | ||
| 37 | + stereo_decorrelation: true, | ||
| 38 | + } | ||
| 39 | + } | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +impl EncoderConfig { | ||
| 43 | + /// Refuse settings that cannot produce a legal stream. | ||
| 44 | + pub fn verify(&self) -> Result<()> { | ||
| 45 | + if !(16..=65535).contains(&self.block_size) { | ||
| 46 | + return Err(Error::unsupported( | ||
| 47 | + format!("block size {}", self.block_size), | ||
| 48 | + "RFC 9639 allows 16..=65535", | ||
| 49 | + )); | ||
| 50 | + } | ||
| 51 | + if self.max_lpc_order > 32 { | ||
| 52 | + return Err(Error::unsupported( | ||
| 53 | + format!("LPC order {}", self.max_lpc_order), | ||
| 54 | + "RFC 9639 allows up to 32", | ||
| 55 | + )); | ||
| 56 | + } | ||
| 57 | + if !(5..=15).contains(&self.qlp_precision) { | ||
| 58 | + return Err(Error::unsupported( | ||
| 59 | + format!("coefficient precision {}", self.qlp_precision), | ||
| 60 | + "RFC 9639 allows 1..=15; below 5 is never useful", | ||
| 61 | + )); | ||
| 62 | + } | ||
| 63 | + if self.max_partition_order > 15 { | ||
| 64 | + return Err(Error::unsupported( | ||
| 65 | + format!("partition order {}", self.max_partition_order), | ||
| 66 | + "RFC 9639 allows up to 15", | ||
| 67 | + )); | ||
| 68 | + } | ||
| 69 | + Ok(()) | ||
| 70 | + } | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Encode interleaved samples into a complete FLAC stream. | ||
| 74 | +/// | ||
| 75 | +/// `samples` are interleaved by channel and must already fit in | ||
| 76 | +/// `bits_per_sample`: a sample outside that range is [`Error::Corrupt`], | ||
| 77 | +/// because silently clipping the caller's audio would make a lossless codec | ||
| 78 | +/// lossy. | ||
| 79 | +pub fn encode( | ||
| 80 | + config: &EncoderConfig, | ||
| 81 | + samples: &[i32], | ||
| 82 | + channels: usize, | ||
| 83 | + bits_per_sample: u32, | ||
| 84 | + sample_rate: u32, | ||
| 85 | +) -> Result<Vec<u8>> { | ||
| 86 | + config.verify()?; | ||
| 87 | + if !(1..=8).contains(&channels) { | ||
| 88 | + return Err(Error::unsupported( | ||
| 89 | + format!("{channels} channels"), | ||
| 90 | + "FLAC codes 1..=8 channels", | ||
| 91 | + )); | ||
| 92 | + } | ||
| 93 | + if !(4..=32).contains(&bits_per_sample) { | ||
| 94 | + return Err(Error::unsupported( | ||
| 95 | + format!("{bits_per_sample} bits per sample"), | ||
| 96 | + "FLAC codes 4..=32 bits", | ||
| 97 | + )); | ||
| 98 | + } | ||
| 99 | + if sample_rate == 0 || sample_rate > 655_350 { | ||
| 100 | + return Err(Error::unsupported( | ||
| 101 | + format!("{sample_rate} Hz"), | ||
| 102 | + "FLAC codes 1..=655350 Hz", | ||
| 103 | + )); | ||
| 104 | + } | ||
| 105 | + if !samples.len().is_multiple_of(channels) { | ||
| 106 | + return Err(Error::corrupt(format!( | ||
| 107 | + "{} samples do not divide into {channels} channels", | ||
| 108 | + samples.len() | ||
| 109 | + ))); | ||
| 110 | + } | ||
| 111 | + let (low, high) = match bits_per_sample { | ||
| 112 | + 32 => (i32::MIN, i32::MAX), | ||
| 113 | + n => (-(1i32 << (n - 1)), (1i32 << (n - 1)) - 1), | ||
| 114 | + }; | ||
| 115 | + if let Some(bad) = samples.iter().find(|&&s| s < low || s > high) { | ||
| 116 | + return Err(Error::corrupt(format!( | ||
| 117 | + "sample {bad} does not fit in {bits_per_sample} bits" | ||
| 118 | + ))); | ||
| 119 | + } | ||
| 120 | + | ||
| 121 | + let frames = samples.len() / channels; | ||
| 122 | + let mut info = StreamInfo { | ||
| 123 | + min_block_size: config.block_size as u16, | ||
| 124 | + max_block_size: config.block_size as u16, | ||
| 125 | + min_frame_size: 0, | ||
| 126 | + max_frame_size: 0, | ||
| 127 | + sample_rate, | ||
| 128 | + channels: channels as u8, | ||
| 129 | + bits_per_sample: bits_per_sample as u8, | ||
| 130 | + total_samples: frames as u64, | ||
| 131 | + md5: md5_of_samples(samples, bits_per_sample), | ||
| 132 | + }; | ||
| 133 | + | ||
| 134 | + let mut out = Vec::with_capacity(samples.len() * bits_per_sample as usize / 8); | ||
| 135 | + out.extend_from_slice(&crate::decode::MAGIC); | ||
| 136 | + out.push(0x80); // last metadata block, type 0 (STREAMINFO) | ||
| 137 | + out.extend_from_slice(&[0, 0, 34]); | ||
| 138 | + let streaminfo_at = out.len(); | ||
| 139 | + out.extend_from_slice(&info.to_bytes()); | ||
| 140 | + | ||
| 141 | + let mut planes: Vec<Vec<i32>> = (0..channels) | ||
| 142 | + .map(|_| Vec::with_capacity(config.block_size)) | ||
| 143 | + .collect(); | ||
| 144 | + let mut scratch = Scratch::default(); | ||
| 145 | + let mut min_frame = u32::MAX; | ||
| 146 | + let mut max_frame = 0u32; | ||
| 147 | + for (number, block) in samples.chunks(config.block_size * channels).enumerate() { | ||
| 148 | + let block_size = block.len() / channels; | ||
| 149 | + for (c, plane) in planes.iter_mut().enumerate() { | ||
| 150 | + plane.clear(); | ||
| 151 | + plane.extend(block.iter().skip(c).step_by(channels).copied()); | ||
| 152 | + } | ||
| 153 | + let frame = encode_frame( | ||
| 154 | + config, | ||
| 155 | + &planes, | ||
| 156 | + block_size, | ||
| 157 | + bits_per_sample, | ||
| 158 | + sample_rate, | ||
| 159 | + number as u64, | ||
| 160 | + &mut scratch, | ||
| 161 | + ); | ||
| 162 | + min_frame = min_frame.min(frame.len() as u32); | ||
| 163 | + max_frame = max_frame.max(frame.len() as u32); | ||
| 164 | + out.extend_from_slice(&frame); | ||
| 165 | + } | ||
| 166 | + if frames > 0 { | ||
| 167 | + info.min_frame_size = min_frame; | ||
| 168 | + info.max_frame_size = max_frame; | ||
| 169 | + out[streaminfo_at..streaminfo_at + 34].copy_from_slice(&info.to_bytes()); | ||
| 170 | + } | ||
| 171 | + Ok(out) | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +/// Buffers reused across blocks: the two stereo candidates and the analysis | ||
| 175 | +/// window, which depends only on the block size and so is built once. | ||
| 176 | +#[derive(Debug, Default)] | ||
| 177 | +struct Scratch { | ||
| 178 | + mid: Vec<i32>, | ||
| 179 | + side: Vec<i32>, | ||
| 180 | + window: Vec<f64>, | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +impl Scratch { | ||
| 184 | + fn ensure_window(&mut self, n: usize) { | ||
| 185 | + if self.window.len() != n { | ||
| 186 | + self.window = tukey_window(n); | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +#[allow(clippy::too_many_arguments)] | ||
| 192 | +fn encode_frame( | ||
| 193 | + config: &EncoderConfig, | ||
| 194 | + planes: &[Vec<i32>], | ||
| 195 | + block_size: usize, | ||
| 196 | + bits_per_sample: u32, | ||
| 197 | + sample_rate: u32, | ||
| 198 | + number: u64, | ||
| 199 | + scratch: &mut Scratch, | ||
| 200 | +) -> Vec<u8> { | ||
| 201 | + let channels = planes.len(); | ||
| 202 | + // Channel assignment: 0..7 = that many independent channels, 8 = left/side, | ||
| 203 | + // 9 = right/side, 10 = mid/side. Each candidate signal is planned once and | ||
| 204 | + // the cheapest pairing wins — planning carries all the search cost, writing | ||
| 205 | + // carries none. | ||
| 206 | + let stereo = channels == 2 && config.stereo_decorrelation && bits_per_sample < 32; | ||
| 207 | + if stereo { | ||
| 208 | + scratch.mid.clear(); | ||
| 209 | + scratch.side.clear(); | ||
| 210 | + for (&l, &r) in planes[0].iter().zip(&planes[1]) { | ||
| 211 | + // i64 first: `l - r` of two full-depth samples does not fit in i32. | ||
| 212 | + scratch | ||
| 213 | + .mid | ||
| 214 | + .push(((i64::from(l) + i64::from(r)) >> 1) as i32); | ||
| 215 | + scratch.side.push((i64::from(l) - i64::from(r)) as i32); | ||
| 216 | + } | ||
| 217 | + } | ||
| 218 | + scratch.ensure_window(block_size); | ||
| 219 | + let window = &scratch.window; | ||
| 220 | + | ||
| 221 | + let mut plans: Vec<SubframePlan> = planes | ||
| 222 | + .iter() | ||
| 223 | + .map(|plane| plan_subframe(config, plane, bits_per_sample, window)) | ||
| 224 | + .collect(); | ||
| 225 | + let mut assignment = channels as u32 - 1; | ||
| 226 | + if stereo { | ||
| 227 | + let mid = plan_subframe(config, &scratch.mid, bits_per_sample, window); | ||
| 228 | + // The side channel needs one bit more than the stream's depth, which is | ||
| 229 | + // why a 32-bit stream cannot be decorrelated at all. | ||
| 230 | + let side = plan_subframe(config, &scratch.side, bits_per_sample + 1, window); | ||
| 231 | + let (l, r) = (plans[0].bits, plans[1].bits); | ||
| 232 | + let (_, best) = [ | ||
| 233 | + (l + r, 1u32), | ||
| 234 | + (l + side.bits, 8), | ||
| 235 | + (side.bits + r, 9), | ||
| 236 | + (mid.bits + side.bits, 10), | ||
| 237 | + ] | ||
| 238 | + .into_iter() | ||
| 239 | + .min() | ||
| 240 | + .expect("four candidates"); | ||
| 241 | + assignment = best; | ||
| 242 | + match best { | ||
| 243 | + 8 => plans[1] = side, | ||
| 244 | + 9 => plans[0] = side, | ||
| 245 | + 10 => { | ||
| 246 | + plans[0] = mid; | ||
| 247 | + plans[1] = side; | ||
| 248 | + } | ||
| 249 | + _ => {} | ||
| 250 | + } | ||
| 251 | + } | ||
| 252 | + | ||
| 253 | + let mut w = BitWriter::with_capacity(block_size * channels * 2); | ||
| 254 | + write_frame_header( | ||
| 255 | + &mut w, | ||
| 256 | + block_size, | ||
| 257 | + sample_rate, | ||
| 258 | + assignment, | ||
| 259 | + bits_per_sample, | ||
| 260 | + number, | ||
| 261 | + ); | ||
| 262 | + debug_assert!(w.is_byte_aligned()); | ||
| 263 | + let crc = crc8(w.as_bytes()); | ||
| 264 | + w.write_bits(u32::from(crc), 8); | ||
| 265 | + for (c, plan) in plans.iter().enumerate() { | ||
| 266 | + let side = matches!((assignment, c), (8, 1) | (10, 1) | (9, 0)); | ||
| 267 | + write_subframe(&mut w, plan, bits_per_sample + u32::from(side)); | ||
| 268 | + } | ||
| 269 | + w.align_to_byte(); | ||
| 270 | + let crc = crc16(w.as_bytes()); | ||
| 271 | + w.write_bits(u32::from(crc), 16); | ||
| 272 | + w.into_bytes() | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +fn write_frame_header( | ||
| 276 | + w: &mut BitWriter, | ||
| 277 | + block_size: usize, | ||
| 278 | + sample_rate: u32, | ||
| 279 | + assignment: u32, | ||
| 280 | + bits_per_sample: u32, | ||
| 281 | + number: u64, | ||
| 282 | +) { | ||
| 283 | + let (bs_code, bs_extra) = match block_size { | ||
| 284 | + 192 => (1, None), | ||
| 285 | + 576 => (2, None), | ||
| 286 | + 1152 => (3, None), | ||
| 287 | + 2304 => (4, None), | ||
| 288 | + 4608 => (5, None), | ||
| 289 | + 256 => (8, None), | ||
| 290 | + 512 => (9, None), | ||
| 291 | + 1024 => (10, None), | ||
| 292 | + 2048 => (11, None), | ||
| 293 | + 4096 => (12, None), | ||
| 294 | + 8192 => (13, None), | ||
| 295 | + 16384 => (14, None), | ||
| 296 | + 32768 => (15, None), | ||
| 297 | + n if n <= 256 => (6, Some((n as u32 - 1, 8))), | ||
| 298 | + n => (7, Some((n as u32 - 1, 16))), | ||
| 299 | + }; | ||
| 300 | + let (sr_code, sr_extra) = match sample_rate { | ||
| 301 | + 88200 => (1, None), | ||
| 302 | + 176_400 => (2, None), | ||
| 303 | + 192_000 => (3, None), | ||
| 304 | + 8000 => (4, None), | ||
| 305 | + 16000 => (5, None), | ||
| 306 | + 22050 => (6, None), | ||
| 307 | + 24000 => (7, None), | ||
| 308 | + 32000 => (8, None), | ||
| 309 | + 44100 => (9, None), | ||
| 310 | + 48000 => (10, None), | ||
| 311 | + 96000 => (11, None), | ||
| 312 | + n if n.is_multiple_of(1000) && n / 1000 <= 255 => (12, Some((n / 1000, 8))), | ||
| 313 | + n if n <= 65535 => (13, Some((n, 16))), | ||
| 314 | + n if n.is_multiple_of(10) && n / 10 <= 65535 => (14, Some((n / 10, 16))), | ||
| 315 | + // Every rate `encode` accepts is covered above; code 0 (take the rate | ||
| 316 | + // from STREAMINFO) is the honest fallback rather than a panic. | ||
| 317 | + _ => (0, None), | ||
| 318 | + }; | ||
| 319 | + let bps_code = match bits_per_sample { | ||
| 320 | + 8 => 1, | ||
| 321 | + 12 => 2, | ||
| 322 | + 16 => 4, | ||
| 323 | + 20 => 5, | ||
| 324 | + 24 => 6, | ||
| 325 | + 32 => 7, | ||
| 326 | + _ => 0, | ||
| 327 | + }; | ||
| 328 | + w.write_bits(0x3ffe, 14); | ||
| 329 | + w.write_bit(false); // reserved | ||
| 330 | + w.write_bit(false); // fixed block size: the coded number is a frame number | ||
| 331 | + w.write_bits(bs_code, 4); | ||
| 332 | + w.write_bits(sr_code, 4); | ||
| 333 | + w.write_bits(assignment, 4); | ||
| 334 | + w.write_bits(bps_code, 3); | ||
| 335 | + w.write_bit(false); // reserved | ||
| 336 | + write_utf8_number(w, number); | ||
| 337 | + if let Some((value, bits)) = bs_extra { | ||
| 338 | + w.write_bits(value, bits); | ||
| 339 | + } | ||
| 340 | + if let Some((value, bits)) = sr_extra { | ||
| 341 | + w.write_bits(value, bits); | ||
| 342 | + } | ||
| 343 | +} | ||
| 344 | + | ||
| 345 | +/// The UTF-8-shaped coded number of a frame header (up to 36 bits, so wider | ||
| 346 | +/// than real UTF-8 ever goes). | ||
| 347 | +fn write_utf8_number(w: &mut BitWriter, value: u64) { | ||
| 348 | + if value < 0x80 { | ||
| 349 | + w.write_bits(value as u32, 8); | ||
| 350 | + return; | ||
| 351 | + } | ||
| 352 | + // `extra` continuation bytes carry 6 bits each; the lead byte carries | ||
| 353 | + // `6 - extra` after its prefix of `extra + 1` ones and a zero. | ||
| 354 | + let mut extra = 1usize; | ||
| 355 | + while extra < 6 && value >= 1u64 << (6 * extra + (6 - extra)) { | ||
| 356 | + extra += 1; | ||
| 357 | + } | ||
| 358 | + let lead_bits = 6 - extra as u32; | ||
| 359 | + let prefix = (0xffu32 << (7 - extra)) & 0xff; | ||
| 360 | + let lead = prefix | ((value >> (6 * extra)) as u32 & ((1 << lead_bits) - 1)); | ||
| 361 | + w.write_bits(lead, 8); | ||
| 362 | + for i in (0..extra).rev() { | ||
| 363 | + w.write_bits(0x80 | ((value >> (6 * i)) as u32 & 0x3f), 8); | ||
| 364 | + } | ||
| 365 | +} | ||
| 366 | + | ||
| 367 | +/// What a subframe will be written as, with its exact cost in bits. | ||
| 368 | +#[derive(Debug, Clone)] | ||
| 369 | +struct SubframePlan { | ||
| 370 | + bits: usize, | ||
| 371 | + wasted: u32, | ||
| 372 | + kind: PlanKind, | ||
| 373 | +} | ||
| 374 | + | ||
| 375 | +#[derive(Debug, Clone)] | ||
| 376 | +enum PlanKind { | ||
| 377 | + Constant(i32), | ||
| 378 | + Verbatim(Vec<i32>), | ||
| 379 | + Fixed { | ||
| 380 | + warmup: Vec<i32>, | ||
| 381 | + residual: Vec<i32>, | ||
| 382 | + rice: RicePlan, | ||
| 383 | + }, | ||
| 384 | + Lpc { | ||
| 385 | + warmup: Vec<i32>, | ||
| 386 | + precision: u32, | ||
| 387 | + shift: u32, | ||
| 388 | + coefs: Vec<i32>, | ||
| 389 | + residual: Vec<i32>, | ||
| 390 | + rice: RicePlan, | ||
| 391 | + }, | ||
| 392 | +} | ||
| 393 | + | ||
| 394 | +#[derive(Debug, Clone, Default)] | ||
| 395 | +struct RicePlan { | ||
| 396 | + /// 4 or 5: the width of a partition's Rice parameter field. | ||
| 397 | + param_bits: u32, | ||
| 398 | + partition_order: u32, | ||
| 399 | + /// Predictor order, which is what makes partition 0 shorter than the rest. | ||
| 400 | + order: usize, | ||
| 401 | + params: Vec<u32>, | ||
| 402 | +} | ||
| 403 | + | ||
| 404 | +fn plan_subframe(config: &EncoderConfig, signal: &[i32], bps: u32, window: &[f64]) -> SubframePlan { | ||
| 405 | + // Wasted bits: when every sample shares trailing zeros, state them once in | ||
| 406 | + // the subframe header instead of once per sample. | ||
| 407 | + let any_set = signal.iter().fold(0u32, |acc, &s| acc | s as u32); | ||
| 408 | + let wasted = match any_set { | ||
| 409 | + 0 => 0, | ||
| 410 | + n => n.trailing_zeros().min(bps - 1), | ||
| 411 | + }; | ||
| 412 | + let shifted: Vec<i32>; | ||
| 413 | + let signal = match wasted { | ||
| 414 | + 0 => signal, | ||
| 415 | + n => { | ||
| 416 | + shifted = signal.iter().map(|&s| s >> n).collect(); | ||
| 417 | + &shifted | ||
| 418 | + } | ||
| 419 | + }; | ||
| 420 | + let bps = bps - wasted; | ||
| 421 | + let header_bits = 8 + wasted as usize; | ||
| 422 | + | ||
| 423 | + if signal.is_empty() { | ||
| 424 | + return SubframePlan { | ||
| 425 | + bits: header_bits + bps as usize, | ||
| 426 | + wasted, | ||
| 427 | + kind: PlanKind::Constant(0), | ||
| 428 | + }; | ||
| 429 | + } | ||
| 430 | + if signal.iter().all(|&s| s == signal[0]) { | ||
| 431 | + return SubframePlan { | ||
| 432 | + bits: header_bits + bps as usize, | ||
| 433 | + wasted, | ||
| 434 | + kind: PlanKind::Constant(signal[0]), | ||
| 435 | + }; | ||
| 436 | + } | ||
| 437 | + | ||
| 438 | + let mut best = SubframePlan { | ||
| 439 | + bits: header_bits + signal.len() * bps as usize, | ||
| 440 | + wasted, | ||
| 441 | + kind: PlanKind::Verbatim(signal.to_vec()), | ||
| 442 | + }; | ||
| 443 | + if let Some(plan) = plan_fixed(config, signal, bps, header_bits) | ||
| 444 | + && plan.bits < best.bits | ||
| 445 | + { | ||
| 446 | + best = SubframePlan { wasted, ..plan }; | ||
| 447 | + } | ||
| 448 | + if config.max_lpc_order > 0 | ||
| 449 | + && signal.len() > config.max_lpc_order | ||
| 450 | + && window.len() == signal.len() | ||
| 451 | + && let Some(plan) = plan_lpc(config, signal, bps, header_bits, window) | ||
| 452 | + && plan.bits < best.bits | ||
| 453 | + { | ||
| 454 | + best = SubframePlan { wasted, ..plan }; | ||
| 455 | + } | ||
| 456 | + best | ||
| 457 | +} | ||
| 458 | + | ||
| 459 | +/// The five fixed predictors, the order chosen by the sum of absolute | ||
| 460 | +/// residuals — the standard estimate; the Rice search then costs it exactly. | ||
| 461 | +fn plan_fixed( | ||
| 462 | + config: &EncoderConfig, | ||
| 463 | + signal: &[i32], | ||
| 464 | + bps: u32, | ||
| 465 | + header_bits: usize, | ||
| 466 | +) -> Option<SubframePlan> { | ||
| 467 | + let max_order = 4.min(signal.len().saturating_sub(1)); | ||
| 468 | + let mut diffs: Vec<Vec<i64>> = Vec::with_capacity(max_order + 1); | ||
| 469 | + diffs.push(signal.iter().map(|&s| i64::from(s)).collect()); | ||
| 470 | + for order in 1..=max_order { | ||
| 471 | + diffs.push(diffs[order - 1].windows(2).map(|w| w[1] - w[0]).collect()); | ||
| 472 | + } | ||
| 473 | + // Compare orders over the same samples, so the estimate is not biased by a | ||
| 474 | + // higher order simply covering fewer of them. | ||
| 475 | + let order = (0..=max_order).min_by_key(|&o| { | ||
| 476 | + let tail: u64 = diffs[o][max_order - o..] | ||
| 477 | + .iter() | ||
| 478 | + .map(|&d| d.unsigned_abs()) | ||
| 479 | + .sum(); | ||
| 480 | + tail + (o as u64) * u64::from(bps) | ||
| 481 | + })?; | ||
| 482 | + let residual: Vec<i32> = diffs[order] | ||
| 483 | + .iter() | ||
| 484 | + .map(|&d| i32::try_from(d)) | ||
| 485 | + .collect::<std::result::Result<_, _>>() | ||
| 486 | + .ok()?; // 32-bit input can overflow the residual; verbatim wins then. | ||
| 487 | + let rice = plan_rice(config, &residual, signal.len(), order); | ||
| 488 | + Some(SubframePlan { | ||
| 489 | + bits: header_bits + order * bps as usize + rice.bits, | ||
| 490 | + wasted: 0, | ||
| 491 | + kind: PlanKind::Fixed { | ||
| 492 | + warmup: signal[..order].to_vec(), | ||
| 493 | + residual, | ||
| 494 | + rice: rice.plan, | ||
| 495 | + }, | ||
| 496 | + }) | ||
| 497 | +} | ||
| 498 | + | ||
| 499 | +fn plan_lpc( | ||
| 500 | + config: &EncoderConfig, | ||
| 501 | + signal: &[i32], | ||
| 502 | + bps: u32, | ||
| 503 | + header_bits: usize, | ||
| 504 | + window: &[f64], | ||
| 505 | +) -> Option<SubframePlan> { | ||
| 506 | + let max_order = config.max_lpc_order.min(signal.len() - 1).min(32); | ||
| 507 | + if max_order == 0 { | ||
| 508 | + return None; | ||
| 509 | + } | ||
| 510 | + let windowed: Vec<f64> = window | ||
| 511 | + .iter() | ||
| 512 | + .zip(signal) | ||
| 513 | + .map(|(w, &s)| w * f64::from(s)) | ||
| 514 | + .collect(); | ||
| 515 | + let autoc = autocorrelation(&windowed, max_order); | ||
| 516 | + if autoc[0] == 0.0 { | ||
| 517 | + return None; | ||
| 518 | + } | ||
| 519 | + let (coefs_by_order, errors) = levinson_durbin(&autoc, max_order); | ||
| 520 | + | ||
| 521 | + // Order choice by the usual estimate: every order costs its coefficients | ||
| 522 | + // and saves half a bit per sample per halving of the prediction error. | ||
| 523 | + let n = signal.len() as f64; | ||
| 524 | + let cost = |o: usize| { | ||
| 525 | + n / 2.0 * errors[o].max(1e-9).log2() + (o as f64) * f64::from(config.qlp_precision) | ||
| 526 | + }; | ||
| 527 | + let order = (1..=max_order) | ||
| 528 | + .filter(|&o| !coefs_by_order[o].is_empty()) | ||
| 529 | + .min_by(|&a, &b| cost(a).total_cmp(&cost(b)))?; | ||
| 530 | + | ||
| 531 | + let (coefs, shift) = quantize_coefficients(&coefs_by_order[order], config.qlp_precision)?; | ||
| 532 | + let mut residual = Vec::with_capacity(signal.len() - order); | ||
| 533 | + for i in order..signal.len() { | ||
| 534 | + let mut sum = 0i64; | ||
| 535 | + for (k, &c) in coefs.iter().enumerate() { | ||
| 536 | + sum += i64::from(c) * i64::from(signal[i - 1 - k]); | ||
| 537 | + } | ||
| 538 | + let r = i64::from(signal[i]) - (sum >> shift); | ||
| 539 | + residual.push(i32::try_from(r).ok()?); | ||
| 540 | + } | ||
| 541 | + let rice = plan_rice(config, &residual, signal.len(), order); | ||
| 542 | + Some(SubframePlan { | ||
| 543 | + bits: header_bits | ||
| 544 | + + order * bps as usize | ||
| 545 | + + 4 | ||
| 546 | + + 5 | ||
| 547 | + + order * config.qlp_precision as usize | ||
| 548 | + + rice.bits, | ||
| 549 | + wasted: 0, | ||
| 550 | + kind: PlanKind::Lpc { | ||
| 551 | + warmup: signal[..order].to_vec(), | ||
| 552 | + precision: config.qlp_precision, | ||
| 553 | + shift, | ||
| 554 | + coefs, | ||
| 555 | + residual, | ||
| 556 | + rice: rice.plan, | ||
| 557 | + }, | ||
| 558 | + }) | ||
| 559 | +} | ||
| 560 | + | ||
| 561 | +struct RiceChoice { | ||
| 562 | + bits: usize, | ||
| 563 | + plan: RicePlan, | ||
| 564 | +} | ||
| 565 | + | ||
| 566 | +/// Choose the partition order and per-partition Rice parameters. | ||
| 567 | +/// | ||
| 568 | +/// Parameters come from partition sums with the usual estimate, then the whole | ||
| 569 | +/// configuration is costed exactly — so orders are compared by real bit counts | ||
| 570 | +/// rather than by two estimates. | ||
| 571 | +fn plan_rice( | ||
| 572 | + config: &EncoderConfig, | ||
| 573 | + residual: &[i32], | ||
| 574 | + block_size: usize, | ||
| 575 | + order: usize, | ||
| 576 | +) -> RiceChoice { | ||
| 577 | + let folded: Vec<u32> = residual.iter().map(|&r| fold(r)).collect(); | ||
| 578 | + let mut best: Option<RiceChoice> = None; | ||
| 579 | + for partition_order in 0..=config.max_partition_order { | ||
| 580 | + let partitions = 1usize << partition_order; | ||
| 581 | + if !block_size.is_multiple_of(partitions) { | ||
| 582 | + break; | ||
| 583 | + } | ||
| 584 | + let partition_len = block_size / partitions; | ||
| 585 | + if partition_len <= order { | ||
| 586 | + break; | ||
| 587 | + } | ||
| 588 | + let mut params = Vec::with_capacity(partitions); | ||
| 589 | + let mut bits = 0usize; | ||
| 590 | + let mut at = 0usize; | ||
| 591 | + let mut max_param = 0u32; | ||
| 592 | + for p in 0..partitions { | ||
| 593 | + let count = partition_len - if p == 0 { order } else { 0 }; | ||
| 594 | + let part = &folded[at..at + count]; | ||
| 595 | + at += count; | ||
| 596 | + let sum: u64 = part.iter().map(|&v| u64::from(v)).sum(); | ||
| 597 | + let param = best_rice_param(sum, count as u64); | ||
| 598 | + bits += part | ||
| 599 | + .iter() | ||
| 600 | + .map(|&v| (v >> param) as usize + 1 + param as usize) | ||
| 601 | + .sum::<usize>(); | ||
| 602 | + max_param = max_param.max(param); | ||
| 603 | + params.push(param); | ||
| 604 | + } | ||
| 605 | + let param_bits = if max_param > 14 { 5 } else { 4 }; | ||
| 606 | + bits += 2 + 4 + partitions * param_bits as usize; | ||
| 607 | + let choice = RiceChoice { | ||
| 608 | + bits, | ||
| 609 | + plan: RicePlan { | ||
| 610 | + param_bits, | ||
| 611 | + partition_order, | ||
| 612 | + order, | ||
| 613 | + params, | ||
| 614 | + }, | ||
| 615 | + }; | ||
| 616 | + if best.as_ref().is_none_or(|b| choice.bits < b.bits) { | ||
| 617 | + best = Some(choice); | ||
| 618 | + } | ||
| 619 | + } | ||
| 620 | + best.expect("partition order 0 is always legal") | ||
| 621 | +} | ||
| 622 | + | ||
| 623 | +/// Zig-zag fold: FLAC codes residuals as unsigned with the sign in bit 0. | ||
| 624 | +fn fold(r: i32) -> u32 { | ||
| 625 | + ((r << 1) ^ (r >> 31)) as u32 | ||
| 626 | +} | ||
| 627 | + | ||
| 628 | +/// The Rice parameter whose quotients cost least for a partition of `count` | ||
| 629 | +/// folded values summing to `sum`, capped at 30 (31 is the escape code). | ||
| 630 | +fn best_rice_param(sum: u64, count: u64) -> u32 { | ||
| 631 | + if count == 0 { | ||
| 632 | + return 0; | ||
| 633 | + } | ||
| 634 | + let mean = sum / count; | ||
| 635 | + let mut param = 0u32; | ||
| 636 | + while param < 30 && (1u64 << (param + 1)) <= mean { | ||
| 637 | + param += 1; | ||
| 638 | + } | ||
| 639 | + let cost = |k: u32| count * (1 + u64::from(k)) + (sum >> k); | ||
| 640 | + let mut best = param; | ||
| 641 | + for k in param.saturating_sub(1)..=(param + 1).min(30) { | ||
| 642 | + if cost(k) < cost(best) { | ||
| 643 | + best = k; | ||
| 644 | + } | ||
| 645 | + } | ||
| 646 | + best | ||
| 647 | +} | ||
| 648 | + | ||
| 649 | +fn write_subframe(w: &mut BitWriter, plan: &SubframePlan, bps: u32) { | ||
| 650 | + let kind_code = match &plan.kind { | ||
| 651 | + PlanKind::Constant(_) => 0, | ||
| 652 | + PlanKind::Verbatim(_) => 1, | ||
| 653 | + PlanKind::Fixed { warmup, .. } => 8 + warmup.len() as u32, | ||
| 654 | + PlanKind::Lpc { warmup, .. } => 31 + warmup.len() as u32, | ||
| 655 | + }; | ||
| 656 | + w.write_bit(false); | ||
| 657 | + w.write_bits(kind_code, 6); | ||
| 658 | + w.write_bit(plan.wasted > 0); | ||
| 659 | + if plan.wasted > 0 { | ||
| 660 | + // Unary: `wasted - 1` zeroes then a one. | ||
| 661 | + for _ in 0..plan.wasted - 1 { | ||
| 662 | + w.write_bit(false); | ||
| 663 | + } | ||
| 664 | + w.write_bit(true); | ||
| 665 | + } | ||
| 666 | + let bps = bps - plan.wasted; | ||
| 667 | + match &plan.kind { | ||
| 668 | + PlanKind::Constant(v) => w.write_signed(*v, bps), | ||
| 669 | + PlanKind::Verbatim(samples) => { | ||
| 670 | + for &s in samples { | ||
| 671 | + w.write_signed(s, bps); | ||
| 672 | + } | ||
| 673 | + } | ||
| 674 | + PlanKind::Fixed { | ||
| 675 | + warmup, | ||
| 676 | + residual, | ||
| 677 | + rice, | ||
| 678 | + } => { | ||
| 679 | + for &s in warmup { | ||
| 680 | + w.write_signed(s, bps); | ||
| 681 | + } | ||
| 682 | + write_residual(w, residual, rice); | ||
| 683 | + } | ||
| 684 | + PlanKind::Lpc { | ||
| 685 | + warmup, | ||
| 686 | + precision, | ||
| 687 | + shift, | ||
| 688 | + coefs, | ||
| 689 | + residual, | ||
| 690 | + rice, | ||
| 691 | + } => { | ||
| 692 | + for &s in warmup { | ||
| 693 | + w.write_signed(s, bps); | ||
| 694 | + } | ||
| 695 | + w.write_bits(precision - 1, 4); | ||
| 696 | + w.write_bits(*shift, 5); | ||
| 697 | + for &c in coefs { | ||
| 698 | + w.write_signed(c, *precision); | ||
| 699 | + } | ||
| 700 | + write_residual(w, residual, rice); | ||
| 701 | + } | ||
| 702 | + } | ||
| 703 | +} | ||
| 704 | + | ||
| 705 | +fn write_residual(w: &mut BitWriter, residual: &[i32], rice: &RicePlan) { | ||
| 706 | + w.write_bits(u32::from(rice.param_bits == 5), 2); | ||
| 707 | + w.write_bits(rice.partition_order, 4); | ||
| 708 | + let partitions = 1usize << rice.partition_order; | ||
| 709 | + let partition_len = (residual.len() + rice.order) / partitions; | ||
| 710 | + let mut at = 0usize; | ||
| 711 | + for (p, ¶m) in rice.params.iter().enumerate() { | ||
| 712 | + let count = partition_len - if p == 0 { rice.order } else { 0 }; | ||
| 713 | + w.write_bits(param, rice.param_bits); | ||
| 714 | + for &r in &residual[at..at + count] { | ||
| 715 | + let folded = fold(r); | ||
| 716 | + for _ in 0..folded >> param { | ||
| 717 | + w.write_bit(false); | ||
| 718 | + } | ||
| 719 | + w.write_bit(true); | ||
| 720 | + if param > 0 { | ||
| 721 | + w.write_bits(folded & ((1 << param) - 1), param); | ||
| 722 | + } | ||
| 723 | + } | ||
| 724 | + at += count; | ||
| 725 | + } | ||
| 726 | + debug_assert_eq!(at, residual.len()); | ||
| 727 | +} | ||
| 728 | + | ||
| 729 | +fn tukey_window(n: usize) -> Vec<f64> { | ||
| 730 | + // Tukey(0.5): a Hann taper over the outer quarter at each end, flat between. | ||
| 731 | + const P: f64 = 0.5; | ||
| 732 | + let taper = (P * (n as f64 - 1.0) / 2.0).max(1.0); | ||
| 733 | + (0..n) | ||
| 734 | + .map(|i| { | ||
| 735 | + let i = i as f64; | ||
| 736 | + let last = n as f64 - 1.0; | ||
| 737 | + if i < taper { | ||
| 738 | + 0.5 * (1.0 - (std::f64::consts::PI * i / taper).cos()) | ||
| 739 | + } else if i > last - taper { | ||
| 740 | + 0.5 * (1.0 - (std::f64::consts::PI * (last - i) / taper).cos()) | ||
| 741 | + } else { | ||
| 742 | + 1.0 | ||
| 743 | + } | ||
| 744 | + }) | ||
| 745 | + .collect() | ||
| 746 | +} | ||
| 747 | + | ||
| 748 | +fn autocorrelation(signal: &[f64], max_order: usize) -> Vec<f64> { | ||
| 749 | + (0..=max_order) | ||
| 750 | + .map(|lag| { | ||
| 751 | + signal[lag..] | ||
| 752 | + .iter() | ||
| 753 | + .zip(signal) | ||
| 754 | + .map(|(a, b)| a * b) | ||
| 755 | + .sum::<f64>() | ||
| 756 | + }) | ||
| 757 | + .collect() | ||
| 758 | +} | ||
| 759 | + | ||
| 760 | +/// Levinson-Durbin: predictor coefficients for every order up to `max_order`, | ||
| 761 | +/// plus the prediction error each order leaves. | ||
| 762 | +/// | ||
| 763 | +/// The returned coefficients are in FLAC's sense — `x[n] ~ sum c[k]*x[n-1-k]` — | ||
| 764 | +/// which is the negation of the recursion's internal ones. | ||
| 765 | +fn levinson_durbin(autoc: &[f64], max_order: usize) -> (Vec<Vec<f64>>, Vec<f64>) { | ||
| 766 | + let mut coefs = vec![Vec::new(); max_order + 1]; | ||
| 767 | + let mut errors = vec![autoc[0]; max_order + 1]; | ||
| 768 | + let mut a = vec![0.0f64; max_order]; | ||
| 769 | + let mut err = autoc[0]; | ||
| 770 | + for i in 0..max_order { | ||
| 771 | + if err <= 0.0 { | ||
| 772 | + break; | ||
| 773 | + } | ||
| 774 | + let mut r = -autoc[i + 1]; | ||
| 775 | + for j in 0..i { | ||
| 776 | + r -= a[j] * autoc[i - j]; | ||
| 777 | + } | ||
| 778 | + r /= err; | ||
| 779 | + a[i] = r; | ||
| 780 | + for j in 0..i / 2 { | ||
| 781 | + let tmp = a[j]; | ||
| 782 | + a[j] += r * a[i - 1 - j]; | ||
| 783 | + a[i - 1 - j] += r * tmp; | ||
| 784 | + } | ||
| 785 | + if i % 2 == 1 { | ||
| 786 | + let j = i / 2; | ||
| 787 | + a[j] += a[j] * r; | ||
| 788 | + } | ||
| 789 | + err *= 1.0 - r * r; | ||
| 790 | + errors[i + 1] = err; | ||
| 791 | + coefs[i + 1] = a[..=i].iter().map(|&v| -v).collect(); | ||
| 792 | + } | ||
| 793 | + (coefs, errors) | ||
| 794 | +} | ||
| 795 | + | ||
| 796 | +/// Quantise predictor coefficients to `precision` bits and a shift, carrying | ||
| 797 | +/// the rounding error forward. | ||
| 798 | +fn quantize_coefficients(coefs: &[f64], precision: u32) -> Option<(Vec<i32>, u32)> { | ||
| 799 | + const MAX_SHIFT: i32 = 15; | ||
| 800 | + let cmax = coefs.iter().fold(0.0f64, |m, c| m.max(c.abs())); | ||
| 801 | + if cmax <= 0.0 || !cmax.is_finite() { | ||
| 802 | + return None; | ||
| 803 | + } | ||
| 804 | + let log2cmax = cmax.log2().floor() as i32; | ||
| 805 | + let shift = (precision as i32 - 1 - log2cmax - 1).min(MAX_SHIFT); | ||
| 806 | + if shift < 0 { | ||
| 807 | + return None; // coefficients too large to quantise; fixed predictors win. | ||
| 808 | + } | ||
| 809 | + let limit = 1i32 << (precision - 1); | ||
| 810 | + let scale = f64::from(1i32 << shift); | ||
| 811 | + let mut error = 0.0f64; | ||
| 812 | + let mut out = Vec::with_capacity(coefs.len()); | ||
| 813 | + for &c in coefs { | ||
| 814 | + error += c * scale; | ||
| 815 | + let q = error.round().clamp(f64::from(-limit), f64::from(limit - 1)) as i32; | ||
| 816 | + error -= f64::from(q); | ||
| 817 | + out.push(q); | ||
| 818 | + } | ||
| 819 | + Some((out, shift as u32)) | ||
| 820 | +} | ||
| 821 | + | ||
| 822 | +#[cfg(test)] | ||
| 823 | +mod tests { | ||
| 824 | + use super::*; | ||
| 825 | + use crate::decode::{Block, FlacReader, read_utf8_number}; | ||
| 826 | + use ec_core::bitio::BitReader; | ||
| 827 | + | ||
| 828 | + fn tone(frames: usize, channels: usize, bps: u32) -> Vec<i32> { | ||
| 829 | + let amp = f64::from(1i32 << (bps - 2)); | ||
| 830 | + (0..frames * channels) | ||
| 831 | + .map(|i| { | ||
| 832 | + let t = (i / channels) as f64; | ||
| 833 | + let c = (i % channels) as f64; | ||
| 834 | + (amp * ((t * 0.031 + c * 0.7).sin() + 0.2 * (t * 0.29).sin())) as i32 | ||
| 835 | + }) | ||
| 836 | + .collect() | ||
| 837 | + } | ||
| 838 | + | ||
| 839 | + fn round_trip(samples: &[i32], channels: usize, bps: u32, rate: u32) { | ||
| 840 | + let config = EncoderConfig::default(); | ||
| 841 | + let bytes = encode(&config, samples, channels, bps, rate).expect("encode"); | ||
| 842 | + let mut reader = FlacReader::new(&bytes).expect("open"); | ||
| 843 | + let info = reader.stream_info().expect("streaminfo").clone(); | ||
| 844 | + assert_eq!(info.sample_rate, rate); | ||
| 845 | + assert_eq!(usize::from(info.channels), channels); | ||
| 846 | + assert_eq!(u32::from(info.bits_per_sample), bps); | ||
| 847 | + assert_eq!(info.total_samples, (samples.len() / channels) as u64); | ||
| 848 | + let decoded = reader.decode_all().expect("decode"); | ||
| 849 | + assert_eq!( | ||
| 850 | + decoded.interleaved(), | ||
| 851 | + samples, | ||
| 852 | + "{channels}ch/{bps}bit/{rate}Hz did not round-trip" | ||
| 853 | + ); | ||
| 854 | + assert_eq!( | ||
| 855 | + info.md5, | ||
| 856 | + md5_of_samples(&decoded.interleaved(), bps), | ||
| 857 | + "STREAMINFO MD5 must match the decoded audio" | ||
| 858 | + ); | ||
| 859 | + } | ||
| 860 | + | ||
| 861 | + #[test] | ||
| 862 | + fn round_trips_every_shape_the_family_uses() { | ||
| 863 | + for (channels, bps, rate) in [ | ||
| 864 | + (1usize, 16u32, 44100u32), | ||
| 865 | + (2, 16, 44100), | ||
| 866 | + (2, 16, 48000), | ||
| 867 | + (2, 24, 96000), | ||
| 868 | + (6, 16, 48000), | ||
| 869 | + (8, 24, 48000), | ||
| 870 | + (1, 8, 8000), | ||
| 871 | + (2, 20, 192_000), | ||
| 872 | + ] { | ||
| 873 | + round_trip(&tone(5000, channels, bps), channels, bps, rate); | ||
| 874 | + } | ||
| 875 | + } | ||
| 876 | + | ||
| 877 | + #[test] | ||
| 878 | + fn round_trips_the_awkward_signals() { | ||
| 879 | + let config = EncoderConfig::default(); | ||
| 880 | + let cases: Vec<Vec<i32>> = vec![ | ||
| 881 | + vec![0; 4096 * 2], // digital silence | ||
| 882 | + vec![i32::from(i16::MIN); 100], // constant full scale | ||
| 883 | + (0..8192) | ||
| 884 | + .map(|i| if i % 64 < 32 { 3000 } else { -3000 }) | ||
| 885 | + .collect(), // square | ||
| 886 | + vec![-1], // one sample | ||
| 887 | + (0..4096).map(|i| (i % 7) * 256).collect(), // wasted bits | ||
| 888 | + (0..4096) | ||
| 889 | + .map(|i| ((i * 2654435761u64 % 65536) as i32) - 32768) | ||
| 890 | + .collect(), // noise | ||
| 891 | + ]; | ||
| 892 | + for samples in cases { | ||
| 893 | + let bytes = encode(&config, &samples, 1, 16, 44100).expect("encode"); | ||
| 894 | + let decoded = FlacReader::new(&bytes) | ||
| 895 | + .expect("open") | ||
| 896 | + .decode_all() | ||
| 897 | + .expect("decode"); | ||
| 898 | + assert_eq!(decoded.interleaved(), samples); | ||
| 899 | + } | ||
| 900 | + } | ||
| 901 | + | ||
| 902 | + #[test] | ||
| 903 | + fn a_short_last_block_still_decodes() { | ||
| 904 | + let config = EncoderConfig { | ||
| 905 | + block_size: 512, | ||
| 906 | + ..EncoderConfig::default() | ||
| 907 | + }; | ||
| 908 | + let samples = tone(1300, 2, 16); | ||
| 909 | + let bytes = encode(&config, &samples, 2, 16, 44100).expect("encode"); | ||
| 910 | + let mut reader = FlacReader::new(&bytes).expect("open"); | ||
| 911 | + let mut block = Block::default(); | ||
| 912 | + let mut sizes = Vec::new(); | ||
| 913 | + while reader.next_block(&mut block).expect("frame") { | ||
| 914 | + sizes.push(block.len()); | ||
| 915 | + } | ||
| 916 | + assert_eq!(sizes, vec![512, 512, 276]); | ||
| 917 | + } | ||
| 918 | + | ||
| 919 | + #[test] | ||
| 920 | + fn refuses_input_it_cannot_encode_losslessly() { | ||
| 921 | + let config = EncoderConfig::default(); | ||
| 922 | + assert!(encode(&config, &[1 << 20], 1, 16, 44100).is_err()); | ||
| 923 | + assert!(encode(&config, &[1, 2, 3], 2, 16, 44100).is_err()); | ||
| 924 | + assert!(encode(&config, &[0; 16], 9, 16, 44100).is_err()); | ||
| 925 | + assert!(encode(&config, &[0; 16], 1, 33, 44100).is_err()); | ||
| 926 | + assert!(encode(&config, &[0; 16], 1, 16, 0).is_err()); | ||
| 927 | + } | ||
| 928 | + | ||
| 929 | + #[test] | ||
| 930 | + fn utf8_coded_numbers_round_trip() { | ||
| 931 | + for value in [ | ||
| 932 | + 0u64, | ||
| 933 | + 1, | ||
| 934 | + 0x7f, | ||
| 935 | + 0x80, | ||
| 936 | + 0x7ff, | ||
| 937 | + 0x800, | ||
| 938 | + 0xffff, | ||
| 939 | + 0x10_ffff, | ||
| 940 | + 0x3ff_ffff, | ||
| 941 | + 0x7fff_ffff, | ||
| 942 | + ] { | ||
| 943 | + let mut w = BitWriter::new(); | ||
| 944 | + write_utf8_number(&mut w, value); | ||
| 945 | + let bytes = w.into_bytes(); | ||
| 946 | + let mut r = BitReader::new(&bytes); | ||
| 947 | + assert_eq!( | ||
| 948 | + read_utf8_number(&mut r, 36).unwrap(), | ||
| 949 | + value, | ||
| 950 | + "number {value}" | ||
| 951 | + ); | ||
| 952 | + } | ||
| 953 | + } | ||
| 954 | + | ||
| 955 | + #[test] | ||
| 956 | + fn compresses_better_than_raw_pcm() { | ||
| 957 | + let samples = tone(44100, 2, 16); | ||
| 958 | + let raw = samples.len() * 2; | ||
| 959 | + let bytes = encode(&EncoderConfig::default(), &samples, 2, 16, 44100).unwrap(); | ||
| 960 | + assert!( | ||
| 961 | + bytes.len() < raw / 2, | ||
| 962 | + "{} bytes from {raw} of PCM is not compression", | ||
| 963 | + bytes.len() | ||
| 964 | + ); | ||
| 965 | + } | ||
| 966 | +} | ||
crates/ec-flac/src/lib.rsadded+191 -0
| @@ -0,0 +1,191 @@ | |||
| 1 | +//! FLAC (RFC 9639) decoding and encoding for the edith_codecs family. | ||
| 2 | +//! | ||
| 3 | +//! Three ways in, smallest first: | ||
| 4 | +//! | ||
| 5 | +//! - [`decode::FlacReader`] over a whole `.flac` buffer — metadata, frames, | ||
| 6 | +//! seek table, and [`decode::FlacReader::decode_all`] for the common case. | ||
| 7 | +//! - [`FlacDecoder`], the [`ec_core::Decoder`] contract, for a container that | ||
| 8 | +//! hands out one FLAC frame per packet. | ||
| 9 | +//! - [`encode::encode`], interleaved samples in, a complete stream out, with | ||
| 10 | +//! the `STREAMINFO` MD5 filled in so any decoder can prove we were lossless. | ||
| 11 | +//! | ||
| 12 | +//! Decoded samples keep their own bit depth in [`decode::Block`] and | ||
| 13 | +//! [`decode::DecodedStream`]; the PCM views ([`decode::DecodedStream::to_pcm_bytes`], | ||
| 14 | +//! [`FlacDecoder`]) shift them left into an `s16`/`s32` container the way | ||
| 15 | +//! ffmpeg and the family's mixer expect. | ||
| 16 | +//! | ||
| 17 | +//! Nothing here panics on malformed input: truncation is `NeedMore`, a broken | ||
| 18 | +//! stream is `Corrupt`, and both CRCs are checked on every frame. | ||
| 19 | + | ||
| 20 | +#![forbid(unsafe_code)] | ||
| 21 | +#![warn(missing_docs)] | ||
| 22 | + | ||
| 23 | +pub mod checksum; | ||
| 24 | +pub mod decode; | ||
| 25 | +pub mod encode; | ||
| 26 | + | ||
| 27 | +use ec_core::error::{Error, Result}; | ||
| 28 | +use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; | ||
| 29 | +use ec_core::packet::{Buf, Packet}; | ||
| 30 | +use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters}; | ||
| 31 | + | ||
| 32 | +pub use decode::{Block, DecodedStream, FlacReader, StreamInfo}; | ||
| 33 | +pub use encode::{EncoderConfig, encode}; | ||
| 34 | + | ||
| 35 | +/// The [`ec_core::Decoder`] seat for FLAC: one packet is one FLAC frame, which | ||
| 36 | +/// is how Matroska, Ogg and the family's own probe deliver them. | ||
| 37 | +#[derive(Debug)] | ||
| 38 | +pub struct FlacDecoder { | ||
| 39 | + params: CodecParameters, | ||
| 40 | + stream_info: Option<StreamInfo>, | ||
| 41 | + block: Block, | ||
| 42 | + pending: Option<AudioFrame>, | ||
| 43 | + drained: bool, | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +impl FlacDecoder { | ||
| 47 | + /// A decoder for a stream whose `extradata`, when present, is the 34-byte | ||
| 48 | + /// `STREAMINFO` payload every container carries for FLAC. | ||
| 49 | + pub fn new(params: CodecParameters) -> Result<FlacDecoder> { | ||
| 50 | + let stream_info = match ¶ms.extradata { | ||
| 51 | + Some(bytes) if bytes.len() >= 34 => Some(StreamInfo::parse(&bytes[..34])?), | ||
| 52 | + _ => None, | ||
| 53 | + }; | ||
| 54 | + Ok(FlacDecoder { | ||
| 55 | + params, | ||
| 56 | + stream_info, | ||
| 57 | + block: Block::default(), | ||
| 58 | + pending: None, | ||
| 59 | + drained: false, | ||
| 60 | + }) | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +impl Decoder for FlacDecoder { | ||
| 65 | + fn codec_parameters(&self) -> &CodecParameters { | ||
| 66 | + &self.params | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + fn send_packet(&mut self, packet: &Packet) -> Result<()> { | ||
| 70 | + let mut reader = FlacReader::frames(&packet.data, self.stream_info.clone())?; | ||
| 71 | + if !reader.next_block(&mut self.block)? { | ||
| 72 | + return Err(Error::NeedMore); | ||
| 73 | + } | ||
| 74 | + let header = self.block.header.expect("a decoded block has a header"); | ||
| 75 | + let shift = decode::container_shift(header.bits_per_sample); | ||
| 76 | + let format = match header.bits_per_sample <= 16 { | ||
| 77 | + true => SampleFormat::S16, | ||
| 78 | + false => SampleFormat::S32, | ||
| 79 | + }; | ||
| 80 | + let samples = self.block.len(); | ||
| 81 | + let interleaved = self.block.to_interleaved(shift); | ||
| 82 | + let mut bytes = Vec::with_capacity(interleaved.len() * format.bytes_per_sample()); | ||
| 83 | + for s in interleaved { | ||
| 84 | + match format { | ||
| 85 | + SampleFormat::S16 => bytes.extend_from_slice(&(s as i16).to_ne_bytes()), | ||
| 86 | + _ => bytes.extend_from_slice(&s.to_ne_bytes()), | ||
| 87 | + } | ||
| 88 | + } | ||
| 89 | + let layout = ChannelLayout::from_count(self.block.channels.len()); | ||
| 90 | + let mut frame = AudioFrame::try_new( | ||
| 91 | + format, | ||
| 92 | + false, | ||
| 93 | + layout.clone(), | ||
| 94 | + header.sample_rate, | ||
| 95 | + samples, | ||
| 96 | + vec![Buf::from_vec(bytes)], | ||
| 97 | + )?; | ||
| 98 | + frame.pts = None; | ||
| 99 | + self.params.media = MediaParameters::Audio(AudioParameters { | ||
| 100 | + sample_rate: header.sample_rate, | ||
| 101 | + layout, | ||
| 102 | + format: Some(format), | ||
| 103 | + bits_per_sample: Some(header.bits_per_sample), | ||
| 104 | + }); | ||
| 105 | + self.pending = Some(frame); | ||
| 106 | + Ok(()) | ||
| 107 | + } | ||
| 108 | + | ||
| 109 | + fn receive_frame(&mut self) -> Result<Frame> { | ||
| 110 | + match self.pending.take() { | ||
| 111 | + Some(frame) => Ok(Frame::Audio(frame)), | ||
| 112 | + None if self.drained => Err(Error::Eof), | ||
| 113 | + None => Err(Error::NeedMore), | ||
| 114 | + } | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + fn flush(&mut self) -> Result<()> { | ||
| 118 | + self.drained = true; | ||
| 119 | + Ok(()) | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + fn reset(&mut self) { | ||
| 123 | + self.pending = None; | ||
| 124 | + self.drained = false; | ||
| 125 | + } | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +/// Codec parameters for a FLAC stream described by its `STREAMINFO`. | ||
| 129 | +pub fn codec_parameters(info: &StreamInfo) -> CodecParameters { | ||
| 130 | + let mut params = CodecParameters::new(CodecId::Flac); | ||
| 131 | + params.extradata = Some(Buf::from_vec(info.to_bytes().to_vec())); | ||
| 132 | + params.media = MediaParameters::Audio(AudioParameters { | ||
| 133 | + sample_rate: info.sample_rate, | ||
| 134 | + layout: ChannelLayout::from_count(usize::from(info.channels)), | ||
| 135 | + format: Some(match info.bits_per_sample <= 16 { | ||
| 136 | + true => SampleFormat::S16, | ||
| 137 | + false => SampleFormat::S32, | ||
| 138 | + }), | ||
| 139 | + bits_per_sample: Some(u32::from(info.bits_per_sample)), | ||
| 140 | + }); | ||
| 141 | + params | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +#[cfg(test)] | ||
| 145 | +mod tests { | ||
| 146 | + use super::*; | ||
| 147 | + use ec_core::timebase::TimeBase; | ||
| 148 | + | ||
| 149 | + /// The container path: encode, hand each frame over as its own packet, and | ||
| 150 | + /// get the same audio back through the family's `Decoder` trait. | ||
| 151 | + #[test] | ||
| 152 | + fn decoder_trait_round_trips_packet_by_packet() { | ||
| 153 | + let samples: Vec<i32> = (0..8000) | ||
| 154 | + .map(|i| ((i as f64 * 0.05).sin() * 8000.0) as i32) | ||
| 155 | + .collect(); | ||
| 156 | + let config = EncoderConfig { | ||
| 157 | + block_size: 1024, | ||
| 158 | + ..EncoderConfig::default() | ||
| 159 | + }; | ||
| 160 | + let stream = encode(&config, &samples, 2, 16, 44100).expect("encode"); | ||
| 161 | + | ||
| 162 | + let mut reader = FlacReader::new(&stream).expect("open"); | ||
| 163 | + let info = reader.stream_info().expect("streaminfo").clone(); | ||
| 164 | + let mut decoder = FlacDecoder::new(codec_parameters(&info)).expect("decoder"); | ||
| 165 | + | ||
| 166 | + // Slice the stream back into frames the way a demuxer would. | ||
| 167 | + let mut block = Block::default(); | ||
| 168 | + let mut bounds = vec![reader.position()]; | ||
| 169 | + while reader.next_block(&mut block).expect("frame") { | ||
| 170 | + bounds.push(reader.position()); | ||
| 171 | + } | ||
| 172 | + let time_base = TimeBase::new(1, 44100); | ||
| 173 | + let mut got = Vec::new(); | ||
| 174 | + for w in bounds.windows(2) { | ||
| 175 | + let packet = Packet::new(0, time_base, &stream[w[0]..w[1]]); | ||
| 176 | + decoder.send_packet(&packet).expect("send"); | ||
| 177 | + let Frame::Audio(frame) = decoder.receive_frame().expect("receive") else { | ||
| 178 | + panic!("FLAC decoded to a video frame"); | ||
| 179 | + }; | ||
| 180 | + assert_eq!(frame.format, SampleFormat::S16); | ||
| 181 | + assert_eq!(frame.channels(), 2); | ||
| 182 | + for chunk in frame.data[0].chunks_exact(2).take(frame.samples * 2) { | ||
| 183 | + got.push(i16::from_ne_bytes([chunk[0], chunk[1]]) as i32); | ||
| 184 | + } | ||
| 185 | + } | ||
| 186 | + assert_eq!(got, samples); | ||
| 187 | + assert!(decoder.receive_frame().unwrap_err().is_need_more()); | ||
| 188 | + decoder.flush().unwrap(); | ||
| 189 | + assert!(decoder.receive_frame().unwrap_err().is_eof()); | ||
| 190 | + } | ||
| 191 | +} | ||
crates/ec-flac/tests/encode_matrix.rsadded+263 -0
| @@ -0,0 +1,263 @@ | |||
| 1 | +//! Our encoder against the fixture matrix, proven the only way a lossless | ||
| 2 | +//! codec can be: encode, decode the result with ffmpeg, compare with the input | ||
| 3 | +//! byte for byte. | ||
| 4 | +//! | ||
| 5 | +//! The size column is informational — it is the same corpus measured against | ||
| 6 | +//! `ffmpeg -c:a flac` at its default compression level. | ||
| 7 | +//! | ||
| 8 | +//! Run the table: | ||
| 9 | +//! cargo test -p ec-flac --release --test encode_matrix -- --nocapture | ||
| 10 | + | ||
| 11 | +use std::path::{Path, PathBuf}; | ||
| 12 | +use std::process::Command; | ||
| 13 | + | ||
| 14 | +use ec_flac::encode::{EncoderConfig, encode}; | ||
| 15 | + | ||
| 16 | +struct Source { | ||
| 17 | + path: PathBuf, | ||
| 18 | + channels: usize, | ||
| 19 | + rate: u32, | ||
| 20 | + bits: u32, | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +fn fixtures() -> PathBuf { | ||
| 24 | + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// A working directory keyed by test name: these tests are threads of one | ||
| 28 | +/// process, so a shared temp directory would have them deleting each other's | ||
| 29 | +/// files. | ||
| 30 | +fn workdir(test: &str) -> PathBuf { | ||
| 31 | + let dir = std::env::temp_dir().join(format!("ec-flac-{}-{test}", std::process::id())); | ||
| 32 | + std::fs::create_dir_all(&dir).expect("create work dir"); | ||
| 33 | + dir | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +fn probe(path: &Path) -> Option<Source> { | ||
| 37 | + let out = Command::new("ffprobe") | ||
| 38 | + .args([ | ||
| 39 | + "-v", | ||
| 40 | + "error", | ||
| 41 | + "-select_streams", | ||
| 42 | + "a:0", | ||
| 43 | + "-show_entries", | ||
| 44 | + "stream=channels,sample_rate,bits_per_raw_sample,sample_fmt", | ||
| 45 | + "-of", | ||
| 46 | + "default=noprint_wrappers=1", | ||
| 47 | + ]) | ||
| 48 | + .arg(path) | ||
| 49 | + .output() | ||
| 50 | + .ok()?; | ||
| 51 | + // Key=value, because ffprobe prints its own field order, not the requested | ||
| 52 | + // one — a positional parse silently swaps rate and channels. | ||
| 53 | + let text = String::from_utf8_lossy(&out.stdout); | ||
| 54 | + let field = |key: &str| { | ||
| 55 | + text.lines() | ||
| 56 | + .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) | ||
| 57 | + .map(str::trim) | ||
| 58 | + }; | ||
| 59 | + let bits = match field("bits_per_raw_sample").and_then(|v| v.parse::<u32>().ok()) { | ||
| 60 | + Some(n) => n, | ||
| 61 | + // WAV states no `bits_per_raw_sample`; its sample format carries it. | ||
| 62 | + None => match field("sample_fmt")? { | ||
| 63 | + "s16" | "s16p" => 16, | ||
| 64 | + "s32" | "s32p" => 32, | ||
| 65 | + "u8" | "u8p" => 8, | ||
| 66 | + _ => return None, | ||
| 67 | + }, | ||
| 68 | + }; | ||
| 69 | + Some(Source { | ||
| 70 | + path: path.to_path_buf(), | ||
| 71 | + channels: field("channels")?.parse().ok()?, | ||
| 72 | + rate: field("sample_rate")?.parse().ok()?, | ||
| 73 | + bits, | ||
| 74 | + }) | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +fn ffmpeg_pcm(path: &Path, bits: u32) -> Vec<u8> { | ||
| 78 | + let format = if bits <= 16 { "s16le" } else { "s32le" }; | ||
| 79 | + let out = Command::new("ffmpeg") | ||
| 80 | + .args(["-v", "error", "-i"]) | ||
| 81 | + .arg(path) | ||
| 82 | + .args(["-f", format, "-"]) | ||
| 83 | + .output() | ||
| 84 | + .expect("run ffmpeg"); | ||
| 85 | + assert!( | ||
| 86 | + out.status.success(), | ||
| 87 | + "ffmpeg failed on {}: {}", | ||
| 88 | + path.display(), | ||
| 89 | + String::from_utf8_lossy(&out.stderr) | ||
| 90 | + ); | ||
| 91 | + out.stdout | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +/// Raw PCM as the samples FLAC codes: the container shift undone. | ||
| 95 | +fn samples_from_pcm(pcm: &[u8], bits: u32) -> Vec<i32> { | ||
| 96 | + match bits <= 16 { | ||
| 97 | + true => pcm | ||
| 98 | + .chunks_exact(2) | ||
| 99 | + .map(|c| i32::from(i16::from_le_bytes([c[0], c[1]])) >> (16 - bits)) | ||
| 100 | + .collect(), | ||
| 101 | + false => pcm | ||
| 102 | + .chunks_exact(4) | ||
| 103 | + .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) >> (32 - bits)) | ||
| 104 | + .collect(), | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option<u64> { | ||
| 109 | + let _ = std::fs::remove_file(out); | ||
| 110 | + let status = Command::new("ffmpeg") | ||
| 111 | + .args(["-v", "error", "-y", "-i"]) | ||
| 112 | + .arg(src) | ||
| 113 | + .args(["-c:a", "flac"]) | ||
| 114 | + .arg(out) | ||
| 115 | + .status() | ||
| 116 | + .ok()?; | ||
| 117 | + match status.success() { | ||
| 118 | + true => std::fs::metadata(out).ok().map(|m| m.len()), | ||
| 119 | + false => None, | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +fn matrix() -> Vec<Source> { | ||
| 124 | + let audio = fixtures().join("audio"); | ||
| 125 | + let vectors = fixtures().join("vectors/flac-xiph/flac-test-files-main/subset"); | ||
| 126 | + let mut paths: Vec<PathBuf> = Vec::new(); | ||
| 127 | + if let Ok(entries) = std::fs::read_dir(&audio) { | ||
| 128 | + let mut found: Vec<PathBuf> = entries | ||
| 129 | + .filter_map(|e| e.ok().map(|e| e.path())) | ||
| 130 | + .filter(|p| { | ||
| 131 | + let name = p.file_name().unwrap_or_default().to_string_lossy(); | ||
| 132 | + name.starts_with("flac-") || name.starts_with("wav16-") | ||
| 133 | + }) | ||
| 134 | + .collect(); | ||
| 135 | + found.sort(); | ||
| 136 | + paths.append(&mut found); | ||
| 137 | + } | ||
| 138 | + // Depth coverage the generated fixtures do not have: 24- and 20-bit. | ||
| 139 | + for name in [ | ||
| 140 | + "28 - high resolution audio, default settings.flac", | ||
| 141 | + "37 - 20 bit per sample.flac", | ||
| 142 | + ] { | ||
| 143 | + let p = vectors.join(name); | ||
| 144 | + if p.exists() { | ||
| 145 | + paths.push(p); | ||
| 146 | + } | ||
| 147 | + } | ||
| 148 | + paths.iter().filter_map(|p| probe(p)).collect() | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +#[test] | ||
| 152 | +fn encoded_streams_decode_back_bit_exact_through_ffmpeg() { | ||
| 153 | + let sources = matrix(); | ||
| 154 | + if sources.is_empty() { | ||
| 155 | + eprintln!("skipped: fixtures not generated"); | ||
| 156 | + return; | ||
| 157 | + } | ||
| 158 | + let dir = workdir("roundtrip"); | ||
| 159 | + let config = EncoderConfig::default(); | ||
| 160 | + let mut failures = Vec::new(); | ||
| 161 | + let (mut ours_total, mut theirs_total) = (0u64, 0u64); | ||
| 162 | + println!( | ||
| 163 | + "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}", | ||
| 164 | + "fixture", "ch", "bit", "rate", "ours", "ffmpeg", "ratio" | ||
| 165 | + ); | ||
| 166 | + for source in &sources { | ||
| 167 | + let name = source | ||
| 168 | + .path | ||
| 169 | + .file_name() | ||
| 170 | + .unwrap_or_default() | ||
| 171 | + .to_string_lossy() | ||
| 172 | + .to_string(); | ||
| 173 | + let pcm = ffmpeg_pcm(&source.path, source.bits); | ||
| 174 | + let samples = samples_from_pcm(&pcm, source.bits); | ||
| 175 | + let encoded = match encode(&config, &samples, source.channels, source.bits, source.rate) { | ||
| 176 | + Ok(bytes) => bytes, | ||
| 177 | + Err(e) => { | ||
| 178 | + failures.push(format!("{name}: encode failed: {e}")); | ||
| 179 | + continue; | ||
| 180 | + } | ||
| 181 | + }; | ||
| 182 | + let out = dir.join(format!("{name}.ours.flac")); | ||
| 183 | + std::fs::write(&out, &encoded).expect("write encoded"); | ||
| 184 | + let decoded = ffmpeg_pcm(&out, source.bits); | ||
| 185 | + if decoded != pcm { | ||
| 186 | + let at = decoded | ||
| 187 | + .iter() | ||
| 188 | + .zip(&pcm) | ||
| 189 | + .position(|(a, b)| a != b) | ||
| 190 | + .map_or_else(|| "length only".to_string(), |i| format!("byte {i}")); | ||
| 191 | + failures.push(format!( | ||
| 192 | + "{name}: ffmpeg decoded our stream differently at {at} ({} vs {} bytes)", | ||
| 193 | + decoded.len(), | ||
| 194 | + pcm.len() | ||
| 195 | + )); | ||
| 196 | + continue; | ||
| 197 | + } | ||
| 198 | + let theirs = ffmpeg_flac_size(&source.path, &dir.join(format!("{name}.ffmpeg.flac"))); | ||
| 199 | + ours_total += encoded.len() as u64; | ||
| 200 | + theirs_total += theirs.unwrap_or(0); | ||
| 201 | + println!( | ||
| 202 | + "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}", | ||
| 203 | + name, | ||
| 204 | + source.channels, | ||
| 205 | + source.bits, | ||
| 206 | + source.rate, | ||
| 207 | + encoded.len(), | ||
| 208 | + theirs.map_or("-".to_string(), |n| n.to_string()), | ||
| 209 | + theirs.map_or("-".to_string(), |n| format!( | ||
| 210 | + "{:.3}", | ||
| 211 | + encoded.len() as f64 / n as f64 | ||
| 212 | + )), | ||
| 213 | + ); | ||
| 214 | + } | ||
| 215 | + println!( | ||
| 216 | + "totals: ours {ours_total}, ffmpeg {theirs_total}, ratio {:.3}", | ||
| 217 | + ours_total as f64 / theirs_total.max(1) as f64 | ||
| 218 | + ); | ||
| 219 | + assert!(failures.is_empty(), "{}", failures.join("\n")); | ||
| 220 | + // Informational bar from the slice charter: within 10% of ffmpeg's default. | ||
| 221 | + assert!( | ||
| 222 | + ours_total as f64 <= theirs_total as f64 * 1.10, | ||
| 223 | + "corpus is {:.1}% larger than ffmpeg's default FLAC", | ||
| 224 | + (ours_total as f64 / theirs_total as f64 - 1.0) * 100.0 | ||
| 225 | + ); | ||
| 226 | +} | ||
| 227 | + | ||
| 228 | +#[test] | ||
| 229 | +fn our_streams_survive_a_probe_and_state_their_shape() { | ||
| 230 | + let Some(source) = matrix().into_iter().find(|s| s.channels == 6) else { | ||
| 231 | + eprintln!("skipped: no 5.1 fixture"); | ||
| 232 | + return; | ||
| 233 | + }; | ||
| 234 | + let dir = workdir("probe"); | ||
| 235 | + let pcm = ffmpeg_pcm(&source.path, source.bits); | ||
| 236 | + let samples = samples_from_pcm(&pcm, source.bits); | ||
| 237 | + let encoded = encode( | ||
| 238 | + &EncoderConfig::default(), | ||
| 239 | + &samples, | ||
| 240 | + source.channels, | ||
| 241 | + source.bits, | ||
| 242 | + source.rate, | ||
| 243 | + ) | ||
| 244 | + .expect("encode"); | ||
| 245 | + let out = dir.join("surround.flac"); | ||
| 246 | + std::fs::write(&out, &encoded).expect("write"); | ||
| 247 | + let probed = probe(&out).expect("ffprobe our own output"); | ||
| 248 | + assert_eq!(probed.channels, source.channels); | ||
| 249 | + assert_eq!(probed.rate, source.rate); | ||
| 250 | + assert_eq!(probed.bits, source.bits); | ||
| 251 | + // `-v error` clean: ffmpeg must find nothing to complain about. | ||
| 252 | + let out_err = Command::new("ffmpeg") | ||
| 253 | + .args(["-v", "error", "-i"]) | ||
| 254 | + .arg(&out) | ||
| 255 | + .args(["-f", "null", "-"]) | ||
| 256 | + .output() | ||
| 257 | + .expect("run ffmpeg"); | ||
| 258 | + assert!( | ||
| 259 | + out_err.stderr.is_empty(), | ||
| 260 | + "ffmpeg complained: {}", | ||
| 261 | + String::from_utf8_lossy(&out_err.stderr) | ||
| 262 | + ); | ||
| 263 | +} | ||
crates/ec-flac/tests/xiph_vectors.rsadded+229 -0
| @@ -0,0 +1,229 @@ | |||
| 1 | +//! The Xiph FLAC test corpus, decoded and compared with ffmpeg byte for byte. | ||
| 2 | +//! | ||
| 3 | +//! ffmpeg is oracle tooling, driven through a pipe: it decodes the same file to | ||
| 4 | +//! raw PCM (`s16le` up to 16 bits, `s32le` above, which is the layout | ||
| 5 | +//! [`ec_flac::decode::DecodedStream::to_pcm_bytes`] writes) and the two buffers | ||
| 6 | +//! must be identical. Lossless codec, no tolerance. | ||
| 7 | +//! | ||
| 8 | +//! The corpus is fetched by `scripts/fetch-vectors.sh`; without it every test | ||
| 9 | +//! here skips rather than fails, so a fresh clone still runs green. | ||
| 10 | +//! | ||
| 11 | +//! Run the tables: | ||
| 12 | +//! cargo test -p ec-flac --release --test xiph_vectors -- --nocapture | ||
| 13 | + | ||
| 14 | +use std::path::{Path, PathBuf}; | ||
| 15 | +use std::process::Command; | ||
| 16 | + | ||
| 17 | +use ec_flac::checksum::md5_of_samples; | ||
| 18 | +use ec_flac::decode::FlacReader; | ||
| 19 | + | ||
| 20 | +fn corpus(kind: &str) -> Option<Vec<PathBuf>> { | ||
| 21 | + let dir = Path::new(env!("CARGO_MANIFEST_DIR")) | ||
| 22 | + .join("../../fixtures/vectors/flac-xiph/flac-test-files-main") | ||
| 23 | + .join(kind); | ||
| 24 | + let mut files: Vec<PathBuf> = std::fs::read_dir(dir) | ||
| 25 | + .ok()? | ||
| 26 | + .filter_map(|e| e.ok().map(|e| e.path())) | ||
| 27 | + .filter(|p| p.extension().is_some_and(|e| e == "flac")) | ||
| 28 | + .collect(); | ||
| 29 | + files.sort(); | ||
| 30 | + match files.is_empty() { | ||
| 31 | + true => None, | ||
| 32 | + false => Some(files), | ||
| 33 | + } | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +/// Decode `path` with ffmpeg into the same raw layout our decoder writes. | ||
| 37 | +fn ffmpeg_pcm(path: &Path, bits_per_sample: u32) -> Result<Vec<u8>, String> { | ||
| 38 | + let format = match bits_per_sample <= 16 { | ||
| 39 | + true => "s16le", | ||
| 40 | + false => "s32le", | ||
| 41 | + }; | ||
| 42 | + let out = Command::new("ffmpeg") | ||
| 43 | + .args(["-v", "error", "-i"]) | ||
| 44 | + .arg(path) | ||
| 45 | + .args(["-f", format, "-"]) | ||
| 46 | + .output() | ||
| 47 | + .map_err(|e| format!("ffmpeg: {e}"))?; | ||
| 48 | + match out.status.success() { | ||
| 49 | + true => Ok(out.stdout), | ||
| 50 | + false => Err(String::from_utf8_lossy(&out.stderr).trim().to_string()), | ||
| 51 | + } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +fn name(path: &Path) -> String { | ||
| 55 | + path.file_name() | ||
| 56 | + .unwrap_or_default() | ||
| 57 | + .to_string_lossy() | ||
| 58 | + .into() | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +#[test] | ||
| 62 | +fn subset_vectors_decode_bit_exact_against_ffmpeg() { | ||
| 63 | + let Some(files) = corpus("subset") else { | ||
| 64 | + eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); | ||
| 65 | + return; | ||
| 66 | + }; | ||
| 67 | + let mut failures = Vec::new(); | ||
| 68 | + let mut passed = 0; | ||
| 69 | + for path in &files { | ||
| 70 | + let bytes = std::fs::read(path).expect("read fixture"); | ||
| 71 | + let mut reader = match FlacReader::new(&bytes) { | ||
| 72 | + Ok(r) => r, | ||
| 73 | + Err(e) => { | ||
| 74 | + failures.push(format!("{}: open failed: {e}", name(path))); | ||
| 75 | + continue; | ||
| 76 | + } | ||
| 77 | + }; | ||
| 78 | + let info = reader.stream_info().cloned(); | ||
| 79 | + let decoded = match reader.decode_all() { | ||
| 80 | + Ok(d) => d, | ||
| 81 | + Err(e) => { | ||
| 82 | + failures.push(format!("{}: decode failed: {e}", name(path))); | ||
| 83 | + continue; | ||
| 84 | + } | ||
| 85 | + }; | ||
| 86 | + let ours = decoded.to_pcm_bytes(); | ||
| 87 | + let theirs = match ffmpeg_pcm(path, decoded.bits_per_sample) { | ||
| 88 | + Ok(p) => p, | ||
| 89 | + Err(e) => { | ||
| 90 | + failures.push(format!("{}: ffmpeg failed: {e}", name(path))); | ||
| 91 | + continue; | ||
| 92 | + } | ||
| 93 | + }; | ||
| 94 | + if ours != theirs { | ||
| 95 | + let at = ours | ||
| 96 | + .iter() | ||
| 97 | + .zip(&theirs) | ||
| 98 | + .position(|(a, b)| a != b) | ||
| 99 | + .map_or_else(|| "length only".to_string(), |i| format!("byte {i}")); | ||
| 100 | + failures.push(format!( | ||
| 101 | + "{}: differs at {at} ({} vs {} bytes)", | ||
| 102 | + name(path), | ||
| 103 | + ours.len(), | ||
| 104 | + theirs.len() | ||
| 105 | + )); | ||
| 106 | + continue; | ||
| 107 | + } | ||
| 108 | + // Every subset file states an MD5; it must match what we decoded. | ||
| 109 | + if let Some(info) = &info | ||
| 110 | + && info.md5 != [0; 16] | ||
| 111 | + { | ||
| 112 | + let ours = md5_of_samples(&decoded.interleaved(), decoded.bits_per_sample); | ||
| 113 | + if ours != info.md5 { | ||
| 114 | + failures.push(format!("{}: STREAMINFO MD5 mismatch", name(path))); | ||
| 115 | + continue; | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | + passed += 1; | ||
| 119 | + println!( | ||
| 120 | + "PASS {:<70} {}ch {}bit {}Hz {} samples", | ||
| 121 | + name(path), | ||
| 122 | + decoded.channels.len(), | ||
| 123 | + decoded.bits_per_sample, | ||
| 124 | + decoded.sample_rate, | ||
| 125 | + decoded.len() | ||
| 126 | + ); | ||
| 127 | + } | ||
| 128 | + println!("subset: {passed}/{} bit-exact vs ffmpeg", files.len()); | ||
| 129 | + assert!(failures.is_empty(), "{}", failures.join("\n")); | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +#[test] | ||
| 133 | +fn uncommon_vectors_decode_bit_exact_or_refuse_by_name() { | ||
| 134 | + let Some(files) = corpus("uncommon") else { | ||
| 135 | + eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); | ||
| 136 | + return; | ||
| 137 | + }; | ||
| 138 | + let mut failures = Vec::new(); | ||
| 139 | + for path in &files { | ||
| 140 | + let bytes = std::fs::read(path).expect("read fixture"); | ||
| 141 | + let outcome = FlacReader::new(&bytes).and_then(|mut r| r.decode_all()); | ||
| 142 | + match outcome { | ||
| 143 | + Ok(decoded) => { | ||
| 144 | + let ours = decoded.to_pcm_bytes(); | ||
| 145 | + match ffmpeg_pcm(path, decoded.bits_per_sample) { | ||
| 146 | + Ok(theirs) if theirs == ours => { | ||
| 147 | + println!("PASS {:<50} bit-exact", name(path)); | ||
| 148 | + } | ||
| 149 | + Ok(theirs) => failures.push(format!( | ||
| 150 | + "{}: differs from ffmpeg ({} vs {} bytes)", | ||
| 151 | + name(path), | ||
| 152 | + ours.len(), | ||
| 153 | + theirs.len() | ||
| 154 | + )), | ||
| 155 | + Err(e) => failures.push(format!("{}: ffmpeg failed: {e}", name(path))), | ||
| 156 | + } | ||
| 157 | + } | ||
| 158 | + // A stream that changes channel count, depth or rate mid-way has no | ||
| 159 | + // single PCM shape to answer with; refusing it by name is the | ||
| 160 | + // contract (`Error::Unsupported` states what and why). | ||
| 161 | + Err(e) => println!("REFUSED {:<46} {e}", name(path)), | ||
| 162 | + } | ||
| 163 | + } | ||
| 164 | + assert!(failures.is_empty(), "{}", failures.join("\n")); | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +#[test] | ||
| 168 | +fn faulty_vectors_error_and_never_panic() { | ||
| 169 | + let Some(files) = corpus("faulty") else { | ||
| 170 | + eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); | ||
| 171 | + return; | ||
| 172 | + }; | ||
| 173 | + // Faults our reader is expected to catch outright rather than decode past: | ||
| 174 | + // these break the structure a decoder must trust. | ||
| 175 | + let must_reject = ["06 - ", "07 - ", "08 - ", "09 - ", "11 - "]; | ||
| 176 | + let mut failures = Vec::new(); | ||
| 177 | + for path in &files { | ||
| 178 | + let bytes = std::fs::read(path).expect("read fixture"); | ||
| 179 | + let outcome = FlacReader::new(&bytes).and_then(|mut r| r.decode_all()); | ||
| 180 | + let file = name(path); | ||
| 181 | + let rejected = outcome.is_err(); | ||
| 182 | + match &outcome { | ||
| 183 | + Ok(d) => println!("DECODED {file:<58} {} samples", d.len()), | ||
| 184 | + Err(e) => println!("ERROR {file:<58} {e}"), | ||
| 185 | + } | ||
| 186 | + if must_reject.iter().any(|p| file.starts_with(p)) && !rejected { | ||
| 187 | + failures.push(format!("{file}: decoded a structurally broken stream")); | ||
| 188 | + } | ||
| 189 | + } | ||
| 190 | + assert!(failures.is_empty(), "{}", failures.join("\n")); | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +#[test] | ||
| 194 | +fn seek_table_positions_the_reader_at_a_frame() { | ||
| 195 | + let Some(files) = corpus("subset") else { | ||
| 196 | + eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); | ||
| 197 | + return; | ||
| 198 | + }; | ||
| 199 | + // "48 - Extremely large SEEKTABLE" is the file with a seek table worth | ||
| 200 | + // exercising; any file carrying one proves the hook. | ||
| 201 | + let mut checked = 0; | ||
| 202 | + for path in files.iter() { | ||
| 203 | + let bytes = std::fs::read(path).expect("read fixture"); | ||
| 204 | + let mut reader = FlacReader::new(&bytes).expect("open"); | ||
| 205 | + if reader.seek_table().is_empty() { | ||
| 206 | + continue; | ||
| 207 | + } | ||
| 208 | + let target = reader.seek_table()[reader.seek_table().len() / 2]; | ||
| 209 | + let landed = reader.seek_to_sample(target.sample + 1); | ||
| 210 | + assert_eq!(landed, target.sample, "{}", name(path)); | ||
| 211 | + let mut block = ec_flac::decode::Block::default(); | ||
| 212 | + assert!( | ||
| 213 | + reader.next_block(&mut block).expect("frame"), | ||
| 214 | + "{}", | ||
| 215 | + name(path) | ||
| 216 | + ); | ||
| 217 | + assert_eq!( | ||
| 218 | + block.len(), | ||
| 219 | + usize::from(target.frame_samples), | ||
| 220 | + "{}", | ||
| 221 | + name(path) | ||
| 222 | + ); | ||
| 223 | + checked += 1; | ||
| 224 | + if checked == 3 { | ||
| 225 | + break; | ||
| 226 | + } | ||
| 227 | + } | ||
| 228 | + println!("seek: {checked} files with a seek table exercised"); | ||
| 229 | +} | ||
shims/flacenc/Cargo.tomladded+11 -0
| @@ -0,0 +1,11 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "flacenc" | ||
| 3 | +description = "Compatibility shim: the flacenc 0.5.1 surface edith consumes, served by ec-flac." | ||
| 4 | +version = "0.5.1" | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | +publish = false | ||
| 9 | + | ||
| 10 | +[dependencies] | ||
| 11 | +ec-flac = { path = "../../crates/ec-flac", version = "0.1.0" } | ||
shims/flacenc/src/bitsink.rsadded+71 -0
| @@ -0,0 +1,71 @@ | |||
| 1 | +//! `flacenc::bitsink`: where a written stream lands. | ||
| 2 | + | ||
| 3 | +use std::convert::Infallible; | ||
| 4 | + | ||
| 5 | +/// Somewhere bits can be written. | ||
| 6 | +/// | ||
| 7 | +/// Only the part the replica needs: it constructs a [`ByteSink`], hands it to | ||
| 8 | +/// `Stream::write` and reads the bytes back. | ||
| 9 | +pub trait BitSink: Sized { | ||
| 10 | + /// What writing can fail with. | ||
| 11 | + type Error: std::error::Error; | ||
| 12 | + | ||
| 13 | + /// Append whole bytes. | ||
| 14 | + fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Self::Error>; | ||
| 15 | + | ||
| 16 | + /// Bits written so far. | ||
| 17 | + fn bit_len(&self) -> usize; | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +/// A `Vec<u8>` sink — `flacenc::bitsink::ByteSink`. | ||
| 21 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] | ||
| 22 | +pub struct ByteSink { | ||
| 23 | + storage: Vec<u8>, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +impl ByteSink { | ||
| 27 | + /// An empty sink. | ||
| 28 | + pub fn new() -> Self { | ||
| 29 | + ByteSink::default() | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + /// An empty sink with room for `bits`. | ||
| 33 | + pub fn with_capacity(bits: usize) -> Self { | ||
| 34 | + ByteSink { | ||
| 35 | + storage: Vec::with_capacity(bits.div_ceil(8)), | ||
| 36 | + } | ||
| 37 | + } | ||
| 38 | + | ||
| 39 | + /// The bytes written so far. | ||
| 40 | + pub fn as_slice(&self) -> &[u8] { | ||
| 41 | + &self.storage | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + /// Take the bytes. | ||
| 45 | + pub fn into_inner(self) -> Vec<u8> { | ||
| 46 | + self.storage | ||
| 47 | + } | ||
| 48 | + | ||
| 49 | + /// Bytes written so far. | ||
| 50 | + pub fn len(&self) -> usize { | ||
| 51 | + self.storage.len() | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + /// True when nothing has been written. | ||
| 55 | + pub fn is_empty(&self) -> bool { | ||
| 56 | + self.storage.is_empty() | ||
| 57 | + } | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +impl BitSink for ByteSink { | ||
| 61 | + type Error = Infallible; | ||
| 62 | + | ||
| 63 | + fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), Infallible> { | ||
| 64 | + self.storage.extend_from_slice(bytes); | ||
| 65 | + Ok(()) | ||
| 66 | + } | ||
| 67 | + | ||
| 68 | + fn bit_len(&self) -> usize { | ||
| 69 | + self.storage.len() * 8 | ||
| 70 | + } | ||
| 71 | +} | ||
shims/flacenc/src/component.rsadded+112 -0
| @@ -0,0 +1,112 @@ | |||
| 1 | +//! `flacenc::component`: the encoded stream and its `STREAMINFO`. | ||
| 2 | +//! | ||
| 3 | +//! The incumbent models every FLAC component as an addressable value and | ||
| 4 | +//! writes them out on demand. Ours holds the encoded bytes and the header | ||
| 5 | +//! fields a caller is allowed to correct afterwards — which is the whole of | ||
| 6 | +//! what the replica does with the tree. | ||
| 7 | + | ||
| 8 | +use crate::bitsink::BitSink; | ||
| 9 | +use crate::error::{OutputError, VerifyError}; | ||
| 10 | + | ||
| 11 | +/// Something that can state its size and write itself to a [`BitSink`]. | ||
| 12 | +pub trait BitRepr { | ||
| 13 | + /// Bits this component occupies. | ||
| 14 | + fn count_bits(&self) -> usize; | ||
| 15 | + | ||
| 16 | + /// Write the component out. | ||
| 17 | + /// | ||
| 18 | + /// # Errors | ||
| 19 | + /// When the sink fails, or the component holds a value FLAC cannot express. | ||
| 20 | + fn write<S: BitSink>(&self, dest: &mut S) -> Result<(), OutputError<S>>; | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +/// A complete encoded FLAC stream. | ||
| 24 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 25 | +pub struct Stream { | ||
| 26 | + bytes: Vec<u8>, | ||
| 27 | + stream_info: StreamInfo, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/// Offset of the `STREAMINFO` payload: `fLaC` plus the 4-byte block header. | ||
| 31 | +const STREAM_INFO_AT: usize = 8; | ||
| 32 | + | ||
| 33 | +impl Stream { | ||
| 34 | + pub(crate) fn from_bytes(bytes: Vec<u8>) -> Stream { | ||
| 35 | + let min = u16::from_be_bytes([bytes[STREAM_INFO_AT], bytes[STREAM_INFO_AT + 1]]); | ||
| 36 | + let max = u16::from_be_bytes([bytes[STREAM_INFO_AT + 2], bytes[STREAM_INFO_AT + 3]]); | ||
| 37 | + Stream { | ||
| 38 | + bytes, | ||
| 39 | + stream_info: StreamInfo { | ||
| 40 | + min_block_size: min, | ||
| 41 | + max_block_size: max, | ||
| 42 | + }, | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /// The stream's `STREAMINFO`, mutable. | ||
| 47 | + pub fn stream_info_mut(&mut self) -> &mut StreamInfo { | ||
| 48 | + &mut self.stream_info | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + /// The stream's `STREAMINFO`. | ||
| 52 | + pub fn stream_info(&self) -> &StreamInfo { | ||
| 53 | + &self.stream_info | ||
| 54 | + } | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +impl BitRepr for Stream { | ||
| 58 | + fn count_bits(&self) -> usize { | ||
| 59 | + self.bytes.len() * 8 | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + fn write<S: BitSink>(&self, dest: &mut S) -> Result<(), OutputError<S>> { | ||
| 63 | + // The declared block sizes are the one field a caller may have changed | ||
| 64 | + // after encoding, so they are patched in on the way out. | ||
| 65 | + let mut bytes = self.bytes.clone(); | ||
| 66 | + bytes[STREAM_INFO_AT..STREAM_INFO_AT + 2] | ||
| 67 | + .copy_from_slice(&self.stream_info.min_block_size.to_be_bytes()); | ||
| 68 | + bytes[STREAM_INFO_AT + 2..STREAM_INFO_AT + 4] | ||
| 69 | + .copy_from_slice(&self.stream_info.max_block_size.to_be_bytes()); | ||
| 70 | + dest.write_bytes(&bytes) | ||
| 71 | + .map_err(|e| OutputError::new(e.to_string())) | ||
| 72 | + } | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/// The `STREAMINFO` fields a caller may correct after encoding. | ||
| 76 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 77 | +pub struct StreamInfo { | ||
| 78 | + min_block_size: u16, | ||
| 79 | + max_block_size: u16, | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +impl StreamInfo { | ||
| 83 | + /// State the stream's block sizes. | ||
| 84 | + /// | ||
| 85 | + /// # Errors | ||
| 86 | + /// When either value is not a legal block size. | ||
| 87 | + pub fn set_block_sizes( | ||
| 88 | + &mut self, | ||
| 89 | + min_value: usize, | ||
| 90 | + max_value: usize, | ||
| 91 | + ) -> Result<(), VerifyError> { | ||
| 92 | + self.min_block_size = u16::try_from(min_value) | ||
| 93 | + .ok() | ||
| 94 | + .filter(|&n| n >= 16) | ||
| 95 | + .ok_or_else(|| VerifyError::new("min_block_size", "must be a valid block size."))?; | ||
| 96 | + self.max_block_size = u16::try_from(max_value) | ||
| 97 | + .ok() | ||
| 98 | + .filter(|&n| n >= 16) | ||
| 99 | + .ok_or_else(|| VerifyError::new("max_block_size", "must be a valid block size."))?; | ||
| 100 | + Ok(()) | ||
| 101 | + } | ||
| 102 | + | ||
| 103 | + /// Smallest block size stated by the stream. | ||
| 104 | + pub fn min_block_size(&self) -> usize { | ||
| 105 | + usize::from(self.min_block_size) | ||
| 106 | + } | ||
| 107 | + | ||
| 108 | + /// Largest block size stated by the stream. | ||
| 109 | + pub fn max_block_size(&self) -> usize { | ||
| 110 | + usize::from(self.max_block_size) | ||
| 111 | + } | ||
| 112 | +} | ||
shims/flacenc/src/config.rsadded+92 -0
| @@ -0,0 +1,92 @@ | |||
| 1 | +//! `flacenc::config`: the encoder configuration tree. | ||
| 2 | +//! | ||
| 3 | +//! The fields the replica reads (`block_size`) and the ones its `Default` | ||
| 4 | +//! walks are kept; the knobs that only steer the incumbent's own search | ||
| 5 | +//! (window functions, per-order caps) are not reproduced, because a value set | ||
| 6 | +//! there would silently do nothing. | ||
| 7 | + | ||
| 8 | +use crate::error::{Verify, VerifyError}; | ||
| 9 | + | ||
| 10 | +/// Encoder configuration — `flacenc::config::Encoder`. | ||
| 11 | +#[derive(Clone, Debug, PartialEq, Eq)] | ||
| 12 | +#[non_exhaustive] | ||
| 13 | +pub struct Encoder { | ||
| 14 | + /// Encoder block size. | ||
| 15 | + pub block_size: usize, | ||
| 16 | + /// Whether the encoder may use several threads. | ||
| 17 | + pub multithread: bool, | ||
| 18 | + /// Stereo coding switches. | ||
| 19 | + pub stereo_coding: StereoCoding, | ||
| 20 | + /// Per-channel coding switches. | ||
| 21 | + pub subframe_coding: SubFrameCoding, | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +impl Default for Encoder { | ||
| 25 | + fn default() -> Self { | ||
| 26 | + Encoder { | ||
| 27 | + block_size: 4096, | ||
| 28 | + multithread: false, | ||
| 29 | + stereo_coding: StereoCoding::default(), | ||
| 30 | + subframe_coding: SubFrameCoding::default(), | ||
| 31 | + } | ||
| 32 | + } | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +impl Verify for Encoder { | ||
| 36 | + fn verify(&self) -> Result<(), VerifyError> { | ||
| 37 | + if !(16..=65535).contains(&self.block_size) { | ||
| 38 | + return Err(VerifyError::new( | ||
| 39 | + "block_size", | ||
| 40 | + "must be in the range of 16..=65535.", | ||
| 41 | + )); | ||
| 42 | + } | ||
| 43 | + Ok(()) | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// Stereo coding switches — `flacenc::config::StereoCoding`. | ||
| 48 | +#[derive(Clone, Debug, PartialEq, Eq)] | ||
| 49 | +#[non_exhaustive] | ||
| 50 | +pub struct StereoCoding { | ||
| 51 | + /// Allow left/side coding. | ||
| 52 | + pub use_leftside: bool, | ||
| 53 | + /// Allow right/side coding. | ||
| 54 | + pub use_rightside: bool, | ||
| 55 | + /// Allow mid/side coding. | ||
| 56 | + pub use_midside: bool, | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +impl Default for StereoCoding { | ||
| 60 | + fn default() -> Self { | ||
| 61 | + StereoCoding { | ||
| 62 | + use_leftside: true, | ||
| 63 | + use_rightside: true, | ||
| 64 | + use_midside: true, | ||
| 65 | + } | ||
| 66 | + } | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/// Per-channel coding switches — `flacenc::config::SubFrameCoding`. | ||
| 70 | +/// | ||
| 71 | +/// Verbatim coding is deliberately not switchable: it is the representation | ||
| 72 | +/// that always exists, so turning it off could leave a signal unencodable. | ||
| 73 | +#[derive(Clone, Debug, PartialEq, Eq)] | ||
| 74 | +#[non_exhaustive] | ||
| 75 | +pub struct SubFrameCoding { | ||
| 76 | + /// Allow constant subframes. | ||
| 77 | + pub use_constant: bool, | ||
| 78 | + /// Allow fixed-predictor subframes. | ||
| 79 | + pub use_fixed: bool, | ||
| 80 | + /// Allow LPC subframes. | ||
| 81 | + pub use_lpc: bool, | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +impl Default for SubFrameCoding { | ||
| 85 | + fn default() -> Self { | ||
| 86 | + SubFrameCoding { | ||
| 87 | + use_constant: true, | ||
| 88 | + use_fixed: true, | ||
| 89 | + use_lpc: true, | ||
| 90 | + } | ||
| 91 | + } | ||
| 92 | +} | ||
shims/flacenc/src/error.rsadded+110 -0
| @@ -0,0 +1,110 @@ | |||
| 1 | +//! `flacenc::error`: verification wrappers and the error types the encoder | ||
| 2 | +//! hands back. | ||
| 3 | + | ||
| 4 | +use std::fmt; | ||
| 5 | +use std::marker::PhantomData; | ||
| 6 | + | ||
| 7 | +use crate::bitsink::BitSink; | ||
| 8 | + | ||
| 9 | +/// A value that has passed [`Verify::verify`]. | ||
| 10 | +/// | ||
| 11 | +/// Derefs to the value, which is how callers read `config.block_size` off a | ||
| 12 | +/// verified config. | ||
| 13 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 14 | +pub struct Verified<T>(T); | ||
| 15 | + | ||
| 16 | +impl<T> std::ops::Deref for Verified<T> { | ||
| 17 | + type Target = T; | ||
| 18 | + fn deref(&self) -> &T { | ||
| 19 | + &self.0 | ||
| 20 | + } | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +/// Configuration structs that can check their own consistency. | ||
| 24 | +pub trait Verify: Sized { | ||
| 25 | + /// Check every field; [`VerifyError`] names the first bad one. | ||
| 26 | + fn verify(&self) -> Result<(), VerifyError>; | ||
| 27 | + | ||
| 28 | + /// Wrap into [`Verified`], or hand the value back with the reason. | ||
| 29 | + fn into_verified(self) -> Result<Verified<Self>, (Self, VerifyError)> { | ||
| 30 | + match self.verify() { | ||
| 31 | + Ok(()) => Ok(Verified(self)), | ||
| 32 | + Err(e) => Err((self, e)), | ||
| 33 | + } | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// A configuration field that is out of range, with the path to it. | ||
| 38 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 39 | +pub struct VerifyError { | ||
| 40 | + components: Vec<String>, | ||
| 41 | + reason: String, | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +impl VerifyError { | ||
| 45 | + /// An error for an invalid field `component`. | ||
| 46 | + pub fn new(component: &str, reason: &str) -> Self { | ||
| 47 | + VerifyError { | ||
| 48 | + components: vec![component.to_owned()], | ||
| 49 | + reason: reason.to_owned(), | ||
| 50 | + } | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + /// Prefix the field path with an enclosing struct's field name. | ||
| 54 | + pub fn within(mut self, component: &str) -> Self { | ||
| 55 | + self.components.insert(0, component.to_owned()); | ||
| 56 | + self | ||
| 57 | + } | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +impl fmt::Display for VerifyError { | ||
| 61 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 62 | + write!( | ||
| 63 | + f, | ||
| 64 | + "verification error: `{}` is not valid. reason: {}", | ||
| 65 | + self.components.join("."), | ||
| 66 | + self.reason | ||
| 67 | + ) | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +impl std::error::Error for VerifyError {} | ||
| 72 | + | ||
| 73 | +/// Encoding failed: either the source or the configuration. | ||
| 74 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 75 | +pub struct EncodeError(pub(crate) String); | ||
| 76 | + | ||
| 77 | +impl fmt::Display for EncodeError { | ||
| 78 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 79 | + f.write_str(&self.0) | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +impl std::error::Error for EncodeError {} | ||
| 84 | + | ||
| 85 | +/// Writing a component to a [`BitSink`] failed. | ||
| 86 | +/// | ||
| 87 | +/// Generic over the sink, as the incumbent is, so `write` signatures match; our | ||
| 88 | +/// only sink is infallible, so this is never constructed in practice. | ||
| 89 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 90 | +pub struct OutputError<S: BitSink> { | ||
| 91 | + reason: String, | ||
| 92 | + sink: PhantomData<fn() -> S>, | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +impl<S: BitSink> OutputError<S> { | ||
| 96 | + pub(crate) fn new(reason: impl Into<String>) -> Self { | ||
| 97 | + OutputError { | ||
| 98 | + reason: reason.into(), | ||
| 99 | + sink: PhantomData, | ||
| 100 | + } | ||
| 101 | + } | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +impl<S: BitSink> fmt::Display for OutputError<S> { | ||
| 105 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 106 | + f.write_str(&self.reason) | ||
| 107 | + } | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +impl<S: BitSink + fmt::Debug> std::error::Error for OutputError<S> {} | ||
shims/flacenc/src/lib.rsadded+135 -0
| @@ -0,0 +1,135 @@ | |||
| 1 | +//! Drop-in replacement for the `flacenc` 0.5.1 surface the replica consumes, | ||
| 2 | +//! implemented over [`ec_flac`]. | ||
| 3 | +//! | ||
| 4 | +//! It carries the incumbent's package name and version so the swap is a | ||
| 5 | +//! `[patch.crates-io]` entry and nothing else. The scope is exactly the API | ||
| 6 | +//! `engine/src/export.rs` calls (`export.rs:67-68,2930-2954`): | ||
| 7 | +//! | ||
| 8 | +//! ```no_run | ||
| 9 | +//! use flacenc::component::BitRepr; | ||
| 10 | +//! use flacenc::error::Verify; | ||
| 11 | +//! | ||
| 12 | +//! let config = flacenc::config::Encoder::default().into_verified().unwrap(); | ||
| 13 | +//! let source = flacenc::source::MemSource::from_samples(&[0i32; 32], 2, 16, 44100); | ||
| 14 | +//! let mut stream = | ||
| 15 | +//! flacenc::encode_with_fixed_block_size(&config, source, config.block_size).unwrap(); | ||
| 16 | +//! stream | ||
| 17 | +//! .stream_info_mut() | ||
| 18 | +//! .set_block_sizes(config.block_size, config.block_size) | ||
| 19 | +//! .unwrap(); | ||
| 20 | +//! let mut sink = flacenc::bitsink::ByteSink::new(); | ||
| 21 | +//! stream.write(&mut sink).unwrap(); | ||
| 22 | +//! let _bytes: &[u8] = sink.as_slice(); | ||
| 23 | +//! ``` | ||
| 24 | +//! | ||
| 25 | +//! Signatures match the incumbent's (types, argument order, error shapes) so | ||
| 26 | +//! call sites compile unchanged; the implementation behind them is ours. | ||
| 27 | +//! Deliberately *not* covered: the `par` feature knobs, `serde` config | ||
| 28 | +//! round-tripping and the component tree (`Frame`/`SubFrame`/`Residual` as | ||
| 29 | +//! addressable values) — the replica constructs none of them. | ||
| 30 | + | ||
| 31 | +#![forbid(unsafe_code)] | ||
| 32 | +#![warn(missing_docs)] | ||
| 33 | + | ||
| 34 | +pub mod bitsink; | ||
| 35 | +pub mod component; | ||
| 36 | +pub mod config; | ||
| 37 | +pub mod error; | ||
| 38 | +pub mod source; | ||
| 39 | + | ||
| 40 | +pub use component::Stream; | ||
| 41 | +pub use error::EncodeError; | ||
| 42 | + | ||
| 43 | +use error::Verified; | ||
| 44 | +use source::Source; | ||
| 45 | + | ||
| 46 | +/// Encode `src` into a stream of fixed-size blocks. | ||
| 47 | +/// | ||
| 48 | +/// Mirrors `flacenc::encode_with_fixed_block_size`: the verified config, a | ||
| 49 | +/// source, and the block size (which the caller reads off the config). | ||
| 50 | +pub fn encode_with_fixed_block_size<T: Source>( | ||
| 51 | + config: &Verified<config::Encoder>, | ||
| 52 | + src: T, | ||
| 53 | + block_size: usize, | ||
| 54 | +) -> Result<Stream, EncodeError> { | ||
| 55 | + let encoder = ec_flac::EncoderConfig { | ||
| 56 | + block_size, | ||
| 57 | + stereo_decorrelation: config.stereo_coding.use_midside | ||
| 58 | + || config.stereo_coding.use_leftside | ||
| 59 | + || config.stereo_coding.use_rightside, | ||
| 60 | + ..ec_flac::EncoderConfig::default() | ||
| 61 | + }; | ||
| 62 | + let bytes = ec_flac::encode( | ||
| 63 | + &encoder, | ||
| 64 | + src.as_raw_slice(), | ||
| 65 | + src.channels(), | ||
| 66 | + src.bits_per_sample() as u32, | ||
| 67 | + src.sample_rate() as u32, | ||
| 68 | + ) | ||
| 69 | + .map_err(|e| EncodeError(e.to_string()))?; | ||
| 70 | + Ok(Stream::from_bytes(bytes)) | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +#[cfg(test)] | ||
| 74 | +mod tests { | ||
| 75 | + use super::*; | ||
| 76 | + use crate::component::BitRepr; | ||
| 77 | + use crate::error::Verify; | ||
| 78 | + | ||
| 79 | + /// The replica's own call sequence, verbatim from `export.rs:2994-3025`, | ||
| 80 | + /// with the result decoded back to prove it is a real FLAC stream. | ||
| 81 | + #[test] | ||
| 82 | + fn the_replica_call_sequence_produces_a_decodable_stream() { | ||
| 83 | + let samples: Vec<i32> = (0..8192) | ||
| 84 | + .map(|i| ((i as f64 * 0.07).sin() * 12000.0) as i32) | ||
| 85 | + .collect(); | ||
| 86 | + | ||
| 87 | + let config = config::Encoder::default() | ||
| 88 | + .into_verified() | ||
| 89 | + .map_err(|(_, e)| format!("flac encoder config: {e}")) | ||
| 90 | + .unwrap(); | ||
| 91 | + let source = source::MemSource::from_samples(&samples, 2, 16, 44100); | ||
| 92 | + let mut stream = encode_with_fixed_block_size(&config, source, config.block_size) | ||
| 93 | + .map_err(|e| format!("flac encode: {e}")) | ||
| 94 | + .unwrap(); | ||
| 95 | + stream | ||
| 96 | + .stream_info_mut() | ||
| 97 | + .set_block_sizes(config.block_size, config.block_size) | ||
| 98 | + .map_err(|e| format!("flac block size: {e}")) | ||
| 99 | + .unwrap(); | ||
| 100 | + let mut sink = bitsink::ByteSink::new(); | ||
| 101 | + stream | ||
| 102 | + .write(&mut sink) | ||
| 103 | + .map_err(|e| format!("flac write: {e}")) | ||
| 104 | + .unwrap(); | ||
| 105 | + | ||
| 106 | + let bytes = sink.as_slice(); | ||
| 107 | + assert_eq!(&bytes[..4], b"fLaC"); | ||
| 108 | + assert_eq!(stream.count_bits(), bytes.len() * 8); | ||
| 109 | + let mut reader = ec_flac::FlacReader::new(bytes).expect("our own output opens"); | ||
| 110 | + let info = reader.stream_info().expect("streaminfo").clone(); | ||
| 111 | + assert_eq!(info.min_block_size, config.block_size as u16); | ||
| 112 | + assert_eq!(info.max_block_size, config.block_size as u16); | ||
| 113 | + let decoded = reader.decode_all().expect("decode"); | ||
| 114 | + assert_eq!(decoded.interleaved(), samples, "the shim must be lossless"); | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + #[test] | ||
| 118 | + fn a_block_size_the_stream_cannot_hold_is_an_error_not_a_panic() { | ||
| 119 | + let config = config::Encoder::default().into_verified().unwrap(); | ||
| 120 | + let source = source::MemSource::from_samples(&[0i32; 64], 2, 16, 44100); | ||
| 121 | + let mut stream = encode_with_fixed_block_size(&config, source, 32).unwrap(); | ||
| 122 | + assert!(stream.stream_info_mut().set_block_sizes(0, 70000).is_err()); | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + #[test] | ||
| 126 | + fn an_invalid_config_is_refused_with_its_original_value() { | ||
| 127 | + let config = config::Encoder { | ||
| 128 | + block_size: 4, | ||
| 129 | + ..config::Encoder::default() | ||
| 130 | + }; | ||
| 131 | + let (returned, error) = config.into_verified().unwrap_err(); | ||
| 132 | + assert_eq!(returned.block_size, 4); | ||
| 133 | + assert!(format!("{error}").contains("block_size")); | ||
| 134 | + } | ||
| 135 | +} | ||
shims/flacenc/src/source.rsadded+79 -0
| @@ -0,0 +1,79 @@ | |||
| 1 | +//! `flacenc::source`: where samples come from. | ||
| 2 | + | ||
| 3 | +/// A signal the encoder can read. | ||
| 4 | +/// | ||
| 5 | +/// The incumbent's trait is a pull interface with a reusable context; the | ||
| 6 | +/// replica only ever hands over a [`MemSource`] it built from a `Vec`, so this | ||
| 7 | +/// is the whole-buffer shape of the same thing. | ||
| 8 | +pub trait Source { | ||
| 9 | + /// Channel count. | ||
| 10 | + fn channels(&self) -> usize; | ||
| 11 | + /// Bits per sample. | ||
| 12 | + fn bits_per_sample(&self) -> usize; | ||
| 13 | + /// Sample rate in Hz. | ||
| 14 | + fn sample_rate(&self) -> usize; | ||
| 15 | + /// The interleaved samples. | ||
| 16 | + fn as_raw_slice(&self) -> &[i32]; | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +/// Samples already in memory — `flacenc::source::MemSource`. | ||
| 20 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 21 | +pub struct MemSource { | ||
| 22 | + channels: usize, | ||
| 23 | + bits_per_sample: usize, | ||
| 24 | + sample_rate: usize, | ||
| 25 | + samples: Vec<i32>, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +impl MemSource { | ||
| 29 | + /// Build from interleaved samples. | ||
| 30 | + pub fn from_samples( | ||
| 31 | + samples: &[i32], | ||
| 32 | + channels: usize, | ||
| 33 | + bits_per_sample: usize, | ||
| 34 | + sample_rate: usize, | ||
| 35 | + ) -> Self { | ||
| 36 | + MemSource { | ||
| 37 | + channels, | ||
| 38 | + bits_per_sample, | ||
| 39 | + sample_rate, | ||
| 40 | + samples: samples.to_owned(), | ||
| 41 | + } | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + /// The samples, interleaved. | ||
| 45 | + pub fn as_raw_slice(&self) -> &[i32] { | ||
| 46 | + &self.samples | ||
| 47 | + } | ||
| 48 | + | ||
| 49 | + /// Inter-channel samples held. | ||
| 50 | + pub fn len(&self) -> usize { | ||
| 51 | + match self.channels { | ||
| 52 | + 0 => 0, | ||
| 53 | + n => self.samples.len() / n, | ||
| 54 | + } | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + /// True when the source holds no samples. | ||
| 58 | + pub fn is_empty(&self) -> bool { | ||
| 59 | + self.samples.is_empty() | ||
| 60 | + } | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +impl Source for MemSource { | ||
| 64 | + fn channels(&self) -> usize { | ||
| 65 | + self.channels | ||
| 66 | + } | ||
| 67 | + | ||
| 68 | + fn bits_per_sample(&self) -> usize { | ||
| 69 | + self.bits_per_sample | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + fn sample_rate(&self) -> usize { | ||
| 73 | + self.sample_rate | ||
| 74 | + } | ||
| 75 | + | ||
| 76 | + fn as_raw_slice(&self) -> &[i32] { | ||
| 77 | + &self.samples | ||
| 78 | + } | ||
| 79 | +} | ||