Merge branch 'alac-enc': ALAC encoder + decoder golomb escape fix
Browse files at this commit7 changed files +1055 -5
- Cargo.lock +1 -0
- crates/ec-alac/Cargo.toml +1 -0
- crates/ec-alac/src/decode.rs +8 -3
- crates/ec-alac/src/encode.rs +627 -0
- crates/ec-alac/src/lib.rs +35 -2
- crates/ec-alac/tests/encode.rs +340 -0
- crates/ec-alac/tests/oracle.rs +43 -0
Cargo.lockmodified+1 -0
| @@ -246,6 +246,7 @@ version = "0.1.0" | |||
| 246 | dependencies = [ | 246 | dependencies = [ |
| 247 | "ec-core", | 247 | "ec-core", |
| 248 | "ec-mp4", | 248 | "ec-mp4", |
| 249 | + "ec-riff", | ||
| 249 | ] | 250 | ] |
| 250 | 251 | ||
| 251 | [[package]] | 252 | [[package]] |
crates/ec-alac/Cargo.tomlmodified+1 -0
| @@ -11,3 +11,4 @@ ec-core = { workspace = true } | |||
| 11 | 11 | ||
| 12 | [dev-dependencies] | 12 | [dev-dependencies] |
| 13 | ec-mp4 = { workspace = true } | 13 | ec-mp4 = { workspace = true } |
| 14 | +ec-riff = { workspace = true } | ||
crates/ec-alac/src/decode.rsmodified+8 -3
| @@ -108,11 +108,16 @@ fn golomb(bits: &mut Bits<'_>, m: u32, k: u32, maxbits: u32) -> u32 { | |||
| 108 | let stream = bits.peek32(); | 108 | let stream = bits.peek32(); |
| 109 | let pre = (!stream).leading_zeros(); | 109 | let pre = (!stream).leading_zeros(); |
| 110 | if pre >= MAX_PREFIX { | 110 | if pre >= MAX_PREFIX { |
| 111 | - bits.pos += (MAX_PREFIX + maxbits) as usize; | 111 | + // The raw value can be up to 32 bits wide (a 24-bit stereo element |
| 112 | - return match maxbits { | 112 | + // codes 25), so it does not fit in the same 32-bit peek as the |
| 113 | + // prefix: step past the prefix and peek again. | ||
| 114 | + bits.pos += MAX_PREFIX as usize; | ||
| 115 | + let raw = match maxbits { | ||
| 113 | 0 => 0, | 116 | 0 => 0, |
| 114 | - n => (stream << MAX_PREFIX) >> (32 - n), | 117 | + n => bits.peek32() >> (32 - n), |
| 115 | }; | 118 | }; |
| 119 | + bits.pos += maxbits as usize; | ||
| 120 | + return raw; | ||
| 116 | } | 121 | } |
| 117 | bits.pos += pre as usize + 1; | 122 | bits.pos += pre as usize + 1; |
| 118 | let mut result = pre * m; | 123 | let mut result = pre * m; |
crates/ec-alac/src/encode.rsadded+627 -0
| @@ -0,0 +1,627 @@ | |||
| 1 | +//! ALAC encoding: the inverse of `decode.rs`'s element walk, adaptive-Golomb | ||
| 2 | +//! coder and predictor. Every constant and code shape here mirrors that file | ||
| 3 | +//! deliberately, so a `AlacEncoder::encode_frame` output is exactly what | ||
| 4 | +//! `AlacDecoder::decode` expects. | ||
| 5 | +//! | ||
| 6 | +//! Written from the published ALAC format description, same as `decode.rs`. | ||
| 7 | +//! Nothing here is derived from Apple's encoder sources. | ||
| 8 | + | ||
| 9 | +use crate::MagicCookie; | ||
| 10 | +use ec_core::error::{Error, Result}; | ||
| 11 | +use ec_core::frame::{Frame, SampleFormat}; | ||
| 12 | +use ec_core::packet::Packet; | ||
| 13 | +use ec_core::registry::{CodecParameters, Encoder}; | ||
| 14 | + | ||
| 15 | +const QBSHIFT: u32 = 9; | ||
| 16 | +const QB: u32 = 1 << QBSHIFT; | ||
| 17 | +const MMULSHIFT: u32 = 2; | ||
| 18 | +const MDENSHIFT: u32 = QBSHIFT - MMULSHIFT - 1; | ||
| 19 | +const MOFF: u32 = 1 << (MDENSHIFT - 2); | ||
| 20 | +const BITOFF: i32 = 24; | ||
| 21 | +const MAX_PREFIX: u32 = 9; | ||
| 22 | +const MAX_RUN_BITS: u32 = 16; | ||
| 23 | +const MEAN_CLAMP: u32 = 0xffff; | ||
| 24 | + | ||
| 25 | +const ID_SCE: u32 = 0; | ||
| 26 | +const ID_CPE: u32 = 1; | ||
| 27 | +const ID_END: u32 = 7; | ||
| 28 | + | ||
| 29 | +/// Filter orders searched for the single-pass (mode 0) predictor, plus 31 — | ||
| 30 | +/// the format's sentinel for "whole-block first-order difference", which | ||
| 31 | +/// `decode.rs`'s `predict` special-cases regardless of any coefficients | ||
| 32 | +/// stored alongside it (`decode.rs:245`). | ||
| 33 | +const ORDER_CANDIDATES: [usize; 5] = [4, 8, 12, 16, 31]; | ||
| 34 | +const ORDER_DIFF: usize = 31; | ||
| 35 | + | ||
| 36 | +/// `floor(log2(x + 3))`, duplicated from `decode.rs` because that module's | ||
| 37 | +/// helpers are private to it. | ||
| 38 | +fn lg3a(x: u32) -> u32 { | ||
| 39 | + 31 - (x + 3).leading_zeros() | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +fn sign(x: i32) -> i32 { | ||
| 43 | + (x > 0) as i32 - (x < 0) as i32 | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// A zigzag of a signed residual into decode.rs's `ndecode` space: 0, -1, 1, | ||
| 47 | +/// -2, 2, ... maps to 0, 1, 2, 3, 4, ... | ||
| 48 | +fn zigzag(v: i32) -> u32 { | ||
| 49 | + let v = i64::from(v); | ||
| 50 | + (if v >= 0 { v * 2 } else { -v * 2 - 1 }) as u32 | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// Where encoded bits go: a real bit writer, or a running count for the | ||
| 54 | +/// order/mix search that never touches memory for the bits themselves. | ||
| 55 | +trait BitSink { | ||
| 56 | + fn put(&mut self, value: u32, n: u32); | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// MSB-first bit writer, byte-aligned on [`BitWriter::finish`] — the write | ||
| 60 | +/// side of `decode.rs`'s `Bits`. | ||
| 61 | +#[derive(Default)] | ||
| 62 | +struct BitWriter { | ||
| 63 | + bytes: Vec<u8>, | ||
| 64 | + cur: u8, | ||
| 65 | + nbits: u32, | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +impl BitWriter { | ||
| 69 | + fn align(&mut self) { | ||
| 70 | + while self.nbits != 0 { | ||
| 71 | + self.put(0, 1); | ||
| 72 | + } | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + fn finish(mut self) -> Vec<u8> { | ||
| 76 | + self.align(); | ||
| 77 | + self.bytes | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +impl BitSink for BitWriter { | ||
| 82 | + fn put(&mut self, value: u32, n: u32) { | ||
| 83 | + for i in (0..n).rev() { | ||
| 84 | + self.cur = (self.cur << 1) | ((value >> i) & 1) as u8; | ||
| 85 | + self.nbits += 1; | ||
| 86 | + if self.nbits == 8 { | ||
| 87 | + self.bytes.push(self.cur); | ||
| 88 | + self.cur = 0; | ||
| 89 | + self.nbits = 0; | ||
| 90 | + } | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// A bit count only, for measuring a candidate before committing to it. | ||
| 96 | +#[derive(Default)] | ||
| 97 | +struct CostSink(u64); | ||
| 98 | + | ||
| 99 | +impl BitSink for CostSink { | ||
| 100 | + fn put(&mut self, _value: u32, n: u32) { | ||
| 101 | + self.0 += u64::from(n); | ||
| 102 | + } | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +/// One adaptive-Golomb code, the write side of `decode.rs`'s `golomb`: a | ||
| 106 | +/// unary quotient of `n / m` (escaping to a raw `maxbits` value past | ||
| 107 | +/// [`MAX_PREFIX`]) and a truncated-binary remainder in `k` or `k - 1` bits. | ||
| 108 | +fn golomb_write<S: BitSink>(sink: &mut S, n: u32, m: u32, k: u32, maxbits: u32) { | ||
| 109 | + if m == 0 { | ||
| 110 | + // `decode.rs`'s reader only reaches this when k <= 1 too, in which | ||
| 111 | + // case it never looks at a remainder at all — a mean-derived k this | ||
| 112 | + // small essentially never occurs (see `rice_encode`'s zero-run k), | ||
| 113 | + // but the fallback here is a plain unary-free raw write rather than | ||
| 114 | + // a divide by zero. | ||
| 115 | + sink.put(n, maxbits.max(1)); | ||
| 116 | + return; | ||
| 117 | + } | ||
| 118 | + debug_assert!(maxbits >= 32 || n >> maxbits == 0, "Golomb value {n} does not fit its {maxbits}-bit escape"); | ||
| 119 | + let q = n / m; | ||
| 120 | + if q >= MAX_PREFIX { | ||
| 121 | + sink.put(u32::MAX, MAX_PREFIX); | ||
| 122 | + if maxbits > 0 { | ||
| 123 | + sink.put(n, maxbits); | ||
| 124 | + } | ||
| 125 | + return; | ||
| 126 | + } | ||
| 127 | + if q > 0 { | ||
| 128 | + sink.put(u32::MAX, q); | ||
| 129 | + } | ||
| 130 | + sink.put(0, 1); | ||
| 131 | + if k > 1 { | ||
| 132 | + let r = n - q * m; | ||
| 133 | + match r { | ||
| 134 | + 0 => sink.put(0, k - 1), | ||
| 135 | + r => sink.put(r + 1, k), | ||
| 136 | + } | ||
| 137 | + } | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +/// Adaptive-Golomb-encode `res` into `sink`, exactly inverting | ||
| 141 | +/// `decode.rs`'s `Rice::decode` — same mean update, same zero-run escape. | ||
| 142 | +fn rice_encode<S: BitSink>(sink: &mut S, cfg: &MagicCookie, pb_factor: u32, res: &[i32], chan_bits: u32) { | ||
| 143 | + let kb = u32::from(cfg.kb).clamp(1, 31); | ||
| 144 | + let pb = u32::from(cfg.pb) * pb_factor / 4; | ||
| 145 | + let wb = (1u32 << kb) - 1; | ||
| 146 | + let mut mean = u32::from(cfg.mb); | ||
| 147 | + let mut zmode = 0u32; | ||
| 148 | + let mut c = 0usize; | ||
| 149 | + while c < res.len() { | ||
| 150 | + let ndecode = zigzag(res[c]); | ||
| 151 | + // Safe: `zmode` is only 1 right after a zero run that consumed every | ||
| 152 | + // contiguous zero, so the sample here is never itself zero. | ||
| 153 | + let n = ndecode - zmode; | ||
| 154 | + let k = lg3a(mean >> QBSHIFT).min(kb); | ||
| 155 | + let m = (1u32 << k) - 1; | ||
| 156 | + golomb_write(sink, n, m, k, chan_bits); | ||
| 157 | + c += 1; | ||
| 158 | + | ||
| 159 | + mean = pb | ||
| 160 | + .wrapping_mul(ndecode) | ||
| 161 | + .wrapping_add(mean) | ||
| 162 | + .wrapping_sub(pb.wrapping_mul(mean) >> QBSHIFT); | ||
| 163 | + if n > MEAN_CLAMP { | ||
| 164 | + mean = MEAN_CLAMP; | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + zmode = 0; | ||
| 168 | + if (mean << MMULSHIFT) < QB && c < res.len() { | ||
| 169 | + zmode = 1; | ||
| 170 | + let k2 = (mean.leading_zeros() as i32 - BITOFF + ((mean + MOFF) >> MDENSHIFT) as i32) | ||
| 171 | + .clamp(0, 31) as u32; | ||
| 172 | + let mz = ((1u32 << k2) - 1) & wb; | ||
| 173 | + let mut run = 0u32; | ||
| 174 | + while (c + run as usize) < res.len() && res[c + run as usize] == 0 { | ||
| 175 | + run += 1; | ||
| 176 | + if run as usize >= (1 << MAX_RUN_BITS) - 1 { | ||
| 177 | + break; | ||
| 178 | + } | ||
| 179 | + } | ||
| 180 | + golomb_write(sink, run, mz, k2, MAX_RUN_BITS); | ||
| 181 | + c += run as usize; | ||
| 182 | + if run >= (1 << MAX_RUN_BITS) - 1 { | ||
| 183 | + zmode = 0; | ||
| 184 | + } | ||
| 185 | + mean = 0; | ||
| 186 | + } | ||
| 187 | + } | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +/// The forward twin of `decode.rs`'s `predict`: given the true samples `y` | ||
| 191 | +/// (already in their coded width), compute the residuals a from-zero | ||
| 192 | +/// sign-adapting filter of `order` taps and `den_shift` would need to | ||
| 193 | +/// reproduce them exactly. The coefficients this implicitly walks through | ||
| 194 | +/// are never returned — the encoder always states an all-zero starting | ||
| 195 | +/// filter, so the decoder's own adaptation, run from the same zero start, | ||
| 196 | +/// retraces this pass exactly. | ||
| 197 | +/// | ||
| 198 | +/// Every residual is wrapped to `chan_bits` exactly as `decode.rs`'s | ||
| 199 | +/// `predict` wraps its reconstruction (`clamp`, decode.rs:242): a difference | ||
| 200 | +/// of two in-range samples can need one bit more than the samples do, the | ||
| 201 | +/// Golomb escape carries only `chan_bits` of it, and the decoder's add then | ||
| 202 | +/// wraps the truncated value back to the right sample. Adapting on the | ||
| 203 | +/// unwrapped residual's sign would diverge from the decoder's walk. | ||
| 204 | +fn analyze(y: &[i32], order: usize, den_shift: u32, chan_bits: u32) -> Vec<i32> { | ||
| 205 | + let n = y.len(); | ||
| 206 | + let mut res = vec![0i32; n]; | ||
| 207 | + if n == 0 { | ||
| 208 | + return res; | ||
| 209 | + } | ||
| 210 | + let chan_shift = 32 - chan_bits; | ||
| 211 | + let wrap = |v: i32| ((v as u32) << chan_shift) as i32 >> chan_shift; | ||
| 212 | + res[0] = y[0]; | ||
| 213 | + if order == ORDER_DIFF { | ||
| 214 | + for j in 1..n { | ||
| 215 | + res[j] = wrap(y[j].wrapping_sub(y[j - 1])); | ||
| 216 | + } | ||
| 217 | + return res; | ||
| 218 | + } | ||
| 219 | + if order == 0 || order >= n { | ||
| 220 | + // Order 0 is decode.rs's "residuals are the samples verbatim"; a | ||
| 221 | + // caller never asks for 0 < order >= n (`best_candidate` filters | ||
| 222 | + // those out), so this path is only ever reached as the order-0 case. | ||
| 223 | + res.copy_from_slice(y); | ||
| 224 | + return res; | ||
| 225 | + } | ||
| 226 | + | ||
| 227 | + let mut coefs = vec![0i32; order]; | ||
| 228 | + for j in 1..=order { | ||
| 229 | + res[j] = wrap(y[j].wrapping_sub(y[j - 1])); | ||
| 230 | + } | ||
| 231 | + let den_half = match den_shift { | ||
| 232 | + 0 => 0, | ||
| 233 | + s => 1i32 << (s - 1), | ||
| 234 | + }; | ||
| 235 | + for j in order..n - 1 { | ||
| 236 | + let top = y[j - order]; | ||
| 237 | + let mut sum = 0i32; | ||
| 238 | + for (k, &c) in coefs.iter().enumerate() { | ||
| 239 | + sum = sum.wrapping_add(c.wrapping_mul(y[j - k].wrapping_sub(top))); | ||
| 240 | + } | ||
| 241 | + let predicted = top.wrapping_add(sum.wrapping_add(den_half) >> den_shift); | ||
| 242 | + let del = wrap(y[j + 1].wrapping_sub(predicted)); | ||
| 243 | + res[j + 1] = del; | ||
| 244 | + | ||
| 245 | + let mut del0 = del; | ||
| 246 | + let sg = sign(del); | ||
| 247 | + if sg > 0 { | ||
| 248 | + for k in (0..order).rev() { | ||
| 249 | + let dd = top.wrapping_sub(y[j - k]); | ||
| 250 | + let s = sign(dd); | ||
| 251 | + coefs[k] -= s; | ||
| 252 | + del0 -= ((order - k) as i32).wrapping_mul(s.wrapping_mul(dd) >> den_shift); | ||
| 253 | + if del0 <= 0 { | ||
| 254 | + break; | ||
| 255 | + } | ||
| 256 | + } | ||
| 257 | + } else if sg < 0 { | ||
| 258 | + for k in (0..order).rev() { | ||
| 259 | + let dd = top.wrapping_sub(y[j - k]); | ||
| 260 | + let s = sign(dd); | ||
| 261 | + coefs[k] += s; | ||
| 262 | + del0 -= ((order - k) as i32).wrapping_mul((-s).wrapping_mul(dd) >> den_shift); | ||
| 263 | + if del0 >= 0 { | ||
| 264 | + break; | ||
| 265 | + } | ||
| 266 | + } | ||
| 267 | + } | ||
| 268 | + } | ||
| 269 | + res | ||
| 270 | +} | ||
| 271 | + | ||
| 272 | +/// One channel's chosen filter: the mode and order fields to write, the | ||
| 273 | +/// residuals it produces, and its total cost in bits (16-bit plan header + | ||
| 274 | +/// coefficients + the Rice-coded residuals), for comparing against every | ||
| 275 | +/// other choice. | ||
| 276 | +struct Candidate { | ||
| 277 | + mode: u32, | ||
| 278 | + order: u32, | ||
| 279 | + res: Vec<i32>, | ||
| 280 | + bits: u64, | ||
| 281 | +} | ||
| 282 | + | ||
| 283 | +/// Cheapest of [`ORDER_CANDIDATES`] (plus the trivial order-0 "residuals are | ||
| 284 | +/// the samples" case) for one channel of true samples, each as mode 0 — the | ||
| 285 | +/// only prediction type real-world decoders accept (decode.rs also undoes | ||
| 286 | +/// mode 1's extra difference pass, but nothing here emits it). | ||
| 287 | +fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) -> Candidate { | ||
| 288 | + let mut orders: Vec<usize> = vec![0]; | ||
| 289 | + orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len())); | ||
| 290 | + let mut best: Option<Candidate> = None; | ||
| 291 | + for order in orders { | ||
| 292 | + let res = analyze(y, order, 9, chan_bits); | ||
| 293 | + let mut cost = CostSink::default(); | ||
| 294 | + rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits); | ||
| 295 | + let bits = 16 + (order as u64) * 16 + cost.0; | ||
| 296 | + | ||
| 297 | + if best.as_ref().is_none_or(|b| bits < b.bits) { | ||
| 298 | + best = Some(Candidate { | ||
| 299 | + mode: 0, | ||
| 300 | + order: order as u32, | ||
| 301 | + res, | ||
| 302 | + bits, | ||
| 303 | + }); | ||
| 304 | + } | ||
| 305 | + } | ||
| 306 | + best.unwrap_or(Candidate { | ||
| 307 | + mode: 0, | ||
| 308 | + order: 0, | ||
| 309 | + res: y.to_vec(), | ||
| 310 | + bits: u64::MAX, | ||
| 311 | + }) | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +/// A channel's coded parameters and residuals, ready to write: the plan | ||
| 315 | +/// header fields plus [`Candidate::res`]. | ||
| 316 | +struct ChannelPlan { | ||
| 317 | + mode: u32, | ||
| 318 | + order: u32, | ||
| 319 | + pb_factor: u32, | ||
| 320 | + res: Vec<i32>, | ||
| 321 | +} | ||
| 322 | + | ||
| 323 | +const DEN_SHIFT: u32 = 9; | ||
| 324 | +const PB_FACTOR: u32 = 4; | ||
| 325 | + | ||
| 326 | +fn write_plan<S: BitSink>(sink: &mut S, plan: &ChannelPlan) { | ||
| 327 | + sink.put(plan.mode, 4); | ||
| 328 | + sink.put(DEN_SHIFT, 4); | ||
| 329 | + sink.put(PB_FACTOR, 3); | ||
| 330 | + sink.put(plan.order, 5); | ||
| 331 | + for _ in 0..plan.order { | ||
| 332 | + sink.put(0, 16); // all-zero starting coefficients (see `analyze`). | ||
| 333 | + } | ||
| 334 | +} | ||
| 335 | + | ||
| 336 | +/// One SCE (mono) or CPE (stereo) element, choosing per-element between raw | ||
| 337 | +/// (escape) and compressed, and for a pair, between direct L/R and a | ||
| 338 | +/// mid/side mix, whichever is smaller. | ||
| 339 | +fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samples: usize, allow_shift: bool) { | ||
| 340 | + w.put(0, 16); // element instance tag + 12 reserved bits. | ||
| 341 | + let pair = planes.len() == 2; | ||
| 342 | + let channels = planes.len() as u32; | ||
| 343 | + let bit_depth = u32::from(cfg.bit_depth); | ||
| 344 | + let partial = samples != cfg.frame_length as usize; | ||
| 345 | + let raw_bits = u64::from(channels) * u64::from(bit_depth) * samples as u64; | ||
| 346 | + | ||
| 347 | + // A 24-bit stream may additionally split each sample into a compressed | ||
| 348 | + // high part and an uncompressed low byte ridden ahead of the residuals | ||
| 349 | + // (decode.rs:485-490, :533-538) — bytes_shifted 1 — when that beats | ||
| 350 | + // compressing the sample whole. Only 0 and 1 are ever tried: 3 is the | ||
| 351 | + // format's escape sentinel (decode.rs:439), and a stream never carries | ||
| 352 | + // more than one low byte's worth of headroom worth shifting off. | ||
| 353 | + let shift_candidates: &[u32] = if bit_depth == 24 && allow_shift { &[0, 1] } else { &[0] }; | ||
| 354 | + | ||
| 355 | + let compressed = (samples >= 2).then(|| { | ||
| 356 | + shift_candidates | ||
| 357 | + .iter() | ||
| 358 | + .map(|&bytes_shifted| { | ||
| 359 | + let shift_bits = bytes_shifted * 8; | ||
| 360 | + let chan_bits = bit_depth - shift_bits + channels - 1; | ||
| 361 | + let low_bits = u64::from(shift_bits) * u64::from(channels) * samples as u64; | ||
| 362 | + let shifted: Vec<Vec<i32>> = planes | ||
| 363 | + .iter() | ||
| 364 | + .map(|p| p.iter().map(|&s| s >> shift_bits).collect()) | ||
| 365 | + .collect(); | ||
| 366 | + | ||
| 367 | + let (mix_bits, mix_res, plans, bits) = if pair { | ||
| 368 | + let (l, r) = (&shifted[0], &shifted[1]); | ||
| 369 | + let lc = best_candidate(cfg, l, chan_bits, PB_FACTOR); | ||
| 370 | + let rc = best_candidate(cfg, r, chan_bits, PB_FACTOR); | ||
| 371 | + let lr_bits = lc.bits + rc.bits; | ||
| 372 | + | ||
| 373 | + // mix_bits = 1, mix_res = 1: v = l - r, u = r + (v >> 1). | ||
| 374 | + let (mut u, mut v) = (vec![0i32; samples], vec![0i32; samples]); | ||
| 375 | + for i in 0..samples { | ||
| 376 | + v[i] = l[i] - r[i]; | ||
| 377 | + u[i] = r[i] + (v[i] >> 1); | ||
| 378 | + } | ||
| 379 | + let uc = best_candidate(cfg, &u, chan_bits, PB_FACTOR); | ||
| 380 | + let vc = best_candidate(cfg, &v, chan_bits, PB_FACTOR); | ||
| 381 | + let ms_bits = uc.bits + vc.bits; | ||
| 382 | + | ||
| 383 | + match ms_bits < lr_bits { | ||
| 384 | + true => (1u32, 1i32, vec![plan_of(uc), plan_of(vc)], ms_bits), | ||
| 385 | + false => (2u32, 0i32, vec![plan_of(lc), plan_of(rc)], lr_bits), | ||
| 386 | + } | ||
| 387 | + } else { | ||
| 388 | + let c0 = best_candidate(cfg, &shifted[0], chan_bits, PB_FACTOR); | ||
| 389 | + let bits = c0.bits; | ||
| 390 | + (0u32, 0i32, vec![plan_of(c0)], bits) | ||
| 391 | + }; | ||
| 392 | + (bytes_shifted, mix_bits, mix_res, plans, bits + low_bits) | ||
| 393 | + }) | ||
| 394 | + .min_by_key(|&(_, _, _, _, bits)| bits) | ||
| 395 | + .unwrap() | ||
| 396 | + }); | ||
| 397 | + | ||
| 398 | + let use_compressed = compressed | ||
| 399 | + .as_ref() | ||
| 400 | + .is_some_and(|(_, _, _, _, bits)| 16 + bits < raw_bits.max(1)); | ||
| 401 | + let bytes_shifted = compressed.as_ref().map_or(0, |&(bs, ..)| bs); | ||
| 402 | + | ||
| 403 | + w.put(partial as u32, 1); | ||
| 404 | + w.put(if use_compressed { bytes_shifted } else { 0 }, 2); | ||
| 405 | + w.put(!use_compressed as u32, 1); | ||
| 406 | + if partial { | ||
| 407 | + w.put((samples as u32) >> 16, 16); | ||
| 408 | + w.put(samples as u32 & 0xffff, 16); | ||
| 409 | + } | ||
| 410 | + | ||
| 411 | + match use_compressed { | ||
| 412 | + false => { | ||
| 413 | + let chan_bits = bit_depth; | ||
| 414 | + for i in 0..samples { | ||
| 415 | + for plane in planes { | ||
| 416 | + w.put(plane[i] as u32 & mask(chan_bits), chan_bits); | ||
| 417 | + } | ||
| 418 | + } | ||
| 419 | + } | ||
| 420 | + true => { | ||
| 421 | + let (bytes_shifted, mix_bits, mix_res, plans, _) = compressed.unwrap(); | ||
| 422 | + let shift_bits = bytes_shifted * 8; | ||
| 423 | + w.put(mix_bits, 8); | ||
| 424 | + w.put((mix_res as i8) as u8 as u32, 8); | ||
| 425 | + for plan in &plans { | ||
| 426 | + write_plan(w, plan); | ||
| 427 | + } | ||
| 428 | + // The low bytes ride ahead of the residuals, one `shift_bits` | ||
| 429 | + // field per sample per channel, in the same i-outer/channel-inner | ||
| 430 | + // order the escape path above uses — decode.rs reads them back | ||
| 431 | + // in exactly that order (decode.rs:533-538). | ||
| 432 | + if shift_bits > 0 { | ||
| 433 | + for i in 0..samples { | ||
| 434 | + for plane in planes { | ||
| 435 | + w.put(plane[i] as u32 & mask(shift_bits), shift_bits); | ||
| 436 | + } | ||
| 437 | + } | ||
| 438 | + } | ||
| 439 | + let chan_bits = bit_depth - shift_bits + channels - 1; | ||
| 440 | + for plan in &plans { | ||
| 441 | + rice_encode(w, cfg, plan.pb_factor, &plan.res, chan_bits); | ||
| 442 | + } | ||
| 443 | + } | ||
| 444 | + } | ||
| 445 | +} | ||
| 446 | + | ||
| 447 | +fn plan_of(c: Candidate) -> ChannelPlan { | ||
| 448 | + ChannelPlan { | ||
| 449 | + mode: c.mode, | ||
| 450 | + order: c.order, | ||
| 451 | + pb_factor: PB_FACTOR, | ||
| 452 | + res: c.res, | ||
| 453 | + } | ||
| 454 | +} | ||
| 455 | + | ||
| 456 | +/// `n` low bits set, for masking a two's-complement value into an escape's | ||
| 457 | +/// raw field. | ||
| 458 | +fn mask(n: u32) -> u32 { | ||
| 459 | + match n { | ||
| 460 | + 32 => u32::MAX, | ||
| 461 | + n => (1 << n) - 1, | ||
| 462 | + } | ||
| 463 | +} | ||
| 464 | + | ||
| 465 | +/// An ALAC encoder for one mono or stereo stream. | ||
| 466 | +#[derive(Debug)] | ||
| 467 | +pub struct AlacEncoder { | ||
| 468 | + cookie: MagicCookie, | ||
| 469 | + params: CodecParameters, | ||
| 470 | + channels: usize, | ||
| 471 | + pending: Vec<i32>, | ||
| 472 | + packets: std::collections::VecDeque<Vec<u8>>, | ||
| 473 | + eof: bool, | ||
| 474 | + allow_shift: bool, | ||
| 475 | +} | ||
| 476 | + | ||
| 477 | +impl AlacEncoder { | ||
| 478 | + /// An encoder for a mono or stereo stream. `bit_depth` is 16 or 24; | ||
| 479 | + /// `frame_length` is the samples-per-channel every full frame carries | ||
| 480 | + /// (Apple's own encoder writes 4096). | ||
| 481 | + pub fn new(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32) -> Result<AlacEncoder> { | ||
| 482 | + if !matches!(bit_depth, 16 | 24) { | ||
| 483 | + return Err(Error::unsupported( | ||
| 484 | + format!("ALAC encoding {bit_depth}-bit samples"), | ||
| 485 | + "this encoder writes 16 and 24 bit only", | ||
| 486 | + )); | ||
| 487 | + } | ||
| 488 | + if !(1..=2).contains(&channels) { | ||
| 489 | + return Err(Error::unsupported( | ||
| 490 | + format!("ALAC encoding {channels} channels"), | ||
| 491 | + "this encoder writes mono and stereo only", | ||
| 492 | + )); | ||
| 493 | + } | ||
| 494 | + let cookie = MagicCookie { | ||
| 495 | + frame_length, | ||
| 496 | + compatible_version: 0, | ||
| 497 | + bit_depth, | ||
| 498 | + pb: 40, | ||
| 499 | + mb: 10, | ||
| 500 | + kb: 14, | ||
| 501 | + channels, | ||
| 502 | + max_run: 255, | ||
| 503 | + max_frame_bytes: 0, | ||
| 504 | + avg_bit_rate: 0, | ||
| 505 | + sample_rate, | ||
| 506 | + }; | ||
| 507 | + let mut params = crate::codec_parameters(&cookie); | ||
| 508 | + params.extradata = Some(cookie.extradata_box().into()); | ||
| 509 | + Ok(AlacEncoder { | ||
| 510 | + cookie, | ||
| 511 | + params, | ||
| 512 | + channels: channels as usize, | ||
| 513 | + pending: Vec::new(), | ||
| 514 | + packets: std::collections::VecDeque::new(), | ||
| 515 | + eof: false, | ||
| 516 | + allow_shift: true, | ||
| 517 | + }) | ||
| 518 | + } | ||
| 519 | + | ||
| 520 | + /// Test-only: force bytes_shifted 0 even at 24 bits, so a test can | ||
| 521 | + /// measure both paths against the same source. Both outputs decode the | ||
| 522 | + /// same; this only trades size. | ||
| 523 | + #[doc(hidden)] | ||
| 524 | + pub fn set_byte_shift(&mut self, allow: bool) { | ||
| 525 | + self.allow_shift = allow; | ||
| 526 | + } | ||
| 527 | + | ||
| 528 | + /// What this encoder states about the stream it writes. | ||
| 529 | + pub fn cookie(&self) -> &MagicCookie { | ||
| 530 | + &self.cookie | ||
| 531 | + } | ||
| 532 | + | ||
| 533 | + /// Encode one frame: `samples` interleaved, true PCM range (not the | ||
| 534 | + /// container-shifted range [`AlacDecoder::decode`] hands back), up to | ||
| 535 | + /// `frame_length` samples per channel — a shorter slice writes a partial | ||
| 536 | + /// frame, exactly as a stream's last frame does. | ||
| 537 | + pub fn encode_frame(&self, samples: &[i32]) -> Vec<u8> { | ||
| 538 | + let channels = self.channels; | ||
| 539 | + let n = samples.len() / channels; | ||
| 540 | + let mut planes: Vec<Vec<i32>> = vec![Vec::with_capacity(n); channels]; | ||
| 541 | + for chunk in samples.chunks_exact(channels) { | ||
| 542 | + for (c, plane) in planes.iter_mut().enumerate() { | ||
| 543 | + plane.push(chunk[c]); | ||
| 544 | + } | ||
| 545 | + } | ||
| 546 | + let mut w = BitWriter::default(); | ||
| 547 | + w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3); | ||
| 548 | + write_element(&self.cookie, &mut w, &planes, n, self.allow_shift); | ||
| 549 | + w.put(ID_END, 3); | ||
| 550 | + w.finish() | ||
| 551 | + } | ||
| 552 | +} | ||
| 553 | + | ||
| 554 | +impl Encoder for AlacEncoder { | ||
| 555 | + fn codec_parameters(&self) -> &CodecParameters { | ||
| 556 | + &self.params | ||
| 557 | + } | ||
| 558 | + | ||
| 559 | + fn send_frame(&mut self, frame: &Frame) -> Result<()> { | ||
| 560 | + let Frame::Audio(audio) = frame else { | ||
| 561 | + return Err(Error::corrupt("video frame pushed into an ALAC encoder")); | ||
| 562 | + }; | ||
| 563 | + let channels = self.channels; | ||
| 564 | + let shift = self.cookie.container_shift(); | ||
| 565 | + let want = self.cookie.sample_format(); | ||
| 566 | + if audio.format != want { | ||
| 567 | + return Err(Error::unsupported( | ||
| 568 | + format!("{:?} input", audio.format), | ||
| 569 | + "this encoder takes samples in the cookie's own sample format", | ||
| 570 | + )); | ||
| 571 | + } | ||
| 572 | + let mut interleaved = Vec::with_capacity(audio.samples * channels); | ||
| 573 | + match (audio.planar, want) { | ||
| 574 | + (false, SampleFormat::S16) => { | ||
| 575 | + for pair in audio.data[0].chunks_exact(2).take(audio.samples * channels) { | ||
| 576 | + interleaved.push(i32::from(i16::from_ne_bytes([pair[0], pair[1]])) >> shift); | ||
| 577 | + } | ||
| 578 | + } | ||
| 579 | + (false, _) => { | ||
| 580 | + for word in audio.data[0].chunks_exact(4).take(audio.samples * channels) { | ||
| 581 | + interleaved.push(i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> shift); | ||
| 582 | + } | ||
| 583 | + } | ||
| 584 | + (true, SampleFormat::S16) => { | ||
| 585 | + for i in 0..audio.samples { | ||
| 586 | + for plane in audio.data.iter().take(channels) { | ||
| 587 | + let at = i * 2; | ||
| 588 | + interleaved.push(i32::from(i16::from_ne_bytes([plane[at], plane[at + 1]])) >> shift); | ||
| 589 | + } | ||
| 590 | + } | ||
| 591 | + } | ||
| 592 | + (true, _) => { | ||
| 593 | + for i in 0..audio.samples { | ||
| 594 | + for plane in audio.data.iter().take(channels) { | ||
| 595 | + let at = i * 4; | ||
| 596 | + let w = [plane[at], plane[at + 1], plane[at + 2], plane[at + 3]]; | ||
| 597 | + interleaved.push(i32::from_ne_bytes(w) >> shift); | ||
| 598 | + } | ||
| 599 | + } | ||
| 600 | + } | ||
| 601 | + } | ||
| 602 | + self.pending.extend(interleaved); | ||
| 603 | + let per_frame = self.cookie.frame_length as usize * channels; | ||
| 604 | + while self.pending.len() >= per_frame { | ||
| 605 | + let frame: Vec<i32> = self.pending.drain(..per_frame).collect(); | ||
| 606 | + self.packets.push_back(self.encode_frame(&frame)); | ||
| 607 | + } | ||
| 608 | + Ok(()) | ||
| 609 | + } | ||
| 610 | + | ||
| 611 | + fn receive_packet(&mut self) -> Result<Packet> { | ||
| 612 | + match self.packets.pop_front() { | ||
| 613 | + Some(data) => Ok(Packet::new(0, ec_core::timebase::TimeBase::new(1, i64::from(self.cookie.sample_rate)), data)), | ||
| 614 | + None if self.eof => Err(Error::Eof), | ||
| 615 | + None => Err(Error::NeedMore), | ||
| 616 | + } | ||
| 617 | + } | ||
| 618 | + | ||
| 619 | + fn flush(&mut self) -> Result<()> { | ||
| 620 | + if !self.pending.is_empty() { | ||
| 621 | + let frame = std::mem::take(&mut self.pending); | ||
| 622 | + self.packets.push_back(self.encode_frame(&frame)); | ||
| 623 | + } | ||
| 624 | + self.eof = true; | ||
| 625 | + Ok(()) | ||
| 626 | + } | ||
| 627 | +} | ||
crates/ec-alac/src/lib.rsmodified+35 -2
| @@ -12,8 +12,8 @@ | |||
| 12 | //! container carries as extradata: the frame length, the bit depth and the | 12 | //! container carries as extradata: the frame length, the bit depth and the |
| 13 | //! three Golomb constants the residual coder adapts from. | 13 | //! three Golomb constants the residual coder adapts from. |
| 14 | //! | 14 | //! |
| 15 | -//! Decode only — edith never writes ALAC, so there is no encoder here and no | 15 | +//! - [`AlacEncoder`], the mirror image: frames in, coded packets out, for a |
| 16 | -//! pretending otherwise. | 16 | +//! container that wants to write ALAC instead of read it. |
| 17 | //! | 17 | //! |
| 18 | //! **Clean room.** Written from the published ALAC format description; Apple's | 18 | //! **Clean room.** Written from the published ALAC format description; Apple's |
| 19 | //! decoder sources were not read. Samples are returned shifted into their PCM | 19 | //! decoder sources were not read. Samples are returned shifted into their PCM |
| @@ -24,6 +24,9 @@ | |||
| 24 | #![warn(missing_docs)] | 24 | #![warn(missing_docs)] |
| 25 | 25 | ||
| 26 | mod decode; | 26 | mod decode; |
| 27 | +mod encode; | ||
| 28 | + | ||
| 29 | +pub use encode::AlacEncoder; | ||
| 27 | 30 | ||
| 28 | use ec_core::error::{Error, Result}; | 31 | use ec_core::error::{Error, Result}; |
| 29 | use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; | 32 | use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; |
| @@ -133,6 +136,36 @@ impl MagicCookie { | |||
| 133 | false => SampleFormat::S32, | 136 | false => SampleFormat::S32, |
| 134 | } | 137 | } |
| 135 | } | 138 | } |
| 139 | + | ||
| 140 | + /// The bare 24-byte `ALACSpecificConfig`, big-endian. | ||
| 141 | + pub fn to_bytes(&self) -> [u8; 24] { | ||
| 142 | + let mut b = [0u8; 24]; | ||
| 143 | + b[0..4].copy_from_slice(&self.frame_length.to_be_bytes()); | ||
| 144 | + b[4] = self.compatible_version; | ||
| 145 | + b[5] = self.bit_depth; | ||
| 146 | + b[6] = self.pb; | ||
| 147 | + b[7] = self.mb; | ||
| 148 | + b[8] = self.kb; | ||
| 149 | + b[9] = self.channels; | ||
| 150 | + b[10..12].copy_from_slice(&self.max_run.to_be_bytes()); | ||
| 151 | + b[12..16].copy_from_slice(&self.max_frame_bytes.to_be_bytes()); | ||
| 152 | + b[16..20].copy_from_slice(&self.avg_bit_rate.to_be_bytes()); | ||
| 153 | + b[20..24].copy_from_slice(&self.sample_rate.to_be_bytes()); | ||
| 154 | + b | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + /// The whole `alac` box a container's sample entry carries: a 12-byte | ||
| 158 | + /// full-box header (size, `alac`, version/flags) in front of | ||
| 159 | + /// [`MagicCookie::to_bytes`], which is the shape `ec_mp4`'s muxer expects | ||
| 160 | + /// as a track's `extradata`. | ||
| 161 | + pub fn extradata_box(&self) -> Vec<u8> { | ||
| 162 | + let mut out = Vec::with_capacity(36); | ||
| 163 | + out.extend_from_slice(&36u32.to_be_bytes()); | ||
| 164 | + out.extend_from_slice(b"alac"); | ||
| 165 | + out.extend_from_slice(&0u32.to_be_bytes()); | ||
| 166 | + out.extend_from_slice(&self.to_bytes()); | ||
| 167 | + out | ||
| 168 | + } | ||
| 136 | } | 169 | } |
| 137 | 170 | ||
| 138 | /// Where each output channel sits in the stream's own coded order. | 171 | /// Where each output channel sits in the stream's own coded order. |
crates/ec-alac/tests/encode.rsadded+340 -0
| @@ -0,0 +1,340 @@ | |||
| 1 | +//! Round-trip the encoder through the decoder it was written to feed, then | ||
| 2 | +//! through a real mp4 mux and (when the oracle is present) ffmpeg/ffprobe. | ||
| 3 | + | ||
| 4 | +use std::fs::File; | ||
| 5 | +use std::io::{BufReader, Cursor}; | ||
| 6 | +use std::path::{Path, PathBuf}; | ||
| 7 | +use std::process::Command; | ||
| 8 | + | ||
| 9 | +use ec_alac::{AlacDecoder, AlacEncoder}; | ||
| 10 | +use ec_core::registry::{CodecId, Demuxer, Encoder, Muxer, StreamInfo}; | ||
| 11 | +use ec_core::timebase::TimeBase; | ||
| 12 | +use ec_core::Packet; | ||
| 13 | + | ||
| 14 | +fn fixtures() -> PathBuf { | ||
| 15 | + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +/// A small deterministic PRNG so a "random data" test does not depend on an | ||
| 19 | +/// external crate: xorshift32. | ||
| 20 | +struct Rng(u32); | ||
| 21 | +impl Rng { | ||
| 22 | + fn next(&mut self) -> u32 { | ||
| 23 | + self.0 ^= self.0 << 13; | ||
| 24 | + self.0 ^= self.0 >> 17; | ||
| 25 | + self.0 ^= self.0 << 5; | ||
| 26 | + self.0 | ||
| 27 | + } | ||
| 28 | + fn range(&mut self, bit_depth: u8) -> i32 { | ||
| 29 | + let max = 1i64 << (bit_depth - 1); | ||
| 30 | + ((self.next() as i64 % (2 * max)) - max) as i32 | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +/// Encode `samples` (interleaved, `channels` wide) in `frame_length`-sample | ||
| 35 | +/// chunks (the last one short) and decode every packet straight back, | ||
| 36 | +/// asserting bit-exact recovery. | ||
| 37 | +fn round_trip(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32, samples: &[i32]) { | ||
| 38 | + let enc = AlacEncoder::new(sample_rate, channels, bit_depth, frame_length).expect("encoder"); | ||
| 39 | + let mut dec = AlacDecoder::new(*enc.cookie()); | ||
| 40 | + let per_frame = frame_length as usize * channels as usize; | ||
| 41 | + let mut decoded = Vec::with_capacity(samples.len()); | ||
| 42 | + for chunk in samples.chunks(per_frame) { | ||
| 43 | + let packet = enc.encode_frame(chunk); | ||
| 44 | + let out = dec.decode(&packet).expect("decode"); | ||
| 45 | + // decode() shifts into the PCM container; undo that to compare | ||
| 46 | + // against the true-range input encode_frame took. | ||
| 47 | + let shift = enc.cookie().container_shift(); | ||
| 48 | + decoded.extend(out.iter().map(|&s| s >> shift)); | ||
| 49 | + } | ||
| 50 | + assert_eq!(decoded, samples, "{channels}ch {bit_depth}bit round trip"); | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// Encode `samples` frame by frame through a real mp4 mux into a fresh temp | ||
| 54 | +/// file, returned with its directory (delete it when done). | ||
| 55 | +fn mux_to_m4a(enc: &AlacEncoder, channels: usize, sample_rate: u32, samples: &[i32]) -> (PathBuf, PathBuf) { | ||
| 56 | + let mut mp4 = ec_mp4::Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); | ||
| 57 | + let time_base = TimeBase::new(1, i64::from(sample_rate)); | ||
| 58 | + let stream = mp4 | ||
| 59 | + .add_stream(StreamInfo::new(0, time_base, enc.codec_parameters().clone())) | ||
| 60 | + .expect("add_stream"); | ||
| 61 | + let mut pts = 0i64; | ||
| 62 | + for chunk in samples.chunks(4096 * channels) { | ||
| 63 | + let n = chunk.len() / channels; | ||
| 64 | + let data = enc.encode_frame(chunk); | ||
| 65 | + let mut packet = Packet::new(stream, time_base, data).with_pts(pts); | ||
| 66 | + packet.duration = Some(n as i64); | ||
| 67 | + mp4.write_packet(&packet).expect("write_packet"); | ||
| 68 | + pts += n as i64; | ||
| 69 | + } | ||
| 70 | + mp4.finish().expect("finish"); | ||
| 71 | + let bytes = mp4.into_inner().into_inner(); | ||
| 72 | + // Tests run in parallel in one process: a per-call serial keeps them out | ||
| 73 | + // of each other's directories. | ||
| 74 | + static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | ||
| 75 | + let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | ||
| 76 | + let dir = std::env::temp_dir().join(format!("ec-alac-mux-test-{}-{serial}", std::process::id())); | ||
| 77 | + std::fs::create_dir_all(&dir).unwrap(); | ||
| 78 | + let out_path = dir.join("out.m4a"); | ||
| 79 | + std::fs::write(&out_path, &bytes).expect("write m4a"); | ||
| 80 | + (dir, out_path) | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +/// ffmpeg's decode of `path` in raw format `fmt`, or None when no oracle is | ||
| 84 | +/// installed. | ||
| 85 | +fn ffmpeg_decode(path: &Path, fmt: &str) -> Option<Vec<u8>> { | ||
| 86 | + let decode = Command::new("ffmpeg") | ||
| 87 | + .args(["-nostdin", "-v", "error", "-i"]) | ||
| 88 | + .arg(path) | ||
| 89 | + .args(["-f", fmt, "-"]) | ||
| 90 | + .output() | ||
| 91 | + .ok()?; | ||
| 92 | + assert!(decode.status.success(), "{}", String::from_utf8_lossy(&decode.stderr)); | ||
| 93 | + Some(decode.stdout) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +#[test] | ||
| 97 | +fn twenty_four_bit_uses_byte_shift_when_cheaper() { | ||
| 98 | + // Real 16-bit audio widened to 24 bits with random dither in the low | ||
| 99 | + // byte: exactly the shape a 24-bit master of 16-bit source material has, | ||
| 100 | + // and exactly what bytes_shifted exists for — the high bits alone | ||
| 101 | + // predict well, but folded together with the dither's noise they do not. | ||
| 102 | + let path = fixtures().join("wav16-stereo-48000.wav"); | ||
| 103 | + if !path.exists() { | ||
| 104 | + eprintln!("fixtures/audio absent (gitignored) — skipping"); | ||
| 105 | + return; | ||
| 106 | + } | ||
| 107 | + let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); | ||
| 108 | + let spec = reader.spec(); | ||
| 109 | + let mut rng = Rng(0xdead_beef); | ||
| 110 | + let samples: Vec<i32> = reader | ||
| 111 | + .read_all_i32() | ||
| 112 | + .expect("pcm") | ||
| 113 | + .into_iter() | ||
| 114 | + .map(|s| (s << 8) | (rng.next() & 0xff) as i32) | ||
| 115 | + .collect(); | ||
| 116 | + let channels = spec.channels as u8; | ||
| 117 | + | ||
| 118 | + round_trip(spec.sample_rate, channels, 24, 4096, &samples); | ||
| 119 | + | ||
| 120 | + let per_frame = 4096 * channels as usize; | ||
| 121 | + let with_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); | ||
| 122 | + let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).len()).sum(); | ||
| 123 | + | ||
| 124 | + let mut without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); | ||
| 125 | + without_shift.set_byte_shift(false); | ||
| 126 | + let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).len()).sum(); | ||
| 127 | + | ||
| 128 | + eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes"); | ||
| 129 | + assert!( | ||
| 130 | + with_bytes < without_bytes, | ||
| 131 | + "bytes_shifted split ({with_bytes}) should beat forcing bytes_shifted=0 ({without_bytes})" | ||
| 132 | + ); | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +#[test] | ||
| 136 | +fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { | ||
| 137 | + // A smooth tone's first residuals are far bigger than the coder's | ||
| 138 | + // starting mean allows, so they go out as 24-bit raw escapes — the one | ||
| 139 | + // Golomb shape random data (whole-frame escape) and 16-bit-derived 24-bit | ||
| 140 | + // audio (bytes_shifted 1, 16 coded bits) never produce. | ||
| 141 | + let mut rng = Rng(0x0bad_cafe); | ||
| 142 | + let n = 4096 * 2 + 777; | ||
| 143 | + for channels in [1u8, 2] { | ||
| 144 | + let tone: Vec<i32> = (0..n * channels as usize) | ||
| 145 | + .map(|i| (2000.0 * (i as f64 / 64.0).sin()) as i32) | ||
| 146 | + .collect(); | ||
| 147 | + let wide: Vec<i32> = tone.iter().map(|&s| (s << 8) | (rng.next() & 0xff) as i32).collect(); | ||
| 148 | + for samples in [&tone, &wide] { | ||
| 149 | + for allow_shift in [true, false] { | ||
| 150 | + let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); | ||
| 151 | + enc.set_byte_shift(allow_shift); | ||
| 152 | + let mut dec = AlacDecoder::new(*enc.cookie()); | ||
| 153 | + let shift = enc.cookie().container_shift(); | ||
| 154 | + let mut decoded = Vec::new(); | ||
| 155 | + for chunk in samples.chunks(4096 * channels as usize) { | ||
| 156 | + decoded.extend(dec.decode(&enc.encode_frame(chunk)).expect("decode").iter().map(|&s| s >> shift)); | ||
| 157 | + } | ||
| 158 | + assert_eq!(&decoded, samples, "{channels}ch 24-bit tone, shift={allow_shift}"); | ||
| 159 | + | ||
| 160 | + // And the reference decoder agrees with what we wrote. | ||
| 161 | + let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); | ||
| 162 | + let got = ffmpeg_decode(&out_path, "s32le"); | ||
| 163 | + std::fs::remove_dir_all(&dir).ok(); | ||
| 164 | + let Some(got) = got else { continue }; | ||
| 165 | + let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); | ||
| 166 | + assert!(got == want, "{channels}ch 24-bit tone, shift={allow_shift}: reference decode differs"); | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + } | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +#[test] | ||
| 173 | +fn escape_frames_round_trip_random_data() { | ||
| 174 | + let mut rng = Rng(0x1234_5678); | ||
| 175 | + for &(channels, bit_depth) in &[(1u8, 16u8), (2, 16), (1, 24), (2, 24)] { | ||
| 176 | + // 4096 + a short tail, so the last frame is partial. | ||
| 177 | + let n = 4096 * 2 + 777; | ||
| 178 | + let samples: Vec<i32> = (0..n * channels as usize).map(|_| rng.range(bit_depth)).collect(); | ||
| 179 | + round_trip(48_000, channels, bit_depth, 4096, &samples); | ||
| 180 | + } | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +#[test] | ||
| 184 | +fn real_audio_round_trips_and_compresses() { | ||
| 185 | + let path = fixtures().join("wav16-stereo-48000.wav"); | ||
| 186 | + if !path.exists() { | ||
| 187 | + eprintln!("fixtures/audio absent (gitignored) — skipping"); | ||
| 188 | + return; | ||
| 189 | + } | ||
| 190 | + let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); | ||
| 191 | + let spec = reader.spec(); | ||
| 192 | + let samples = reader.read_all_i32().expect("pcm"); | ||
| 193 | + round_trip(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096, &samples); | ||
| 194 | + | ||
| 195 | + let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) | ||
| 196 | + .expect("encoder"); | ||
| 197 | + let per_frame = 4096 * spec.channels as usize; | ||
| 198 | + let mut coded_bytes = 0usize; | ||
| 199 | + for chunk in samples.chunks(per_frame) { | ||
| 200 | + coded_bytes += enc.encode_frame(chunk).len(); | ||
| 201 | + } | ||
| 202 | + let raw_bytes = samples.len() * 2; | ||
| 203 | + let ratio = coded_bytes as f64 / raw_bytes as f64; | ||
| 204 | + eprintln!("wav16-stereo-48000: {coded_bytes}/{raw_bytes} bytes, ratio {ratio:.4}"); | ||
| 205 | + assert!(ratio <= 0.75, "compression ratio {ratio:.4} > 0.75"); | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +#[test] | ||
| 209 | +fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { | ||
| 210 | + let path = fixtures().join("wav16-stereo-48000.wav"); | ||
| 211 | + if !path.exists() { | ||
| 212 | + eprintln!("fixtures/audio absent (gitignored) — skipping"); | ||
| 213 | + return; | ||
| 214 | + } | ||
| 215 | + let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); | ||
| 216 | + let spec = reader.spec(); | ||
| 217 | + let samples = reader.read_all_i32().expect("pcm"); | ||
| 218 | + let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) | ||
| 219 | + .expect("encoder"); | ||
| 220 | + | ||
| 221 | + let (dir, out_path) = mux_to_m4a(&enc, spec.channels as usize, spec.sample_rate, &samples); | ||
| 222 | + | ||
| 223 | + // Sanity without an oracle: our own demuxer/decoder reads it back | ||
| 224 | + // bit-exact against the source PCM. | ||
| 225 | + let mut demuxer = | ||
| 226 | + ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&out_path).expect("open"))).expect("mp4"); | ||
| 227 | + let track = demuxer | ||
| 228 | + .streams() | ||
| 229 | + .iter() | ||
| 230 | + .find(|s| s.params.codec == CodecId::Alac) | ||
| 231 | + .expect("alac track") | ||
| 232 | + .clone(); | ||
| 233 | + let mut dec = AlacDecoder::from_parameters(track.params).expect("cookie"); | ||
| 234 | + let shift = dec.cookie().container_shift(); | ||
| 235 | + let mut decoded = Vec::new(); | ||
| 236 | + loop { | ||
| 237 | + match demuxer.next_packet() { | ||
| 238 | + Ok(p) if p.stream != track.index => continue, | ||
| 239 | + Ok(p) => decoded.extend(dec.decode(&p.data).expect("decode").iter().map(|&s| s >> shift)), | ||
| 240 | + Err(e) if e.is_eof() => break, | ||
| 241 | + Err(e) => panic!("{e}"), | ||
| 242 | + } | ||
| 243 | + } | ||
| 244 | + assert_eq!(decoded, samples, "mux -> demux -> decode round trip"); | ||
| 245 | + | ||
| 246 | + // The oracle: ffprobe reads the track back as alac at the right rate and | ||
| 247 | + // channel count, and ffmpeg's own decode matches the source exactly. | ||
| 248 | + if Command::new("ffprobe").arg("-version").output().is_err() { | ||
| 249 | + eprintln!("ffprobe absent — skipping oracle checks"); | ||
| 250 | + return; | ||
| 251 | + } | ||
| 252 | + let probe = Command::new("ffprobe") | ||
| 253 | + .args([ | ||
| 254 | + "-v", "error", "-select_streams", "a:0", "-show_entries", | ||
| 255 | + "stream=codec_name,sample_rate,channels", | ||
| 256 | + "-of", "default=noprint_wrappers=1", | ||
| 257 | + ]) | ||
| 258 | + .arg(&out_path) | ||
| 259 | + .output() | ||
| 260 | + .expect("ffprobe"); | ||
| 261 | + let info = String::from_utf8_lossy(&probe.stdout); | ||
| 262 | + assert!(info.contains("codec_name=alac"), "{info}"); | ||
| 263 | + assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}"); | ||
| 264 | + assert!(info.contains(&format!("channels={}", spec.channels)), "{info}"); | ||
| 265 | + | ||
| 266 | + let Some(stdout) = ffmpeg_decode(&out_path, "s16le") else { return }; | ||
| 267 | + let want: Vec<i16> = samples.iter().map(|&s| s as i16).collect(); | ||
| 268 | + let got: Vec<i16> = stdout | ||
| 269 | + .chunks_exact(2) | ||
| 270 | + .map(|c| i16::from_le_bytes([c[0], c[1]])) | ||
| 271 | + .collect(); | ||
| 272 | + assert_eq!(got, want, "ffmpeg decode of the muxed file vs source PCM"); | ||
| 273 | + | ||
| 274 | + let _ = std::fs::remove_dir_all(&dir); | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | + | ||
| 278 | +/// Encode through our encoder, decode through ours and (when installed) the | ||
| 279 | +/// reference decoder via a real m4a; both must hand back `samples` exactly. | ||
| 280 | +fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, what: &str) { | ||
| 281 | + let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); | ||
| 282 | + enc.set_byte_shift(allow_shift); | ||
| 283 | + let mut dec = AlacDecoder::new(*enc.cookie()); | ||
| 284 | + let shift = enc.cookie().container_shift(); | ||
| 285 | + let mut decoded = Vec::new(); | ||
| 286 | + for chunk in samples.chunks(4096 * channels as usize) { | ||
| 287 | + decoded.extend(dec.decode(&enc.encode_frame(chunk)).expect("decode").iter().map(|&s| s >> shift)); | ||
| 288 | + } | ||
| 289 | + assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit, shift={allow_shift}"); | ||
| 290 | + | ||
| 291 | + let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); | ||
| 292 | + let got = ffmpeg_decode(&out_path, "s32le"); | ||
| 293 | + std::fs::remove_dir_all(&dir).ok(); | ||
| 294 | + let Some(got) = got else { return }; | ||
| 295 | + let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); | ||
| 296 | + assert!(got == want, "{what}: {channels}ch 24-bit, shift={allow_shift}: reference decode differs"); | ||
| 297 | +} | ||
| 298 | + | ||
| 299 | +#[test] | ||
| 300 | +fn mono_24_bit_ramp_round_trips_bit_exactly() { | ||
| 301 | + // A modular ramp whose wrap-around steps are wider than 2^23: the | ||
| 302 | + // residual of that step needs 25 bits, one more than the 24-bit escape | ||
| 303 | + // carries, so the encoder must wrap it the way the decoder does. | ||
| 304 | + for n in [1015usize, 1016, 1024, 2048, 4096] { | ||
| 305 | + let samples: Vec<i32> = (0..n).map(|i| ((i as i64 * 7919) % 8_000_000 - 4_000_000) as i32).collect(); | ||
| 306 | + for allow_shift in [true, false] { | ||
| 307 | + round_trip_both_decoders(1, &samples, allow_shift, &format!("ramp n={n}")); | ||
| 308 | + } | ||
| 309 | + } | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +#[test] | ||
| 313 | +fn mono_24_bit_full_scale_alternating_round_trips() { | ||
| 314 | + for n in [512usize, 4096] { | ||
| 315 | + let samples: Vec<i32> = (0..n).map(|i| if i % 2 == 0 { 8_388_607 } else { -8_388_607 }).collect(); | ||
| 316 | + round_trip_both_decoders(1, &samples, true, &format!("alternating n={n}")); | ||
| 317 | + } | ||
| 318 | +} | ||
| 319 | + | ||
| 320 | +#[test] | ||
| 321 | +fn fuzz_round_trips_bit_exactly() { | ||
| 322 | + let mut rng = Rng(0x5eed_f00d); | ||
| 323 | + for case in 0..200 { | ||
| 324 | + let bit_depth = [16u8, 24][rng.next() as usize % 2]; | ||
| 325 | + let channels = [1u8, 2][rng.next() as usize % 2]; | ||
| 326 | + let n = 1 + rng.next() as usize % 4097; | ||
| 327 | + let content = rng.next() % 4; | ||
| 328 | + let full = (1i64 << (bit_depth - 1)) - 1; | ||
| 329 | + let samples: Vec<i32> = (0..n * channels as usize) | ||
| 330 | + .map(|i| match content { | ||
| 331 | + 0 => rng.range(bit_depth), | ||
| 332 | + 1 => ((i as i64 * 7919) % (2 * full) - full) as i32, | ||
| 333 | + 2 => if i % 2 == 0 { full as i32 } else { -full as i32 }, | ||
| 334 | + _ => (full as f64 * 0.9 * (i as f64 / 37.0).sin()) as i32, | ||
| 335 | + }) | ||
| 336 | + .collect(); | ||
| 337 | + round_trip(48_000, channels, bit_depth, 4096, &samples); | ||
| 338 | + eprintln!("case {case}: {bit_depth}bit {channels}ch n={n} content={content} ok"); | ||
| 339 | + } | ||
| 340 | +} | ||
crates/ec-alac/tests/oracle.rsmodified+43 -0
| @@ -129,3 +129,46 @@ fn truncated_frames_are_refused_without_panicking() { | |||
| 129 | .is_empty() | 129 | .is_empty() |
| 130 | ); | 130 | ); |
| 131 | } | 131 | } |
| 132 | + | ||
| 133 | +/// A 24-bit tone with a dithered low byte, encoded by the reference encoder: | ||
| 134 | +/// its first residuals escape to raw 24-bit values — a Golomb shape none of | ||
| 135 | +/// the checked-in fixtures (16-bit, or 24-bit with a shifted low byte) carry. | ||
| 136 | +#[test] | ||
| 137 | +fn reference_encoded_24_bit_tone_decodes_bit_exactly() { | ||
| 138 | + if Command::new("ffmpeg").arg("-version").output().is_err() { | ||
| 139 | + eprintln!("ffmpeg absent — skipping"); | ||
| 140 | + return; | ||
| 141 | + } | ||
| 142 | + let dir = std::env::temp_dir().join(format!("ec-alac-tone-{}", std::process::id())); | ||
| 143 | + std::fs::create_dir_all(&dir).expect("tmp"); | ||
| 144 | + let raw = dir.join("tone.raw"); | ||
| 145 | + let m4a = dir.join("tone.m4a"); | ||
| 146 | + let mut seed = 0x0bad_cafeu32; | ||
| 147 | + let pcm: Vec<u8> = (0..48_000 * 2) | ||
| 148 | + .flat_map(|i| { | ||
| 149 | + seed ^= seed << 13; | ||
| 150 | + seed ^= seed >> 17; | ||
| 151 | + seed ^= seed << 5; | ||
| 152 | + let s = ((2000.0 * (i as f64 / 64.0).sin()) as i32) << 8 | (seed & 0xff) as i32; | ||
| 153 | + s.to_le_bytes() | ||
| 154 | + }) | ||
| 155 | + .collect(); | ||
| 156 | + std::fs::write(&raw, &pcm).expect("raw"); | ||
| 157 | + let enc = Command::new("ffmpeg") | ||
| 158 | + .args(["-nostdin", "-y", "-v", "error", "-f", "s32le", "-ar", "48000", "-ac", "2", "-i"]) | ||
| 159 | + .arg(&raw) | ||
| 160 | + .args(["-c:a", "alac", "-sample_fmt", "s32p"]) | ||
| 161 | + .arg(&m4a) | ||
| 162 | + .output() | ||
| 163 | + .expect("ffmpeg"); | ||
| 164 | + assert!(enc.status.success(), "{}", String::from_utf8_lossy(&enc.stderr)); | ||
| 165 | + | ||
| 166 | + let (cookie, got) = decode(&m4a); | ||
| 167 | + assert_eq!(cookie.bit_depth, 24); | ||
| 168 | + let shift = cookie.container_shift(); | ||
| 169 | + let got: Vec<u8> = got.iter().flat_map(|&s| (s >> shift << 8).to_le_bytes()).collect(); | ||
| 170 | + let want = ffmpeg(&m4a, "s32le"); | ||
| 171 | + std::fs::remove_dir_all(&dir).ok(); | ||
| 172 | + assert_eq!(got.len(), want.len()); | ||
| 173 | + assert!(got == want, "reference-encoded 24-bit tone: our decode differs from the reference decode"); | ||
| 174 | +} | ||