forge
Explore
Log in

Don't you dare go Hollow

Implement bytes_shifted split and mode-1 double-difference

Browse files at this commit

d92d8b152aae3b718b74651cb0c017a049b26a7aAhmet Kaan GümüşParent: 98a0f6f
  • feat
    • implement bytes_shifted split and mode-1 double-difference
Show full message
feat(alac-enc): implement bytes_shifted split and mode-1 double-difference

Two documented corner-cuts closed: 24-bit bytes_shifted (0/1, cost-chosen
per element via the existing CostSink) and the mode-1 double-difference
predictor pass (per-channel cost-chosen against mode 0).

Mode 1 is real but gated off by default (EC_ALAC_MODE1 env knob): writing
it broke this crate's own ffmpeg-oracle test with "unknown prediction
type: 1" — real-world ALAC decoders reject any prediction type but 0, even
though this crate's own decode.rs (independently written from the format
description) parses and reconstructs it correctly. Kept selectable for a
dedicated test and any stream known never to cross a third-party decoder.

Also discovered (not fixed, out of scope): a pre-existing bug corrupts
correlated 24-bit content's round trip independent of this change
(reproduces with bytes_shifted forced off too) — logged to the ledger.
crates/ec-alac/src/encode.rsmodified+96 -14
@@ -259,28 +259,67 @@ fn analyze(y: &[i32], order: usize, den_shift: u32) -> Vec<i32> {
259 res259 res
260 }260 }
261 261
262-/// One channel's chosen filter: the order field to write, the residuals it262+/// One channel's chosen filter: the mode and order fields to write, the
263-/// produces, and its total cost in bits (16-bit plan header + coefficients263+/// residuals it produces, and its total cost in bits (16-bit plan header +
264-/// + the Rice-coded residuals), for comparing against every other choice.264+/// coefficients + the Rice-coded residuals), for comparing against every
265+/// other choice.
265 struct Candidate {266 struct Candidate {
267+ mode: u32,
266 order: u32,268 order: u32,
267 res: Vec<i32>,269 res: Vec<i32>,
268 bits: u64,270 bits: u64,
269 }271 }
270 272
273+/// Whether [`best_candidate`] may pick mode 1 (decode.rs:510-529's
274+/// double-difference pass): off by default. decode.rs, written from the
275+/// published format description, parses and reconstructs it correctly (see
276+/// `mode_one_is_chosen_on_smooth_signal` below, which forces this on to
277+/// prove it), but real-world ALAC decoders reject any prediction type other
278+/// than 0 outright — confirmed against this crate's own oracle test, which
279+/// failed with an `unknown prediction type` decode error the one time this
280+/// was left enabled. Kept as a knob rather than deleted so the capability
281+/// stays reachable for a future stream that is known never to cross a
282+/// third-party decoder, and so its cost math stays exercised by a real test.
283+fn mode1_allowed() -> bool {
284+ std::env::var_os("EC_ALAC_MODE1").is_some()
285+}
286+
271 /// Cheapest of [`ORDER_CANDIDATES`] (plus the trivial order-0 "residuals are287 /// Cheapest of [`ORDER_CANDIDATES`] (plus the trivial order-0 "residuals are
272-/// the samples" case) for one channel of true samples.288+/// the samples" case) for one channel of true samples, each order tried as
289+/// mode 0 (the filter alone) and, when [`mode1_allowed`], also as mode 1: a
290+/// first-order pre-difference ahead of the same filter. Mode 1's residuals
291+/// are `analyze`'s inverse of that pass: run the filter forward as usual,
292+/// then difference *that* result with the order-31 sentinel — decode.rs
293+/// undoes it in the same order, integrating first and filtering second.
273 fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) -> Candidate {294 fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) -> Candidate {
274 let mut orders: Vec<usize> = vec![0];295 let mut orders: Vec<usize> = vec![0];
275 orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len()));296 orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len()));
297+ let mode1 = mode1_allowed();
276 let mut best: Option<Candidate> = None;298 let mut best: Option<Candidate> = None;
277 for order in orders {299 for order in orders {
278 let res = analyze(y, order, 9);300 let res = analyze(y, order, 9);
279 let mut cost = CostSink::default();301 let mut cost = CostSink::default();
280 rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits);302 rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits);
281 let bits = 16 + (order as u64) * 16 + cost.0;303 let bits = 16 + (order as u64) * 16 + cost.0;
304+
305+ if mode1 {
306+ let res1 = analyze(&res, ORDER_DIFF, 0);
307+ let mut cost1 = CostSink::default();
308+ rice_encode(&mut cost1, cfg, pb_factor, &res1, chan_bits);
309+ let bits1 = 16 + (order as u64) * 16 + cost1.0;
310+ if best.as_ref().is_none_or(|b| bits1 < b.bits) {
311+ best = Some(Candidate {
312+ mode: 1,
313+ order: order as u32,
314+ res: res1,
315+ bits: bits1,
316+ });
317+ }
318+ }
319+
282 if best.as_ref().is_none_or(|b| bits < b.bits) {320 if best.as_ref().is_none_or(|b| bits < b.bits) {
283 best = Some(Candidate {321 best = Some(Candidate {
322+ mode: 0,
284 order: order as u32,323 order: order as u32,
285 res,324 res,
286 bits,325 bits,
@@ -288,6 +327,7 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32)
288 }327 }
289 }328 }
290 best.unwrap_or(Candidate {329 best.unwrap_or(Candidate {
330+ mode: 0,
291 order: 0,331 order: 0,
292 res: y.to_vec(),332 res: y.to_vec(),
293 bits: u64::MAX,333 bits: u64::MAX,
@@ -297,6 +337,7 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32)
297 /// A channel's coded parameters and residuals, ready to write: the plan337 /// A channel's coded parameters and residuals, ready to write: the plan
298 /// header fields plus [`Candidate::res`].338 /// header fields plus [`Candidate::res`].
299 struct ChannelPlan {339 struct ChannelPlan {
340+ mode: u32,
300 order: u32,341 order: u32,
301 pb_factor: u32,342 pb_factor: u32,
302 res: Vec<i32>,343 res: Vec<i32>,
@@ -306,7 +347,7 @@ const DEN_SHIFT: u32 = 9;
306 const PB_FACTOR: u32 = 4;347 const PB_FACTOR: u32 = 4;
307 348
308 fn write_plan<S: BitSink>(sink: &mut S, plan: &ChannelPlan) {349 fn write_plan<S: BitSink>(sink: &mut S, plan: &ChannelPlan) {
309- sink.put(0, 4); // mode: always the single (non-difference-doubled) pass.350+ sink.put(plan.mode, 4);
310 sink.put(DEN_SHIFT, 4);351 sink.put(DEN_SHIFT, 4);
311 sink.put(PB_FACTOR, 3);352 sink.put(PB_FACTOR, 3);
312 sink.put(plan.order, 5);353 sink.put(plan.order, 5);
@@ -326,10 +367,33 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samp
326 let partial = samples != cfg.frame_length as usize;367 let partial = samples != cfg.frame_length as usize;
327 let raw_bits = u64::from(channels) * u64::from(bit_depth) * samples as u64;368 let raw_bits = u64::from(channels) * u64::from(bit_depth) * samples as u64;
328 369
370+ // A 24-bit stream may additionally split each sample into a compressed
371+ // high part and an uncompressed low byte ridden ahead of the residuals
372+ // (decode.rs:485-490, :533-538) — bytes_shifted 1 — when that beats
373+ // compressing the sample whole. Only 0 and 1 are ever tried: 3 is the
374+ // format's escape sentinel (decode.rs:439), and a stream never carries
375+ // more than one low byte's worth of headroom worth shifting off.
376+ // EC_ALAC_NO_SHIFT forces bytes_shifted 0 even at 24 bits — a test-only
377+ // knob so a test can measure both paths against the same source
378+ // (`twenty_four_bit_uses_byte_shift_when_cheaper`), not a real-world
379+ // interop concern like `mode1_allowed`'s.
380+ let no_shift = std::env::var_os("EC_ALAC_NO_SHIFT").is_some();
381+ let shift_candidates: &[u32] = if bit_depth == 24 && !no_shift { &[0, 1] } else { &[0] };
382+
329 let compressed = (samples >= 2).then(|| {383 let compressed = (samples >= 2).then(|| {
330- let chan_bits = bit_depth + channels - 1;384+ shift_candidates
331- if pair {385+ .iter()
332- let (l, r) = (&planes[0], &planes[1]);386+ .map(|&bytes_shifted| {
387+ let shift_bits = bytes_shifted * 8;
388+ let chan_bits = bit_depth - shift_bits + channels - 1;
389+ let low_bits = u64::from(shift_bits) * u64::from(channels) * samples as u64;
390+ let shifted: Vec<Vec<i32>> = planes
391+ .iter()
392+ .map(|p| p.iter().map(|&s| s >> shift_bits).collect())
393+ .collect();
394+
395+ let (mix_bits, mix_res, plans, bits) = if pair {
396+ let (l, r) = (&shifted[0], &shifted[1]);
333 let lc = best_candidate(cfg, l, chan_bits, PB_FACTOR);397 let lc = best_candidate(cfg, l, chan_bits, PB_FACTOR);
334 let rc = best_candidate(cfg, r, chan_bits, PB_FACTOR);398 let rc = best_candidate(cfg, r, chan_bits, PB_FACTOR);
335 let lr_bits = lc.bits + rc.bits;399 let lr_bits = lc.bits + rc.bits;
@@ -349,18 +413,23 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samp
349 false => (2u32, 0i32, vec![plan_of(lc), plan_of(rc)], lr_bits),413 false => (2u32, 0i32, vec![plan_of(lc), plan_of(rc)], lr_bits),
350 }414 }
351 } else {415 } else {
352- let c0 = best_candidate(cfg, &planes[0], chan_bits, PB_FACTOR);416+ let c0 = best_candidate(cfg, &shifted[0], chan_bits, PB_FACTOR);
353 let bits = c0.bits;417 let bits = c0.bits;
354 (0u32, 0i32, vec![plan_of(c0)], bits)418 (0u32, 0i32, vec![plan_of(c0)], bits)
355- }419+ };
420+ (bytes_shifted, mix_bits, mix_res, plans, bits + low_bits)
421+ })
422+ .min_by_key(|&(_, _, _, _, bits)| bits)
423+ .unwrap()
356 });424 });
357 425
358 let use_compressed = compressed426 let use_compressed = compressed
359 .as_ref()427 .as_ref()
360- .is_some_and(|(_, _, _, bits)| 16 + bits < raw_bits.max(1));428+ .is_some_and(|(_, _, _, _, bits)| 16 + bits < raw_bits.max(1));
429+ let bytes_shifted = compressed.as_ref().map_or(0, |&(bs, ..)| bs);
361 430
362 w.put(partial as u32, 1);431 w.put(partial as u32, 1);
363- w.put(0, 2); // bytes_shifted: always 0 (corner-cut, see module docs).432+ w.put(if use_compressed { bytes_shifted } else { 0 }, 2);
364 w.put(!use_compressed as u32, 1);433 w.put(!use_compressed as u32, 1);
365 if partial {434 if partial {
366 w.put((samples as u32) >> 16, 16);435 w.put((samples as u32) >> 16, 16);
@@ -377,13 +446,25 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samp
377 }446 }
378 }447 }
379 true => {448 true => {
380- let (mix_bits, mix_res, plans, _) = compressed.unwrap();449+ let (bytes_shifted, mix_bits, mix_res, plans, _) = compressed.unwrap();
450+ let shift_bits = bytes_shifted * 8;
381 w.put(mix_bits, 8);451 w.put(mix_bits, 8);
382 w.put((mix_res as i8) as u8 as u32, 8);452 w.put((mix_res as i8) as u8 as u32, 8);
383 for plan in &plans {453 for plan in &plans {
384 write_plan(w, plan);454 write_plan(w, plan);
385 }455 }
386- let chan_bits = bit_depth + channels - 1;456+ // The low bytes ride ahead of the residuals, one `shift_bits`
457+ // field per sample per channel, in the same i-outer/channel-inner
458+ // order the escape path above uses — decode.rs reads them back
459+ // in exactly that order (decode.rs:533-538).
460+ if shift_bits > 0 {
461+ for i in 0..samples {
462+ for plane in planes {
463+ w.put(plane[i] as u32 & mask(shift_bits), shift_bits);
464+ }
465+ }
466+ }
467+ let chan_bits = bit_depth - shift_bits + channels - 1;
387 for plan in &plans {468 for plan in &plans {
388 rice_encode(w, cfg, plan.pb_factor, &plan.res, chan_bits);469 rice_encode(w, cfg, plan.pb_factor, &plan.res, chan_bits);
389 }470 }
@@ -393,6 +474,7 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samp
393 474
394 fn plan_of(c: Candidate) -> ChannelPlan {475 fn plan_of(c: Candidate) -> ChannelPlan {
395 ChannelPlan {476 ChannelPlan {
477+ mode: c.mode,
396 order: c.order,478 order: c.order,
397 pb_factor: PB_FACTOR,479 pb_factor: PB_FACTOR,
398 res: c.res,480 res: c.res,
crates/ec-alac/tests/encode.rsmodified+78 -0
@@ -50,6 +50,83 @@ fn round_trip(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32,
50 assert_eq!(decoded, samples, "{channels}ch {bit_depth}bit round trip");50 assert_eq!(decoded, samples, "{channels}ch {bit_depth}bit round trip");
51 }51 }
52 52
53+/// One bit field starting at bit `start` of `data`, MSB-first — enough to
54+/// reach into a compressed mono frame's plan header (which starts at bit 39:
55+/// 3 element-tag + 16 instance/reserved + 1 partial + 2 bytes_shifted + 1
56+/// escape + 8 mix_bits + 8 mix_res) without pulling in the decoder's own
57+/// private bit reader.
58+fn bits_at(data: &[u8], start: usize, n: usize) -> u32 {
59+ let mut v = 0u32;
60+ for i in 0..n {
61+ let pos = start + i;
62+ v = (v << 1) | u32::from((data[pos / 8] >> (7 - pos % 8)) & 1);
63+ }
64+ v
65+}
66+
67+#[test]
68+fn twenty_four_bit_uses_byte_shift_when_cheaper() {
69+ // Real 16-bit audio widened to 24 bits with random dither in the low
70+ // byte: exactly the shape a 24-bit master of 16-bit source material has,
71+ // and exactly what bytes_shifted exists for — the high bits alone
72+ // predict well, but folded together with the dither's noise they do not.
73+ let path = fixtures().join("wav16-stereo-48000.wav");
74+ if !path.exists() {
75+ eprintln!("fixtures/audio absent (gitignored) — skipping");
76+ return;
77+ }
78+ let mut reader = ec_riff::WavReader::open(&path).expect("open wav");
79+ let spec = reader.spec();
80+ let mut rng = Rng(0xdead_beef);
81+ let samples: Vec<i32> = reader
82+ .read_all_i32()
83+ .expect("pcm")
84+ .into_iter()
85+ .map(|s| (s << 8) | (rng.next() & 0xff) as i32)
86+ .collect();
87+ let channels = spec.channels as u8;
88+
89+ round_trip(spec.sample_rate, channels, 24, 4096, &samples);
90+
91+ let per_frame = 4096 * channels as usize;
92+ let with_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder");
93+ let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).len()).sum();
94+
95+ // SAFETY: single-threaded test-only env toggle, restored before return.
96+ unsafe { std::env::set_var("EC_ALAC_NO_SHIFT", "1") };
97+ let without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder");
98+ let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).len()).sum();
99+ unsafe { std::env::remove_var("EC_ALAC_NO_SHIFT") };
100+
101+ eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes");
102+ assert!(
103+ with_bytes < without_bytes,
104+ "bytes_shifted split ({with_bytes}) should beat forcing bytes_shifted=0 ({without_bytes})"
105+ );
106+}
107+
108+#[test]
109+fn mode_one_is_chosen_on_smooth_signal() {
110+ // A pure ramp: its first difference is a near-constant, which mode 1's
111+ // extra difference squeezes to near zero — cheaper than any order-0
112+ // filter's residual stream, which stays at the ramp's own value.
113+ let n = 4096usize;
114+ let samples: Vec<i32> = (0..n as i32).map(|i| 100 + i * 3).collect();
115+
116+ unsafe { std::env::set_var("EC_ALAC_MODE1", "1") };
117+ let enc = AlacEncoder::new(48_000, 1, 16, 4096).expect("encoder");
118+ let packet = enc.encode_frame(&samples);
119+ unsafe { std::env::remove_var("EC_ALAC_MODE1") };
120+
121+ let mode = bits_at(&packet, 39, 4);
122+ assert_eq!(mode, 1, "mode 1 should win the cost comparison on a pure ramp");
123+
124+ let mut dec = AlacDecoder::new(*enc.cookie());
125+ let shift = enc.cookie().container_shift();
126+ let decoded: Vec<i32> = dec.decode(&packet).expect("decode").iter().map(|&s| s >> shift).collect();
127+ assert_eq!(decoded, samples, "mode 1 round trip");
128+}
129+
53 #[test]130 #[test]
54 fn escape_frames_round_trip_random_data() {131 fn escape_frames_round_trip_random_data() {
55 let mut rng = Rng(0x1234_5678);132 let mut rng = Rng(0x1234_5678);
@@ -183,3 +260,4 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() {
183 260
184 let _ = std::fs::remove_dir_all(&dir);261 let _ = std::fs::remove_dir_all(&dir);
185 }262 }
263+