Mono/stereo ALAC encoder (cookie/escape frames + adaptive-Golomb LPC compression)
Browse files at this commit98a0f6fb83d54c75e9d87d831ee83ab071a88261Parent: b966d5e- feat
- mono/stereo ALAC encoder (cookie/escape frames + adaptive-Golomb LPC compression)
5 changed files +779 -2
- Cargo.lock +1 -0
- crates/ec-alac/Cargo.toml +1 -0
- crates/ec-alac/src/encode.rs +557 -0
- crates/ec-alac/src/lib.rs +35 -2
- crates/ec-alac/tests/encode.rs +185 -0
Cargo.lockmodified+1 -0
| @@ -246,6 +246,7 @@ version = "0.1.0" | ||
| 246 | 246 | dependencies = [ |
| 247 | 247 | "ec-core", |
| 248 | 248 | "ec-mp4", |
| 249 | + "ec-riff", | |
| 249 | 250 | ] |
| 250 | 251 | |
| 251 | 252 | [[package]] |
crates/ec-alac/Cargo.tomlmodified+1 -0
| @@ -11,3 +11,4 @@ ec-core = { workspace = true } | ||
| 11 | 11 | |
| 12 | 12 | [dev-dependencies] |
| 13 | 13 | ec-mp4 = { workspace = true } |
| 14 | +ec-riff = { workspace = true } |
crates/ec-alac/src/encode.rsadded+557 -0
| @@ -0,0 +1,557 @@ | ||
| 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 | + let q = n / m; | |
| 119 | + if q >= MAX_PREFIX { | |
| 120 | + sink.put(u32::MAX, MAX_PREFIX); | |
| 121 | + if maxbits > 0 { | |
| 122 | + sink.put(n, maxbits); | |
| 123 | + } | |
| 124 | + return; | |
| 125 | + } | |
| 126 | + if q > 0 { | |
| 127 | + sink.put(u32::MAX, q); | |
| 128 | + } | |
| 129 | + sink.put(0, 1); | |
| 130 | + if k > 1 { | |
| 131 | + let r = n - q * m; | |
| 132 | + match r { | |
| 133 | + 0 => sink.put(0, k - 1), | |
| 134 | + r => sink.put(r + 1, k), | |
| 135 | + } | |
| 136 | + } | |
| 137 | +} | |
| 138 | + | |
| 139 | +/// Adaptive-Golomb-encode `res` into `sink`, exactly inverting | |
| 140 | +/// `decode.rs`'s `Rice::decode` — same mean update, same zero-run escape. | |
| 141 | +fn rice_encode<S: BitSink>(sink: &mut S, cfg: &MagicCookie, pb_factor: u32, res: &[i32], chan_bits: u32) { | |
| 142 | + let kb = u32::from(cfg.kb).clamp(1, 31); | |
| 143 | + let pb = u32::from(cfg.pb) * pb_factor / 4; | |
| 144 | + let wb = (1u32 << kb) - 1; | |
| 145 | + let mut mean = u32::from(cfg.mb); | |
| 146 | + let mut zmode = 0u32; | |
| 147 | + let mut c = 0usize; | |
| 148 | + while c < res.len() { | |
| 149 | + let ndecode = zigzag(res[c]); | |
| 150 | + // Safe: `zmode` is only 1 right after a zero run that consumed every | |
| 151 | + // contiguous zero, so the sample here is never itself zero. | |
| 152 | + let n = ndecode - zmode; | |
| 153 | + let k = lg3a(mean >> QBSHIFT).min(kb); | |
| 154 | + let m = (1u32 << k) - 1; | |
| 155 | + golomb_write(sink, n, m, k, chan_bits); | |
| 156 | + c += 1; | |
| 157 | + | |
| 158 | + mean = pb | |
| 159 | + .wrapping_mul(ndecode) | |
| 160 | + .wrapping_add(mean) | |
| 161 | + .wrapping_sub(pb.wrapping_mul(mean) >> QBSHIFT); | |
| 162 | + if n > MEAN_CLAMP { | |
| 163 | + mean = MEAN_CLAMP; | |
| 164 | + } | |
| 165 | + | |
| 166 | + zmode = 0; | |
| 167 | + if (mean << MMULSHIFT) < QB && c < res.len() { | |
| 168 | + zmode = 1; | |
| 169 | + let k2 = (mean.leading_zeros() as i32 - BITOFF + ((mean + MOFF) >> MDENSHIFT) as i32) | |
| 170 | + .clamp(0, 31) as u32; | |
| 171 | + let mz = ((1u32 << k2) - 1) & wb; | |
| 172 | + let mut run = 0u32; | |
| 173 | + while (c + run as usize) < res.len() && res[c + run as usize] == 0 { | |
| 174 | + run += 1; | |
| 175 | + if run as usize >= (1 << MAX_RUN_BITS) - 1 { | |
| 176 | + break; | |
| 177 | + } | |
| 178 | + } | |
| 179 | + golomb_write(sink, run, mz, k2, MAX_RUN_BITS); | |
| 180 | + c += run as usize; | |
| 181 | + if run >= (1 << MAX_RUN_BITS) - 1 { | |
| 182 | + zmode = 0; | |
| 183 | + } | |
| 184 | + mean = 0; | |
| 185 | + } | |
| 186 | + } | |
| 187 | +} | |
| 188 | + | |
| 189 | +/// The forward twin of `decode.rs`'s `predict`: given the true samples `y` | |
| 190 | +/// (already in their coded width), compute the residuals a from-zero | |
| 191 | +/// sign-adapting filter of `order` taps and `den_shift` would need to | |
| 192 | +/// reproduce them exactly. The coefficients this implicitly walks through | |
| 193 | +/// are never returned — the encoder always states an all-zero starting | |
| 194 | +/// filter, so the decoder's own adaptation, run from the same zero start, | |
| 195 | +/// retraces this pass exactly. | |
| 196 | +fn analyze(y: &[i32], order: usize, den_shift: u32) -> Vec<i32> { | |
| 197 | + let n = y.len(); | |
| 198 | + let mut res = vec![0i32; n]; | |
| 199 | + if n == 0 { | |
| 200 | + return res; | |
| 201 | + } | |
| 202 | + res[0] = y[0]; | |
| 203 | + if order == ORDER_DIFF { | |
| 204 | + for j in 1..n { | |
| 205 | + res[j] = y[j].wrapping_sub(y[j - 1]); | |
| 206 | + } | |
| 207 | + return res; | |
| 208 | + } | |
| 209 | + if order == 0 || order >= n { | |
| 210 | + // Order 0 is decode.rs's "residuals are the samples verbatim"; a | |
| 211 | + // caller never asks for 0 < order >= n (`best_candidate` filters | |
| 212 | + // those out), so this path is only ever reached as the order-0 case. | |
| 213 | + res.copy_from_slice(y); | |
| 214 | + return res; | |
| 215 | + } | |
| 216 | + | |
| 217 | + let mut coefs = vec![0i32; order]; | |
| 218 | + for j in 1..=order { | |
| 219 | + res[j] = y[j].wrapping_sub(y[j - 1]); | |
| 220 | + } | |
| 221 | + let den_half = match den_shift { | |
| 222 | + 0 => 0, | |
| 223 | + s => 1i32 << (s - 1), | |
| 224 | + }; | |
| 225 | + for j in order..n - 1 { | |
| 226 | + let top = y[j - order]; | |
| 227 | + let mut sum = 0i32; | |
| 228 | + for (k, &c) in coefs.iter().enumerate() { | |
| 229 | + sum = sum.wrapping_add(c.wrapping_mul(y[j - k].wrapping_sub(top))); | |
| 230 | + } | |
| 231 | + let predicted = top.wrapping_add(sum.wrapping_add(den_half) >> den_shift); | |
| 232 | + let del = y[j + 1].wrapping_sub(predicted); | |
| 233 | + res[j + 1] = del; | |
| 234 | + | |
| 235 | + let mut del0 = del; | |
| 236 | + let sg = sign(del); | |
| 237 | + if sg > 0 { | |
| 238 | + for k in (0..order).rev() { | |
| 239 | + let dd = top.wrapping_sub(y[j - k]); | |
| 240 | + let s = sign(dd); | |
| 241 | + coefs[k] -= s; | |
| 242 | + del0 -= ((order - k) as i32).wrapping_mul(s.wrapping_mul(dd) >> den_shift); | |
| 243 | + if del0 <= 0 { | |
| 244 | + break; | |
| 245 | + } | |
| 246 | + } | |
| 247 | + } else 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 | + } | |
| 258 | + } | |
| 259 | + res | |
| 260 | +} | |
| 261 | + | |
| 262 | +/// One channel's chosen filter: the order field to write, the residuals it | |
| 263 | +/// produces, and its total cost in bits (16-bit plan header + coefficients | |
| 264 | +/// + the Rice-coded residuals), for comparing against every other choice. | |
| 265 | +struct Candidate { | |
| 266 | + order: u32, | |
| 267 | + res: Vec<i32>, | |
| 268 | + bits: u64, | |
| 269 | +} | |
| 270 | + | |
| 271 | +/// Cheapest of [`ORDER_CANDIDATES`] (plus the trivial order-0 "residuals are | |
| 272 | +/// the samples" case) for one channel of true samples. | |
| 273 | +fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) -> Candidate { | |
| 274 | + let mut orders: Vec<usize> = vec![0]; | |
| 275 | + orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len())); | |
| 276 | + let mut best: Option<Candidate> = None; | |
| 277 | + for order in orders { | |
| 278 | + let res = analyze(y, order, 9); | |
| 279 | + let mut cost = CostSink::default(); | |
| 280 | + rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits); | |
| 281 | + let bits = 16 + (order as u64) * 16 + cost.0; | |
| 282 | + if best.as_ref().is_none_or(|b| bits < b.bits) { | |
| 283 | + best = Some(Candidate { | |
| 284 | + order: order as u32, | |
| 285 | + res, | |
| 286 | + bits, | |
| 287 | + }); | |
| 288 | + } | |
| 289 | + } | |
| 290 | + best.unwrap_or(Candidate { | |
| 291 | + order: 0, | |
| 292 | + res: y.to_vec(), | |
| 293 | + bits: u64::MAX, | |
| 294 | + }) | |
| 295 | +} | |
| 296 | + | |
| 297 | +/// A channel's coded parameters and residuals, ready to write: the plan | |
| 298 | +/// header fields plus [`Candidate::res`]. | |
| 299 | +struct ChannelPlan { | |
| 300 | + order: u32, | |
| 301 | + pb_factor: u32, | |
| 302 | + res: Vec<i32>, | |
| 303 | +} | |
| 304 | + | |
| 305 | +const DEN_SHIFT: u32 = 9; | |
| 306 | +const PB_FACTOR: u32 = 4; | |
| 307 | + | |
| 308 | +fn write_plan<S: BitSink>(sink: &mut S, plan: &ChannelPlan) { | |
| 309 | + sink.put(0, 4); // mode: always the single (non-difference-doubled) pass. | |
| 310 | + sink.put(DEN_SHIFT, 4); | |
| 311 | + sink.put(PB_FACTOR, 3); | |
| 312 | + sink.put(plan.order, 5); | |
| 313 | + for _ in 0..plan.order { | |
| 314 | + sink.put(0, 16); // all-zero starting coefficients (see `analyze`). | |
| 315 | + } | |
| 316 | +} | |
| 317 | + | |
| 318 | +/// One SCE (mono) or CPE (stereo) element, choosing per-element between raw | |
| 319 | +/// (escape) and compressed, and for a pair, between direct L/R and a | |
| 320 | +/// mid/side mix, whichever is smaller. | |
| 321 | +fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samples: usize) { | |
| 322 | + w.put(0, 16); // element instance tag + 12 reserved bits. | |
| 323 | + let pair = planes.len() == 2; | |
| 324 | + let channels = planes.len() as u32; | |
| 325 | + let bit_depth = u32::from(cfg.bit_depth); | |
| 326 | + let partial = samples != cfg.frame_length as usize; | |
| 327 | + let raw_bits = u64::from(channels) * u64::from(bit_depth) * samples as u64; | |
| 328 | + | |
| 329 | + let compressed = (samples >= 2).then(|| { | |
| 330 | + let chan_bits = bit_depth + channels - 1; | |
| 331 | + if pair { | |
| 332 | + let (l, r) = (&planes[0], &planes[1]); | |
| 333 | + let lc = best_candidate(cfg, l, chan_bits, PB_FACTOR); | |
| 334 | + let rc = best_candidate(cfg, r, chan_bits, PB_FACTOR); | |
| 335 | + let lr_bits = lc.bits + rc.bits; | |
| 336 | + | |
| 337 | + // mix_bits = 1, mix_res = 1: v = l - r, u = r + (v >> 1). | |
| 338 | + let (mut u, mut v) = (vec![0i32; samples], vec![0i32; samples]); | |
| 339 | + for i in 0..samples { | |
| 340 | + v[i] = l[i] - r[i]; | |
| 341 | + u[i] = r[i] + (v[i] >> 1); | |
| 342 | + } | |
| 343 | + let uc = best_candidate(cfg, &u, chan_bits, PB_FACTOR); | |
| 344 | + let vc = best_candidate(cfg, &v, chan_bits, PB_FACTOR); | |
| 345 | + let ms_bits = uc.bits + vc.bits; | |
| 346 | + | |
| 347 | + match ms_bits < lr_bits { | |
| 348 | + true => (1u32, 1i32, vec![plan_of(uc), plan_of(vc)], ms_bits), | |
| 349 | + false => (2u32, 0i32, vec![plan_of(lc), plan_of(rc)], lr_bits), | |
| 350 | + } | |
| 351 | + } else { | |
| 352 | + let c0 = best_candidate(cfg, &planes[0], chan_bits, PB_FACTOR); | |
| 353 | + let bits = c0.bits; | |
| 354 | + (0u32, 0i32, vec![plan_of(c0)], bits) | |
| 355 | + } | |
| 356 | + }); | |
| 357 | + | |
| 358 | + let use_compressed = compressed | |
| 359 | + .as_ref() | |
| 360 | + .is_some_and(|(_, _, _, bits)| 16 + bits < raw_bits.max(1)); | |
| 361 | + | |
| 362 | + w.put(partial as u32, 1); | |
| 363 | + w.put(0, 2); // bytes_shifted: always 0 (corner-cut, see module docs). | |
| 364 | + w.put(!use_compressed as u32, 1); | |
| 365 | + if partial { | |
| 366 | + w.put((samples as u32) >> 16, 16); | |
| 367 | + w.put(samples as u32 & 0xffff, 16); | |
| 368 | + } | |
| 369 | + | |
| 370 | + match use_compressed { | |
| 371 | + false => { | |
| 372 | + let chan_bits = bit_depth; | |
| 373 | + for i in 0..samples { | |
| 374 | + for plane in planes { | |
| 375 | + w.put(plane[i] as u32 & mask(chan_bits), chan_bits); | |
| 376 | + } | |
| 377 | + } | |
| 378 | + } | |
| 379 | + true => { | |
| 380 | + let (mix_bits, mix_res, plans, _) = compressed.unwrap(); | |
| 381 | + w.put(mix_bits, 8); | |
| 382 | + w.put((mix_res as i8) as u8 as u32, 8); | |
| 383 | + for plan in &plans { | |
| 384 | + write_plan(w, plan); | |
| 385 | + } | |
| 386 | + let chan_bits = bit_depth + channels - 1; | |
| 387 | + for plan in &plans { | |
| 388 | + rice_encode(w, cfg, plan.pb_factor, &plan.res, chan_bits); | |
| 389 | + } | |
| 390 | + } | |
| 391 | + } | |
| 392 | +} | |
| 393 | + | |
| 394 | +fn plan_of(c: Candidate) -> ChannelPlan { | |
| 395 | + ChannelPlan { | |
| 396 | + order: c.order, | |
| 397 | + pb_factor: PB_FACTOR, | |
| 398 | + res: c.res, | |
| 399 | + } | |
| 400 | +} | |
| 401 | + | |
| 402 | +/// `n` low bits set, for masking a two's-complement value into an escape's | |
| 403 | +/// raw field. | |
| 404 | +fn mask(n: u32) -> u32 { | |
| 405 | + match n { | |
| 406 | + 32 => u32::MAX, | |
| 407 | + n => (1 << n) - 1, | |
| 408 | + } | |
| 409 | +} | |
| 410 | + | |
| 411 | +/// An ALAC encoder for one mono or stereo stream. | |
| 412 | +#[derive(Debug)] | |
| 413 | +pub struct AlacEncoder { | |
| 414 | + cookie: MagicCookie, | |
| 415 | + params: CodecParameters, | |
| 416 | + channels: usize, | |
| 417 | + pending: Vec<i32>, | |
| 418 | + packets: std::collections::VecDeque<Vec<u8>>, | |
| 419 | + eof: bool, | |
| 420 | +} | |
| 421 | + | |
| 422 | +impl AlacEncoder { | |
| 423 | + /// An encoder for a mono or stereo stream. `bit_depth` is 16 or 24; | |
| 424 | + /// `frame_length` is the samples-per-channel every full frame carries | |
| 425 | + /// (Apple's own encoder writes 4096). | |
| 426 | + pub fn new(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32) -> Result<AlacEncoder> { | |
| 427 | + if !(1..=2).contains(&channels) { | |
| 428 | + return Err(Error::unsupported( | |
| 429 | + format!("ALAC encoding {channels} channels"), | |
| 430 | + "this encoder writes mono and stereo only", | |
| 431 | + )); | |
| 432 | + } | |
| 433 | + let cookie = MagicCookie { | |
| 434 | + frame_length, | |
| 435 | + compatible_version: 0, | |
| 436 | + bit_depth, | |
| 437 | + pb: 40, | |
| 438 | + mb: 10, | |
| 439 | + kb: 14, | |
| 440 | + channels, | |
| 441 | + max_run: 255, | |
| 442 | + max_frame_bytes: 0, | |
| 443 | + avg_bit_rate: 0, | |
| 444 | + sample_rate, | |
| 445 | + }; | |
| 446 | + let mut params = crate::codec_parameters(&cookie); | |
| 447 | + params.extradata = Some(cookie.extradata_box().into()); | |
| 448 | + Ok(AlacEncoder { | |
| 449 | + cookie, | |
| 450 | + params, | |
| 451 | + channels: channels as usize, | |
| 452 | + pending: Vec::new(), | |
| 453 | + packets: std::collections::VecDeque::new(), | |
| 454 | + eof: false, | |
| 455 | + }) | |
| 456 | + } | |
| 457 | + | |
| 458 | + /// What this encoder states about the stream it writes. | |
| 459 | + pub fn cookie(&self) -> &MagicCookie { | |
| 460 | + &self.cookie | |
| 461 | + } | |
| 462 | + | |
| 463 | + /// Encode one frame: `samples` interleaved, true PCM range (not the | |
| 464 | + /// container-shifted range [`AlacDecoder::decode`] hands back), up to | |
| 465 | + /// `frame_length` samples per channel — a shorter slice writes a partial | |
| 466 | + /// frame, exactly as a stream's last frame does. | |
| 467 | + pub fn encode_frame(&self, samples: &[i32]) -> Vec<u8> { | |
| 468 | + let channels = self.channels; | |
| 469 | + let n = samples.len() / channels; | |
| 470 | + let mut planes: Vec<Vec<i32>> = vec![Vec::with_capacity(n); channels]; | |
| 471 | + for chunk in samples.chunks_exact(channels) { | |
| 472 | + for (c, plane) in planes.iter_mut().enumerate() { | |
| 473 | + plane.push(chunk[c]); | |
| 474 | + } | |
| 475 | + } | |
| 476 | + let mut w = BitWriter::default(); | |
| 477 | + w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3); | |
| 478 | + write_element(&self.cookie, &mut w, &planes, n); | |
| 479 | + w.put(ID_END, 3); | |
| 480 | + w.finish() | |
| 481 | + } | |
| 482 | +} | |
| 483 | + | |
| 484 | +impl Encoder for AlacEncoder { | |
| 485 | + fn codec_parameters(&self) -> &CodecParameters { | |
| 486 | + &self.params | |
| 487 | + } | |
| 488 | + | |
| 489 | + fn send_frame(&mut self, frame: &Frame) -> Result<()> { | |
| 490 | + let Frame::Audio(audio) = frame else { | |
| 491 | + return Err(Error::corrupt("video frame pushed into an ALAC encoder")); | |
| 492 | + }; | |
| 493 | + let channels = self.channels; | |
| 494 | + let shift = self.cookie.container_shift(); | |
| 495 | + let want = self.cookie.sample_format(); | |
| 496 | + if audio.format != want { | |
| 497 | + return Err(Error::unsupported( | |
| 498 | + format!("{:?} input", audio.format), | |
| 499 | + "this encoder takes samples in the cookie's own sample format", | |
| 500 | + )); | |
| 501 | + } | |
| 502 | + let mut interleaved = Vec::with_capacity(audio.samples * channels); | |
| 503 | + match (audio.planar, want) { | |
| 504 | + (false, SampleFormat::S16) => { | |
| 505 | + for pair in audio.data[0].chunks_exact(2).take(audio.samples * channels) { | |
| 506 | + interleaved.push(i32::from(i16::from_ne_bytes([pair[0], pair[1]])) >> shift); | |
| 507 | + } | |
| 508 | + } | |
| 509 | + (false, _) => { | |
| 510 | + for word in audio.data[0].chunks_exact(4).take(audio.samples * channels) { | |
| 511 | + interleaved.push(i32::from_ne_bytes([word[0], word[1], word[2], word[3]]) >> shift); | |
| 512 | + } | |
| 513 | + } | |
| 514 | + (true, SampleFormat::S16) => { | |
| 515 | + for i in 0..audio.samples { | |
| 516 | + for plane in audio.data.iter().take(channels) { | |
| 517 | + let at = i * 2; | |
| 518 | + interleaved.push(i32::from(i16::from_ne_bytes([plane[at], plane[at + 1]])) >> shift); | |
| 519 | + } | |
| 520 | + } | |
| 521 | + } | |
| 522 | + (true, _) => { | |
| 523 | + for i in 0..audio.samples { | |
| 524 | + for plane in audio.data.iter().take(channels) { | |
| 525 | + let at = i * 4; | |
| 526 | + let w = [plane[at], plane[at + 1], plane[at + 2], plane[at + 3]]; | |
| 527 | + interleaved.push(i32::from_ne_bytes(w) >> shift); | |
| 528 | + } | |
| 529 | + } | |
| 530 | + } | |
| 531 | + } | |
| 532 | + self.pending.extend(interleaved); | |
| 533 | + let per_frame = self.cookie.frame_length as usize * channels; | |
| 534 | + while self.pending.len() >= per_frame { | |
| 535 | + let frame: Vec<i32> = self.pending.drain(..per_frame).collect(); | |
| 536 | + self.packets.push_back(self.encode_frame(&frame)); | |
| 537 | + } | |
| 538 | + Ok(()) | |
| 539 | + } | |
| 540 | + | |
| 541 | + fn receive_packet(&mut self) -> Result<Packet> { | |
| 542 | + match self.packets.pop_front() { | |
| 543 | + Some(data) => Ok(Packet::new(0, ec_core::timebase::TimeBase::new(1, i64::from(self.cookie.sample_rate)), data)), | |
| 544 | + None if self.eof => Err(Error::Eof), | |
| 545 | + None => Err(Error::NeedMore), | |
| 546 | + } | |
| 547 | + } | |
| 548 | + | |
| 549 | + fn flush(&mut self) -> Result<()> { | |
| 550 | + if !self.pending.is_empty() { | |
| 551 | + let frame = std::mem::take(&mut self.pending); | |
| 552 | + self.packets.push_back(self.encode_frame(&frame)); | |
| 553 | + } | |
| 554 | + self.eof = true; | |
| 555 | + Ok(()) | |
| 556 | + } | |
| 557 | +} |
crates/ec-alac/src/lib.rsmodified+35 -2
| @@ -12,8 +12,8 @@ | ||
| 12 | 12 | //! container carries as extradata: the frame length, the bit depth and the |
| 13 | 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 | |
| 16 | -//! pretending otherwise. | |
| 15 | +//! - [`AlacEncoder`], the mirror image: frames in, coded packets out, for a | |
| 16 | +//! container that wants to write ALAC instead of read it. | |
| 17 | 17 | //! |
| 18 | 18 | //! **Clean room.** Written from the published ALAC format description; Apple's |
| 19 | 19 | //! decoder sources were not read. Samples are returned shifted into their PCM |
| @@ -24,6 +24,9 @@ | ||
| 24 | 24 | #![warn(missing_docs)] |
| 25 | 25 | |
| 26 | 26 | mod decode; |
| 27 | +mod encode; | |
| 28 | + | |
| 29 | +pub use encode::AlacEncoder; | |
| 27 | 30 | |
| 28 | 31 | use ec_core::error::{Error, Result}; |
| 29 | 32 | use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; |
| @@ -133,6 +136,36 @@ impl MagicCookie { | ||
| 133 | 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 | 171 | /// Where each output channel sits in the stream's own coded order. |
crates/ec-alac/tests/encode.rsadded+185 -0
| @@ -0,0 +1,185 @@ | ||
| 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 | +#[test] | |
| 54 | +fn escape_frames_round_trip_random_data() { | |
| 55 | + let mut rng = Rng(0x1234_5678); | |
| 56 | + for &(channels, bit_depth) in &[(1u8, 16u8), (2, 16), (1, 24), (2, 24)] { | |
| 57 | + // 4096 + a short tail, so the last frame is partial. | |
| 58 | + let n = 4096 * 2 + 777; | |
| 59 | + let samples: Vec<i32> = (0..n * channels as usize).map(|_| rng.range(bit_depth)).collect(); | |
| 60 | + round_trip(48_000, channels, bit_depth, 4096, &samples); | |
| 61 | + } | |
| 62 | +} | |
| 63 | + | |
| 64 | +#[test] | |
| 65 | +fn real_audio_round_trips_and_compresses() { | |
| 66 | + let path = fixtures().join("wav16-stereo-48000.wav"); | |
| 67 | + if !path.exists() { | |
| 68 | + eprintln!("fixtures/audio absent (gitignored) — skipping"); | |
| 69 | + return; | |
| 70 | + } | |
| 71 | + let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); | |
| 72 | + let spec = reader.spec(); | |
| 73 | + let samples = reader.read_all_i32().expect("pcm"); | |
| 74 | + round_trip(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096, &samples); | |
| 75 | + | |
| 76 | + let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) | |
| 77 | + .expect("encoder"); | |
| 78 | + let per_frame = 4096 * spec.channels as usize; | |
| 79 | + let mut coded_bytes = 0usize; | |
| 80 | + for chunk in samples.chunks(per_frame) { | |
| 81 | + coded_bytes += enc.encode_frame(chunk).len(); | |
| 82 | + } | |
| 83 | + let raw_bytes = samples.len() * 2; | |
| 84 | + let ratio = coded_bytes as f64 / raw_bytes as f64; | |
| 85 | + eprintln!("wav16-stereo-48000: {coded_bytes}/{raw_bytes} bytes, ratio {ratio:.4}"); | |
| 86 | + assert!(ratio <= 0.75, "compression ratio {ratio:.4} > 0.75"); | |
| 87 | +} | |
| 88 | + | |
| 89 | +#[test] | |
| 90 | +fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { | |
| 91 | + let path = fixtures().join("wav16-stereo-48000.wav"); | |
| 92 | + if !path.exists() { | |
| 93 | + eprintln!("fixtures/audio absent (gitignored) — skipping"); | |
| 94 | + return; | |
| 95 | + } | |
| 96 | + let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); | |
| 97 | + let spec = reader.spec(); | |
| 98 | + let samples = reader.read_all_i32().expect("pcm"); | |
| 99 | + let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) | |
| 100 | + .expect("encoder"); | |
| 101 | + | |
| 102 | + let mut mp4 = ec_mp4::Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); | |
| 103 | + let time_base = TimeBase::new(1, i64::from(spec.sample_rate)); | |
| 104 | + let stream = mp4 | |
| 105 | + .add_stream(StreamInfo::new(0, time_base, enc.codec_parameters().clone())) | |
| 106 | + .expect("add_stream"); | |
| 107 | + | |
| 108 | + let per_frame = 4096 * spec.channels as usize; | |
| 109 | + let mut pts = 0i64; | |
| 110 | + for chunk in samples.chunks(per_frame) { | |
| 111 | + let n = chunk.len() / spec.channels as usize; | |
| 112 | + let data = enc.encode_frame(chunk); | |
| 113 | + let mut packet = Packet::new(stream, time_base, data).with_pts(pts); | |
| 114 | + packet.duration = Some(n as i64); | |
| 115 | + mp4.write_packet(&packet).expect("write_packet"); | |
| 116 | + pts += n as i64; | |
| 117 | + } | |
| 118 | + mp4.finish().expect("finish"); | |
| 119 | + let bytes = mp4.into_inner().into_inner(); | |
| 120 | + | |
| 121 | + let dir = std::env::temp_dir().join(format!("ec-alac-mux-test-{}", std::process::id())); | |
| 122 | + std::fs::create_dir_all(&dir).unwrap(); | |
| 123 | + let out_path = dir.join("out.m4a"); | |
| 124 | + std::fs::write(&out_path, &bytes).expect("write m4a"); | |
| 125 | + | |
| 126 | + // Sanity without an oracle: our own demuxer/decoder reads it back | |
| 127 | + // bit-exact against the source PCM. | |
| 128 | + let mut demuxer = | |
| 129 | + ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&out_path).expect("open"))).expect("mp4"); | |
| 130 | + let track = demuxer | |
| 131 | + .streams() | |
| 132 | + .iter() | |
| 133 | + .find(|s| s.params.codec == CodecId::Alac) | |
| 134 | + .expect("alac track") | |
| 135 | + .clone(); | |
| 136 | + let mut dec = AlacDecoder::from_parameters(track.params).expect("cookie"); | |
| 137 | + let shift = dec.cookie().container_shift(); | |
| 138 | + let mut decoded = Vec::new(); | |
| 139 | + loop { | |
| 140 | + match demuxer.next_packet() { | |
| 141 | + Ok(p) if p.stream != track.index => continue, | |
| 142 | + Ok(p) => decoded.extend(dec.decode(&p.data).expect("decode").iter().map(|&s| s >> shift)), | |
| 143 | + Err(e) if e.is_eof() => break, | |
| 144 | + Err(e) => panic!("{e}"), | |
| 145 | + } | |
| 146 | + } | |
| 147 | + assert_eq!(decoded, samples, "mux -> demux -> decode round trip"); | |
| 148 | + | |
| 149 | + // The oracle: ffprobe reads the track back as alac at the right rate and | |
| 150 | + // channel count, and ffmpeg's own decode matches the source exactly. | |
| 151 | + if Command::new("ffprobe").arg("-version").output().is_err() { | |
| 152 | + eprintln!("ffprobe absent — skipping oracle checks"); | |
| 153 | + return; | |
| 154 | + } | |
| 155 | + let probe = Command::new("ffprobe") | |
| 156 | + .args([ | |
| 157 | + "-v", "error", "-select_streams", "a:0", "-show_entries", | |
| 158 | + "stream=codec_name,sample_rate,channels", | |
| 159 | + "-of", "default=noprint_wrappers=1", | |
| 160 | + ]) | |
| 161 | + .arg(&out_path) | |
| 162 | + .output() | |
| 163 | + .expect("ffprobe"); | |
| 164 | + let info = String::from_utf8_lossy(&probe.stdout); | |
| 165 | + assert!(info.contains("codec_name=alac"), "{info}"); | |
| 166 | + assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}"); | |
| 167 | + assert!(info.contains(&format!("channels={}", spec.channels)), "{info}"); | |
| 168 | + | |
| 169 | + let decode = Command::new("ffmpeg") | |
| 170 | + .args(["-nostdin", "-v", "error", "-i"]) | |
| 171 | + .arg(&out_path) | |
| 172 | + .args(["-f", "s16le", "-"]) | |
| 173 | + .output() | |
| 174 | + .expect("ffmpeg"); | |
| 175 | + assert!(decode.status.success(), "{}", String::from_utf8_lossy(&decode.stderr)); | |
| 176 | + let want: Vec<i16> = samples.iter().map(|&s| s as i16).collect(); | |
| 177 | + let got: Vec<i16> = decode | |
| 178 | + .stdout | |
| 179 | + .chunks_exact(2) | |
| 180 | + .map(|c| i16::from_le_bytes([c[0], c[1]])) | |
| 181 | + .collect(); | |
| 182 | + assert_eq!(got, want, "ffmpeg decode of the muxed file vs source PCM"); | |
| 183 | + | |
| 184 | + let _ = std::fs::remove_dir_all(&dir); | |
| 185 | +} |