Repository Public
1//! ORIX Sonata2//! File: crates/sonata-render/src/flac.rs3//! Description: FLAC encoder (fixed predictors, partitioned Rice coding, stereo decorrelation,4//! MD5 signature) and a complete decoder for the FLAC subset (constant, verbatim, fixed and LPC5//! subframes; all stereo modes), with CRC and MD5 verification.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use crate::md5::Md5;1112const BLOCK: usize = 4096;1314fn crc8(data: &[u8]) -> u8 {15 let mut c = 0u8;16 for &b in data {17 c ^= b;18 for _ in 0..8 {19 c = if c & 0x80 != 0 { (c << 1) ^ 0x07 } else { c << 1 };20 }21 }22 c23}2425fn crc16(data: &[u8]) -> u16 {26 let mut c = 0u16;27 for &b in data {28 c ^= (b as u16) << 8;29 for _ in 0..8 {30 c = if c & 0x8000 != 0 { (c << 1) ^ 0x8005 } else { c << 1 };31 }32 }33 c34}3536struct BitWriter {37 out: Vec<u8>,38 acc: u64,39 bits: u32,40}4142impl BitWriter {43 fn new() -> BitWriter {44 BitWriter { out: Vec::new(), acc: 0, bits: 0 }45 }46 fn put(&mut self, value: u64, n: u32) {47 debug_assert!(n <= 32);48 if n == 0 {49 return;50 }51 self.acc = (self.acc << n) | (value & ((1u64 << n) - 1));52 self.bits += n;53 while self.bits >= 8 {54 self.bits -= 8;55 self.out.push((self.acc >> self.bits) as u8);56 }57 }58 fn put_signed(&mut self, value: i64, n: u32) {59 self.put(value as u64, n.min(32));60 }61 fn unary(&mut self, mut q: u32) {62 while q >= 32 {63 self.put(0, 32);64 q -= 32;65 }66 self.put(1, q + 1);67 }68 fn align(&mut self) {69 if self.bits > 0 {70 let pad = 8 - self.bits;71 self.put(0, pad);72 }73 }74}7576fn fixed_residual(x: &[i64], order: usize, out: &mut Vec<i64>) {77 out.clear();78 for i in order..x.len() {79 out.push(match order {80 0 => x[i],81 1 => x[i] - x[i - 1],82 2 => x[i] - 2 * x[i - 1] + x[i - 2],83 3 => x[i] - 3 * x[i - 1] + 3 * x[i - 2] - x[i - 3],84 _ => x[i] - 4 * x[i - 1] + 6 * x[i - 2] - 4 * x[i - 3] + x[i - 4],85 });86 }87}8889#[inline]90fn zigzag(r: i64) -> u64 {91 ((r << 1) ^ (r >> 63)) as u6492}9394/// Bits needed to Rice-code `res` with parameter `k`.95fn rice_bits(res: &[i64], k: u32) -> u64 {96 res.iter().map(|r| (zigzag(*r) >> k) + 1 + k as u64).sum()97}9899fn best_rice(res: &[i64], max_k: u32) -> (u32, u64) {100 if res.is_empty() {101 return (0, 0);102 }103 let mean = res.iter().map(|r| zigzag(*r)).sum::<u64>() / res.len() as u64;104 let guess = (64 - mean.leading_zeros()).saturating_sub(1).min(max_k);105 let mut best = (guess, rice_bits(res, guess));106 for k in [guess.saturating_sub(1), (guess + 1).min(max_k)] {107 let b = rice_bits(res, k);108 if b < best.1 {109 best = (k, b);110 }111 }112 best113}114115/// Channel assignment code, one plan per subframe, and the samples (with their bit depth) each codes.116type Planned = (u64, Vec<Subframe>, Vec<(Vec<i64>, u32)>);117118struct Subframe {119 bits: u64,120 order: Option<usize>, // None = verbatim121 part_order: u32,122 params: Vec<u32>,123 constant: bool,124}125126fn plan_subframe(x: &[i64], bps: u32, scratch: &mut Vec<i64>) -> Subframe {127 let n = x.len();128 if x.iter().all(|v| *v == x[0]) {129 return Subframe { bits: 8 + bps as u64, order: None, part_order: 0, params: vec![], constant: true };130 }131 let max_k = if bps > 16 { 30 } else { 14 };132 let param_bits = if bps > 16 { 5 } else { 4 };133 let mut best = Subframe { bits: 8 + bps as u64 * n as u64, order: None, part_order: 0, params: vec![], constant: false };134 for order in 0..=4usize.min(n.saturating_sub(1)) {135 fixed_residual(x, order, scratch);136 if scratch.iter().any(|r| r.unsigned_abs() >= 1 << 31) {137 continue;138 }139 // Partition orders: the block must divide evenly and the first partition must hold the warm-up.140 let mut po = 0u32;141 loop {142 let parts = 1usize << po;143 if !n.is_multiple_of(parts) || n / parts <= order {144 break;145 }146 let mut bits = 8 + (order as u64) * bps as u64 + 6;147 let mut params = Vec::with_capacity(parts);148 for p in 0..parts {149 let a = if p == 0 { 0 } else { p * (n / parts) - order };150 let b = (p + 1) * (n / parts) - order;151 let (k, kb) = best_rice(&scratch[a..b], max_k);152 bits += param_bits + kb;153 params.push(k);154 }155 if bits < best.bits {156 best = Subframe { bits, order: Some(order), part_order: po, params, constant: false };157 }158 po += 1;159 if po > 6 {160 break;161 }162 }163 }164 best165}166167fn write_subframe(w: &mut BitWriter, x: &[i64], bps: u32, plan: &Subframe, scratch: &mut Vec<i64>) {168 if plan.constant {169 w.put(0b0000_0000, 8);170 w.put_signed(x[0], bps);171 return;172 }173 let Some(order) = plan.order else {174 w.put(0b0000_0010, 8);175 for v in x {176 w.put_signed(*v, bps);177 }178 return;179 };180 w.put(((0b001000 | order as u64) << 1) & 0x7e, 8);181 for v in &x[..order] {182 w.put_signed(*v, bps);183 }184 fixed_residual(x, order, scratch);185 let five = bps > 16;186 w.put(if five { 1 } else { 0 }, 2);187 w.put(plan.part_order as u64, 4);188 let parts = 1usize << plan.part_order;189 let n = x.len();190 for p in 0..parts {191 let a = if p == 0 { 0 } else { p * (n / parts) - order };192 let b = (p + 1) * (n / parts) - order;193 let k = plan.params[p];194 w.put(k as u64, if five { 5 } else { 4 });195 for r in &scratch[a..b] {196 let u = zigzag(*r);197 w.unary((u >> k) as u32);198 w.put(u, k);199 }200 }201}202203fn utf8_number(mut v: u64, out: &mut Vec<u8>) {204 if v < 0x80 {205 out.push(v as u8);206 return;207 }208 let mut tail = [0u8; 6];209 let mut n = 0;210 let mut lead_bits = 6;211 while v >= (1 << lead_bits) {212 tail[n] = 0x80 | (v & 0x3f) as u8;213 v >>= 6;214 n += 1;215 lead_bits -= 1;216 }217 out.push((0xffu16 << (lead_bits + 1)) as u8 | v as u8);218 for i in (0..n).rev() {219 out.push(tail[i]);220 }221}222223/// Encodes interleaved-by-channel integer PCM (`channels[c][frame]`, values within `bits` bits224/// signed) as a FLAC stream. `bits` is 16 or 24; 1 or 2 channels; sample rate up to 655350 Hz.225pub fn encode(channels: &[Vec<i32>], sample_rate: u32, bits: u32) -> Result<Vec<u8>, String> {226 let nch = channels.len();227 if !(1..=2).contains(&nch) {228 return Err("the FLAC writer supports one or two channels".into());229 }230 if bits != 16 && bits != 24 {231 return Err("the FLAC writer supports 16 or 24 bits per sample".into());232 }233 if sample_rate == 0 || sample_rate > 655_350 {234 return Err(format!("sample rate {sample_rate} Hz cannot be stored in FLAC"));235 }236 let frames = channels[0].len();237 if channels.iter().any(|c| c.len() != frames) {238 return Err("channels have different lengths".into());239 }240 if frames as u64 >= 1 << 36 {241 return Err("too many samples for a FLAC stream".into());242 }243 let (lo, hi) = (-(1i32 << (bits - 1)), (1i32 << (bits - 1)) - 1);244 if channels.iter().any(|c| c.iter().any(|v| *v < lo || *v > hi)) {245 return Err(format!("a sample does not fit {bits} bits"));246 }247248 let mut md5 = Md5::new();249 let bytes = (bits / 8) as usize;250 let mut raw = Vec::with_capacity(BLOCK * nch * bytes);251 let mut body: Vec<u8> = Vec::new();252 let (mut min_frame, mut max_frame) = (u32::MAX, 0u32);253 let mut scratch = Vec::with_capacity(BLOCK);254 let rate_code: u64 = match sample_rate {255 88_200 => 1,256 176_400 => 2,257 192_000 => 3,258 8_000 => 4,259 16_000 => 5,260 22_050 => 6,261 24_000 => 7,262 32_000 => 8,263 44_100 => 9,264 48_000 => 10,265 96_000 => 11,266 _ => 0,267 };268 let size_code: u64 = if bits == 16 { 4 } else { 6 };269 let mut start = 0;270 let mut frame_no = 0u64;271 while start < frames {272 let n = BLOCK.min(frames - start);273 raw.clear();274 for i in start..start + n {275 for c in channels {276 raw.extend_from_slice(&c[i].to_le_bytes()[..bytes]);277 }278 }279 md5.update(&raw);280281 let ch: Vec<Vec<i64>> = channels.iter().map(|c| c[start..start + n].iter().map(|v| *v as i64).collect()).collect();282 let mut header = vec![0xff, 0xf8];283 let block_code: u64 = if n == 4096 {284 12285 } else if n <= 256 {286 6287 } else {288 7289 };290 // Choose between independent and mid/side coding for stereo.291 let (assignment, subs, data): Planned = if nch == 2 {292 let mid: Vec<i64> = ch[0].iter().zip(&ch[1]).map(|(l, r)| (l + r) >> 1).collect();293 let side: Vec<i64> = ch[0].iter().zip(&ch[1]).map(|(l, r)| l - r).collect();294 let lr = [plan_subframe(&ch[0], bits, &mut scratch), plan_subframe(&ch[1], bits, &mut scratch)];295 let ms = [plan_subframe(&mid, bits, &mut scratch), plan_subframe(&side, bits + 1, &mut scratch)];296 if ms[0].bits + ms[1].bits < lr[0].bits + lr[1].bits {297 (10, ms.into_iter().collect(), vec![(mid, bits), (side, bits + 1)])298 } else {299 (1, lr.into_iter().collect(), vec![(ch[0].clone(), bits), (ch[1].clone(), bits)])300 }301 } else {302 (0, vec![plan_subframe(&ch[0], bits, &mut scratch)], vec![(ch[0].clone(), bits)])303 };304 header.push(((block_code << 4) | rate_code) as u8);305 header.push(((assignment << 4) | (size_code << 1)) as u8);306 utf8_number(frame_no, &mut header);307 if block_code == 6 {308 header.push((n - 1) as u8);309 } else if block_code == 7 {310 header.extend_from_slice(&((n - 1) as u16).to_be_bytes());311 }312 header.push(crc8(&header));313 let mut w = BitWriter::new();314 for (plan, (x, bps)) in subs.iter().zip(&data) {315 write_subframe(&mut w, x, *bps, plan, &mut scratch);316 }317 w.align();318 let mut frame = header;319 frame.extend_from_slice(&w.out);320 let crc = crc16(&frame);321 frame.extend_from_slice(&crc.to_be_bytes());322 min_frame = min_frame.min(frame.len() as u32);323 max_frame = max_frame.max(frame.len() as u32);324 body.extend_from_slice(&frame);325 start += n;326 frame_no += 1;327 }328 if frames == 0 {329 min_frame = 0;330 }331332 let mut out = Vec::with_capacity(body.len() + 42);333 out.extend_from_slice(b"fLaC");334 out.push(0x80); // last metadata block, type 0 (STREAMINFO)335 out.extend_from_slice(&[0, 0, 34]);336 let block = BLOCK.max(16) as u16;337 out.extend_from_slice(&block.to_be_bytes());338 out.extend_from_slice(&block.to_be_bytes());339 out.extend_from_slice(&min_frame.min(0xff_ffff).to_be_bytes()[1..]);340 out.extend_from_slice(&max_frame.min(0xff_ffff).to_be_bytes()[1..]);341 let packed: u64 = ((sample_rate as u64) << 44) | ((nch as u64 - 1) << 41) | ((bits as u64 - 1) << 36) | frames as u64;342 out.extend_from_slice(&packed.to_be_bytes());343 out.extend_from_slice(&md5.finish());344 out.extend_from_slice(&body);345 Ok(out)346}347348/// A decoded FLAC stream.349#[derive(Clone, Debug, PartialEq)]350pub struct Decoded {351 pub sample_rate: u32,352 pub bits: u32,353 pub channels: Vec<Vec<i32>>,354 /// True when the stream carried an MD5 signature and it matched the decoded audio.355 pub md5_verified: bool,356}357358struct BitReader<'a> {359 data: &'a [u8],360 pos: usize,361 bit: u32,362}363364impl<'a> BitReader<'a> {365 fn get(&mut self, n: u32) -> Result<u64, String> {366 let mut v = 0u64;367 for _ in 0..n {368 let byte = *self.data.get(self.pos).ok_or("unexpected end of FLAC data")?;369 v = (v << 1) | ((byte >> (7 - self.bit)) & 1) as u64;370 self.bit += 1;371 if self.bit == 8 {372 self.bit = 0;373 self.pos += 1;374 }375 }376 Ok(v)377 }378 fn signed(&mut self, n: u32) -> Result<i64, String> {379 let v = self.get(n)?;380 Ok(if n == 0 { 0 } else { ((v << (64 - n)) as i64) >> (64 - n) })381 }382 fn unary(&mut self) -> Result<u32, String> {383 let mut q = 0u32;384 while self.get(1)? == 0 {385 q += 1;386 if q > 1 << 24 {387 return Err("corrupt Rice code in FLAC data".into());388 }389 }390 Ok(q)391 }392 fn align(&mut self) {393 if self.bit != 0 {394 self.bit = 0;395 self.pos += 1;396 }397 }398}399400fn read_residual(r: &mut BitReader, order: usize, n: usize, out: &mut Vec<i64>) -> Result<(), String> {401 let method = r.get(2)?;402 if method > 1 {403 return Err("reserved residual coding method".into());404 }405 let pbits = if method == 0 { 4 } else { 5 };406 let escape = (1u64 << pbits) - 1;407 let po = r.get(4)? as u32;408 let parts = 1usize << po;409 if !n.is_multiple_of(parts) || (n >> po) < order {410 return Err("invalid Rice partition order".into());411 }412 for p in 0..parts {413 let count = if p == 0 { (n >> po) - order } else { n >> po };414 let k = r.get(pbits)?;415 if k == escape {416 let raw = r.get(5)? as u32;417 for _ in 0..count {418 out.push(r.signed(raw)?);419 }420 } else {421 for _ in 0..count {422 let q = r.unary()? as u64;423 let u = (q << k) | r.get(k as u32)?;424 out.push(((u >> 1) as i64) ^ -((u & 1) as i64));425 }426 }427 }428 Ok(())429}430431fn read_subframe(r: &mut BitReader, n: usize, bps: u32) -> Result<Vec<i64>, String> {432 if r.get(1)? != 0 {433 return Err("subframe padding bit is set".into());434 }435 let kind = r.get(6)?;436 let mut wasted = 0u32;437 if r.get(1)? == 1 {438 wasted = r.unary()? + 1;439 }440 if wasted >= bps {441 return Err("invalid wasted bits count".into());442 }443 let bps = bps - wasted;444 let mut x: Vec<i64> = Vec::with_capacity(n);445 match kind {446 0 => {447 let v = r.signed(bps)?;448 x.resize(n, v);449 }450 1 => {451 for _ in 0..n {452 x.push(r.signed(bps)?);453 }454 }455 8..=12 => {456 let order = (kind - 8) as usize;457 if order > n {458 return Err("fixed predictor order exceeds block size".into());459 }460 for _ in 0..order {461 x.push(r.signed(bps)?);462 }463 let mut res = Vec::with_capacity(n - order);464 read_residual(r, order, n, &mut res)?;465 for (j, e) in res.iter().enumerate() {466 let i = order + j;467 let p = match order {468 0 => 0,469 1 => x[i - 1],470 2 => 2 * x[i - 1] - x[i - 2],471 3 => 3 * x[i - 1] - 3 * x[i - 2] + x[i - 3],472 _ => 4 * x[i - 1] - 6 * x[i - 2] + 4 * x[i - 3] - x[i - 4],473 };474 x.push(p.wrapping_add(*e));475 }476 }477 32..=63 => {478 let order = (kind - 31) as usize;479 if order > n {480 return Err("LPC order exceeds block size".into());481 }482 for _ in 0..order {483 x.push(r.signed(bps)?);484 }485 let precision = r.get(4)? as u32 + 1;486 if precision == 16 {487 return Err("invalid LPC precision".into());488 }489 let shift = r.signed(5)?;490 if shift < 0 {491 return Err("negative LPC shift".into());492 }493 let mut coefs = Vec::with_capacity(order);494 for _ in 0..order {495 coefs.push(r.signed(precision)?);496 }497 let mut res = Vec::with_capacity(n - order);498 read_residual(r, order, n, &mut res)?;499 for (j, e) in res.iter().enumerate() {500 let i = order + j;501 let mut acc = 0i64;502 for (c, coef) in coefs.iter().enumerate() {503 acc = acc.wrapping_add(coef.wrapping_mul(x[i - 1 - c]));504 }505 x.push((acc >> shift).wrapping_add(*e));506 }507 }508 _ => return Err("reserved subframe type".into()),509 }510 if x.len() != n {511 return Err("subframe length mismatch".into());512 }513 if wasted > 0 {514 for v in &mut x {515 *v <<= wasted;516 }517 }518 Ok(x)519}520521/// Decodes a FLAC stream. Verifies every frame CRC, and the MD5 signature when present.522/// `max_frames` bounds the decoded length (a stream announcing more is rejected before any523/// allocation). Supports 1 to 8 channels and 8 to 24 bits per sample.524pub fn decode(data: &[u8], max_frames: u64) -> Result<Decoded, String> {525 if data.len() < 42 || &data[..4] != b"fLaC" {526 return Err("not a FLAC stream".into());527 }528 let mut pos = 4;529 let mut info: Option<(u32, usize, u32, u64, [u8; 16])> = None;530 loop {531 let head = data.get(pos..pos + 4).ok_or("truncated FLAC metadata")?;532 let (last, kind) = (head[0] & 0x80 != 0, head[0] & 0x7f);533 let len = u32::from_be_bytes([0, head[1], head[2], head[3]]) as usize;534 let block = data.get(pos + 4..pos + 4 + len).ok_or("truncated FLAC metadata block")?;535 if kind == 0 {536 if len != 34 {537 return Err("invalid STREAMINFO block".into());538 }539 let packed = u64::from_be_bytes(block[10..18].try_into().map_err(|_| "invalid STREAMINFO")?);540 let mut md5 = [0u8; 16];541 md5.copy_from_slice(&block[18..34]);542 info = Some(((packed >> 44) as u32, ((packed >> 41) & 7) as usize + 1, ((packed >> 36) & 31) as u32 + 1, packed & ((1 << 36) - 1), md5));543 }544 pos += 4 + len;545 if last {546 break;547 }548 }549 let (sample_rate, nch, bits, total, md5_want) = info.ok_or("FLAC stream has no STREAMINFO")?;550 if sample_rate == 0 || !(8..=24).contains(&bits) {551 return Err(format!("unsupported FLAC format: {sample_rate} Hz, {bits} bits"));552 }553 if total > max_frames {554 return Err(format!("FLAC stream holds {total} frames, more than the limit of {max_frames}"));555 }556 let mut channels: Vec<Vec<i32>> = (0..nch).map(|_| Vec::with_capacity(total as usize)).collect();557 while pos < data.len() {558 let start = pos;559 let h = data.get(pos..pos + 4).ok_or("truncated FLAC frame header")?;560 if h[0] != 0xff || h[1] & 0xfe != 0xf8 {561 return Err("lost synchronisation in FLAC stream".into());562 }563 let block_code = h[2] >> 4;564 let rate_code = h[2] & 15;565 let assignment = h[3] >> 4;566 let size_code = (h[3] >> 1) & 7;567 if h[3] & 1 != 0 || rate_code == 15 || size_code == 3 {568 return Err("reserved bits set in FLAC frame header".into());569 }570 pos += 4;571 // UTF-8 style frame or sample number.572 let lead = *data.get(pos).ok_or("truncated FLAC frame header")?;573 let extra = if lead < 0x80 { 0 } else { (lead.leading_ones() as usize).saturating_sub(1) };574 if lead.leading_ones() == 1 || extra > 6 {575 return Err("invalid frame number in FLAC stream".into());576 }577 pos += 1 + extra;578 let n = match block_code {579 0 => return Err("reserved block size".into()),580 1 => 192,581 2..=5 => 576usize << (block_code - 2),582 6 => {583 pos += 1;584 *data.get(pos - 1).ok_or("truncated FLAC frame header")? as usize + 1585 }586 7 => {587 pos += 2;588 u16::from_be_bytes([*data.get(pos - 2).ok_or("truncated")?, *data.get(pos - 1).ok_or("truncated")?]) as usize + 1589 }590 _ => 256usize << (block_code - 8),591 };592 pos += match rate_code {593 12 => 1,594 13 | 14 => 2,595 _ => 0,596 };597 let crc = *data.get(pos).ok_or("truncated FLAC frame header")?;598 if crc8(&data[start..pos]) != crc {599 return Err("FLAC frame header CRC mismatch".into());600 }601 pos += 1;602 let frame_bits = match size_code {603 0 => bits,604 1 => 8,605 2 => 12,606 4 => 16,607 5 => 20,608 6 => 24,609 _ => return Err("unsupported sample size in FLAC frame".into()),610 };611 if frame_bits != bits {612 return Err("FLAC stream changes sample size mid-stream".into());613 }614 let frame_ch = if assignment < 8 { assignment as usize + 1 } else { 2 };615 if assignment > 10 || frame_ch != nch {616 return Err("FLAC frame channel layout does not match the stream".into());617 }618 if channels[0].len() as u64 + n as u64 > max_frames.max(total) {619 return Err("FLAC stream is longer than announced".into());620 }621 let mut r = BitReader { data, pos, bit: 0 };622 let mut sub: Vec<Vec<i64>> = Vec::with_capacity(nch);623 for c in 0..nch {624 let side = matches!((assignment, c), (8, 1) | (9, 0) | (10, 1));625 sub.push(read_subframe(&mut r, n, bits + side as u32)?);626 }627 r.align();628 pos = r.pos;629 let want = u16::from_be_bytes([*data.get(pos).ok_or("truncated FLAC frame")?, *data.get(pos + 1).ok_or("truncated FLAC frame")?]);630 if crc16(&data[start..pos]) != want {631 return Err("FLAC frame CRC mismatch".into());632 }633 pos += 2;634 match assignment {635 8 => {636 for i in 0..n {637 sub[1][i] = sub[0][i] - sub[1][i];638 }639 }640 9 => {641 for i in 0..n {642 sub[0][i] += sub[1][i];643 }644 }645 10 => {646 for i in 0..n {647 let (m, s) = (sub[0][i], sub[1][i]);648 let m2 = (m << 1) | (s & 1);649 sub[0][i] = (m2 + s) >> 1;650 sub[1][i] = (m2 - s) >> 1;651 }652 }653 _ => {}654 }655 for (c, s) in sub.iter().enumerate() {656 channels[c].extend(s.iter().map(|v| *v as i32));657 }658 }659 if total != 0 && channels[0].len() as u64 != total {660 return Err(format!("FLAC stream announced {total} frames but holds {}", channels[0].len()));661 }662 let mut md5_verified = false;663 if md5_want != [0u8; 16] {664 let bytes = bits.div_ceil(8) as usize;665 let mut m = Md5::new();666 let mut raw = Vec::with_capacity(65_536);667 for i in 0..channels[0].len() {668 for c in &channels {669 raw.extend_from_slice(&c[i].to_le_bytes()[..bytes]);670 }671 if raw.len() >= 65_000 {672 m.update(&raw);673 raw.clear();674 }675 }676 m.update(&raw);677 if m.finish() != md5_want {678 return Err("FLAC MD5 signature does not match the decoded audio".into());679 }680 md5_verified = true;681 }682 Ok(Decoded { sample_rate, bits, channels, md5_verified })683}684685#[cfg(test)]686mod tests {687 use super::*;688689 fn signal(n: usize, bits: u32, seed: u64) -> Vec<i32> {690 let mut s = seed;691 let full = (1i64 << (bits - 1)) - 1;692 (0..n)693 .map(|i| {694 s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);695 let noise = ((s >> 40) as f64 / (1u64 << 24) as f64 - 0.5) * 0.02;696 let v = 0.6 * (i as f64 * 0.031).sin() + 0.3 * (i as f64 * 0.0007).sin() + noise;697 (v * full as f64) as i32698 })699 .collect()700 }701702 #[test]703 fn round_trip_is_lossless_for_every_layout() {704 for bits in [16u32, 24] {705 for nch in [1usize, 2] {706 for n in [0usize, 1, 5, 4095, 4096, 4097, 20_000] {707 let ch: Vec<Vec<i32>> = (0..nch).map(|c| signal(n, bits, 7 + c as u64)).collect();708 let enc = encode(&ch, 48_000, bits).unwrap();709 let dec = decode(&enc, 1 << 30).unwrap();710 assert_eq!(dec.channels, ch, "bits {bits} channels {nch} frames {n}");711 assert_eq!((dec.sample_rate, dec.bits, dec.md5_verified), (48_000, bits, true));712 }713 }714 }715 }716717 #[test]718 fn compresses_tonal_material_and_handles_extremes() {719 let ch = vec![signal(48_000, 16, 1), signal(48_000, 16, 1)];720 let enc = encode(&ch, 44_100, 16).unwrap();721 assert!(enc.len() < 48_000 * 4 * 6 / 10, "expected compression, got {} bytes", enc.len());722 // Identical channels: the side channel is zero, mid/side must be chosen.723 assert_eq!(decode(&enc, 1 << 30).unwrap().channels, ch);724 // Full-scale square wave, silence, alternating extremes (worst case for predictors).725 let extremes: Vec<i32> = (0..10_000).map(|i| if i % 2 == 0 { 32_767 } else { -32_768 }).collect();726 let square: Vec<i32> = (0..10_000).map(|i| if (i / 50) % 2 == 0 { 8_388_607 } else { -8_388_608 }).collect();727 for (x, bits) in [(extremes, 16), (square, 24), (vec![0; 10_000], 16), (vec![-5; 9_999], 24)] {728 let two = vec![x.clone(), x.iter().map(|v| -v.max(&-((1 << (bits - 1)) - 1))).collect()];729 let enc = encode(&two, 96_000, bits).unwrap();730 assert_eq!(decode(&enc, 1 << 30).unwrap().channels, two);731 }732 }733734 #[test]735 fn rejects_invalid_input_and_detects_corruption() {736 assert!(encode(&[vec![40_000]], 48_000, 16).is_err());737 assert!(encode(&[vec![0], vec![0, 0]], 48_000, 16).is_err());738 assert!(encode(&[vec![0]], 48_000, 20).is_err());739 assert!(encode(&[vec![0], vec![0], vec![0]], 48_000, 16).is_err());740 let ch = vec![signal(9000, 16, 3)];741 let enc = encode(&ch, 48_000, 16).unwrap();742 assert!(decode(&enc, 100).unwrap_err().contains("more than the limit"));743 assert!(decode(b"RIFFxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 1 << 20).is_err());744 assert!(decode(&enc[..enc.len() - 10], 1 << 20).is_err());745 for at in [50usize, 200, enc.len() / 2, enc.len() - 3] {746 let mut bad = enc.clone();747 bad[at] ^= 0x10;748 assert!(decode(&bad, 1 << 20).is_err(), "corruption at byte {at} went unnoticed");749 }750 }751752 #[test]753 fn frame_number_coding() {754 for (v, want) in [755 (0u64, vec![0u8]),756 (127, vec![0x7f]),757 (128, vec![0xc2, 0x80]),758 (2047, vec![0xdf, 0xbf]),759 (2048, vec![0xe0, 0xa0, 0x80]),760 (65_536, vec![0xf0, 0x90, 0x80, 0x80]),761 ] {762 let mut out = Vec::new();763 utf8_number(v, &mut out);764 assert_eq!(out, want, "{v}");765 }766 assert_eq!(crc8(b"123456789"), 0xf4);767 assert_eq!(crc16(b"123456789"), 0xfee8);768 }769}770