forge
Explore
Log in

Don't you dare go Hollow

Wrap predictor residuals to chan_bits the way the decoder does

Browse files at this commit

70bf744437a0d834489f0f59549acdeac91ec918Ahmet Kaan GümüşParent: b8b47ce
  • fix
    • wrap predictor residuals to chan_bits the way the decoder does
Show full message
fix(alac-enc): wrap predictor residuals to chan_bits the way the decoder does

A residual of two in-range samples can need one bit more than the samples
(24-bit ramp wrap-around, full-scale alternating at 16 coded bits after a
byte shift); the Golomb escape carries only chan_bits of it, so the value
truncated on the wire and the decoder's clamp() reconstructed the wrong
sample, or lost sync entirely. analyze() now wraps every residual to
chan_bits before zigzag and before the sign-adapt step, matching
decode.rs predict(). Guard AlacEncoder::new to the 16/24-bit depths
actually tested; add ramp/alternating/fuzz round-trip tests.
crates/ec-alac/src/encode.rsmodified+21 -5
@@ -115,6 +115,7 @@ fn golomb_write<S: BitSink>(sink: &mut S, n: u32, m: u32, k: u32, maxbits: u32)
115 sink.put(n, maxbits.max(1));115 sink.put(n, maxbits.max(1));
116 return;116 return;
117 }117 }
118+ debug_assert!(maxbits >= 32 || n >> maxbits == 0, "Golomb value {n} does not fit its {maxbits}-bit escape");
118 let q = n / m;119 let q = n / m;
119 if q >= MAX_PREFIX {120 if q >= MAX_PREFIX {
120 sink.put(u32::MAX, MAX_PREFIX);121 sink.put(u32::MAX, MAX_PREFIX);
@@ -193,16 +194,25 @@ fn rice_encode<S: BitSink>(sink: &mut S, cfg: &MagicCookie, pb_factor: u32, res:
193 /// are never returned — the encoder always states an all-zero starting194 /// 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 /// filter, so the decoder's own adaptation, run from the same zero start,
195 /// retraces this pass exactly.196 /// retraces this pass exactly.
196-fn analyze(y: &[i32], order: usize, den_shift: u32) -> Vec<i32> {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> {
197 let n = y.len();205 let n = y.len();
198 let mut res = vec![0i32; n];206 let mut res = vec![0i32; n];
199 if n == 0 {207 if n == 0 {
200 return res;208 return res;
201 }209 }
210+ let chan_shift = 32 - chan_bits;
211+ let wrap = |v: i32| ((v as u32) << chan_shift) as i32 >> chan_shift;
202 res[0] = y[0];212 res[0] = y[0];
203 if order == ORDER_DIFF {213 if order == ORDER_DIFF {
204 for j in 1..n {214 for j in 1..n {
205- res[j] = y[j].wrapping_sub(y[j - 1]);215+ res[j] = wrap(y[j].wrapping_sub(y[j - 1]));
206 }216 }
207 return res;217 return res;
208 }218 }
@@ -216,7 +226,7 @@ fn analyze(y: &[i32], order: usize, den_shift: u32) -> Vec<i32> {
216 226
217 let mut coefs = vec![0i32; order];227 let mut coefs = vec![0i32; order];
218 for j in 1..=order {228 for j in 1..=order {
219- res[j] = y[j].wrapping_sub(y[j - 1]);229+ res[j] = wrap(y[j].wrapping_sub(y[j - 1]));
220 }230 }
221 let den_half = match den_shift {231 let den_half = match den_shift {
222 0 => 0,232 0 => 0,
@@ -229,7 +239,7 @@ fn analyze(y: &[i32], order: usize, den_shift: u32) -> Vec<i32> {
229 sum = sum.wrapping_add(c.wrapping_mul(y[j - k].wrapping_sub(top)));239 sum = sum.wrapping_add(c.wrapping_mul(y[j - k].wrapping_sub(top)));
230 }240 }
231 let predicted = top.wrapping_add(sum.wrapping_add(den_half) >> den_shift);241 let predicted = top.wrapping_add(sum.wrapping_add(den_half) >> den_shift);
232- let del = y[j + 1].wrapping_sub(predicted);242+ let del = wrap(y[j + 1].wrapping_sub(predicted));
233 res[j + 1] = del;243 res[j + 1] = del;
234 244
235 let mut del0 = del;245 let mut del0 = del;
@@ -279,7 +289,7 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32)
279 orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len()));289 orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len()));
280 let mut best: Option<Candidate> = None;290 let mut best: Option<Candidate> = None;
281 for order in orders {291 for order in orders {
282- let res = analyze(y, order, 9);292+ let res = analyze(y, order, 9, chan_bits);
283 let mut cost = CostSink::default();293 let mut cost = CostSink::default();
284 rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits);294 rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits);
285 let bits = 16 + (order as u64) * 16 + cost.0;295 let bits = 16 + (order as u64) * 16 + cost.0;
@@ -469,6 +479,12 @@ impl AlacEncoder {
469 /// `frame_length` is the samples-per-channel every full frame carries479 /// `frame_length` is the samples-per-channel every full frame carries
470 /// (Apple's own encoder writes 4096).480 /// (Apple's own encoder writes 4096).
471 pub fn new(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32) -> Result<AlacEncoder> {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+ }
472 if !(1..=2).contains(&channels) {488 if !(1..=2).contains(&channels) {
473 return Err(Error::unsupported(489 return Err(Error::unsupported(
474 format!("ALAC encoding {channels} channels"),490 format!("ALAC encoding {channels} channels"),
crates/ec-alac/tests/encode.rsmodified+64 -0
@@ -274,3 +274,67 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() {
274 let _ = std::fs::remove_dir_all(&dir);274 let _ = std::fs::remove_dir_all(&dir);
275 }275 }
276 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+}