diff --git a/crates/ec-alac/src/encode.rs b/crates/ec-alac/src/encode.rs index 5ff06bc3..9ba0bb82 100644 --- a/crates/ec-alac/src/encode.rs +++ b/crates/ec-alac/src/encode.rs @@ -115,6 +115,7 @@ fn golomb_write(sink: &mut S, n: u32, m: u32, k: u32, maxbits: u32) sink.put(n, maxbits.max(1)); return; } + debug_assert!(maxbits >= 32 || n >> maxbits == 0, "Golomb value {n} does not fit its {maxbits}-bit escape"); let q = n / m; if q >= MAX_PREFIX { sink.put(u32::MAX, MAX_PREFIX); @@ -193,16 +194,25 @@ fn rice_encode(sink: &mut S, cfg: &MagicCookie, pb_factor: u32, res: /// are never returned — the encoder always states an all-zero starting /// filter, so the decoder's own adaptation, run from the same zero start, /// retraces this pass exactly. -fn analyze(y: &[i32], order: usize, den_shift: u32) -> Vec { +/// +/// Every residual is wrapped to `chan_bits` exactly as `decode.rs`'s +/// `predict` wraps its reconstruction (`clamp`, decode.rs:242): a difference +/// of two in-range samples can need one bit more than the samples do, the +/// Golomb escape carries only `chan_bits` of it, and the decoder's add then +/// wraps the truncated value back to the right sample. Adapting on the +/// unwrapped residual's sign would diverge from the decoder's walk. +fn analyze(y: &[i32], order: usize, den_shift: u32, chan_bits: u32) -> Vec { let n = y.len(); let mut res = vec![0i32; n]; if n == 0 { return res; } + let chan_shift = 32 - chan_bits; + let wrap = |v: i32| ((v as u32) << chan_shift) as i32 >> chan_shift; res[0] = y[0]; if order == ORDER_DIFF { for j in 1..n { - res[j] = y[j].wrapping_sub(y[j - 1]); + res[j] = wrap(y[j].wrapping_sub(y[j - 1])); } return res; } @@ -216,7 +226,7 @@ fn analyze(y: &[i32], order: usize, den_shift: u32) -> Vec { let mut coefs = vec![0i32; order]; for j in 1..=order { - res[j] = y[j].wrapping_sub(y[j - 1]); + res[j] = wrap(y[j].wrapping_sub(y[j - 1])); } let den_half = match den_shift { 0 => 0, @@ -229,7 +239,7 @@ fn analyze(y: &[i32], order: usize, den_shift: u32) -> Vec { sum = sum.wrapping_add(c.wrapping_mul(y[j - k].wrapping_sub(top))); } let predicted = top.wrapping_add(sum.wrapping_add(den_half) >> den_shift); - let del = y[j + 1].wrapping_sub(predicted); + let del = wrap(y[j + 1].wrapping_sub(predicted)); res[j + 1] = del; let mut del0 = del; @@ -279,7 +289,7 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len())); let mut best: Option = None; for order in orders { - let res = analyze(y, order, 9); + let res = analyze(y, order, 9, chan_bits); let mut cost = CostSink::default(); rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits); let bits = 16 + (order as u64) * 16 + cost.0; @@ -469,6 +479,12 @@ impl AlacEncoder { /// `frame_length` is the samples-per-channel every full frame carries /// (Apple's own encoder writes 4096). pub fn new(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32) -> Result { + if !matches!(bit_depth, 16 | 24) { + return Err(Error::unsupported( + format!("ALAC encoding {bit_depth}-bit samples"), + "this encoder writes 16 and 24 bit only", + )); + } if !(1..=2).contains(&channels) { return Err(Error::unsupported( format!("ALAC encoding {channels} channels"), diff --git a/crates/ec-alac/tests/encode.rs b/crates/ec-alac/tests/encode.rs index 2a3afc2c..cb078ed6 100644 --- a/crates/ec-alac/tests/encode.rs +++ b/crates/ec-alac/tests/encode.rs @@ -274,3 +274,67 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { let _ = std::fs::remove_dir_all(&dir); } + +/// Encode through our encoder, decode through ours and (when installed) the +/// reference decoder via a real m4a; both must hand back `samples` exactly. +fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, what: &str) { + let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); + enc.set_byte_shift(allow_shift); + let mut dec = AlacDecoder::new(*enc.cookie()); + let shift = enc.cookie().container_shift(); + let mut decoded = Vec::new(); + for chunk in samples.chunks(4096 * channels as usize) { + decoded.extend(dec.decode(&enc.encode_frame(chunk)).expect("decode").iter().map(|&s| s >> shift)); + } + assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit, shift={allow_shift}"); + + let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); + let got = ffmpeg_decode(&out_path, "s32le"); + std::fs::remove_dir_all(&dir).ok(); + let Some(got) = got else { return }; + let want: Vec = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); + assert!(got == want, "{what}: {channels}ch 24-bit, shift={allow_shift}: reference decode differs"); +} + +#[test] +fn mono_24_bit_ramp_round_trips_bit_exactly() { + // A modular ramp whose wrap-around steps are wider than 2^23: the + // residual of that step needs 25 bits, one more than the 24-bit escape + // carries, so the encoder must wrap it the way the decoder does. + for n in [1015usize, 1016, 1024, 2048, 4096] { + let samples: Vec = (0..n).map(|i| ((i as i64 * 7919) % 8_000_000 - 4_000_000) as i32).collect(); + for allow_shift in [true, false] { + round_trip_both_decoders(1, &samples, allow_shift, &format!("ramp n={n}")); + } + } +} + +#[test] +fn mono_24_bit_full_scale_alternating_round_trips() { + for n in [512usize, 4096] { + let samples: Vec = (0..n).map(|i| if i % 2 == 0 { 8_388_607 } else { -8_388_607 }).collect(); + round_trip_both_decoders(1, &samples, true, &format!("alternating n={n}")); + } +} + +#[test] +fn fuzz_round_trips_bit_exactly() { + let mut rng = Rng(0x5eed_f00d); + for case in 0..200 { + let bit_depth = [16u8, 24][rng.next() as usize % 2]; + let channels = [1u8, 2][rng.next() as usize % 2]; + let n = 1 + rng.next() as usize % 4097; + let content = rng.next() % 4; + let full = (1i64 << (bit_depth - 1)) - 1; + let samples: Vec = (0..n * channels as usize) + .map(|i| match content { + 0 => rng.range(bit_depth), + 1 => ((i as i64 * 7919) % (2 * full) - full) as i32, + 2 => if i % 2 == 0 { full as i32 } else { -full as i32 }, + _ => (full as f64 * 0.9 * (i as f64 / 37.0).sin()) as i32, + }) + .collect(); + round_trip(48_000, channels, bit_depth, 4096, &samples); + eprintln!("case {case}: {bit_depth}bit {channels}ch n={n} content={content} ok"); + } +}