forge
Explore
Log in

Don't you dare go Hollow

Read a Golomb escape's raw value past the 32-bit prefix peek

Browse files at this commit

b8b47ce0dd9eecb29b337e3632bd256e3a7b8363Ahmet Kaan GümüşParent: d92d8b1
  • fix
    • read a Golomb escape's raw value past the 32-bit prefix peek
    • drop the mode-1 emission knob
Show full message
fix(alac): read a Golomb escape's raw value past the 32-bit prefix peek; drop the mode-1 emission knob

The adaptive-Golomb escape (9 ones + a raw maxbits value) was decoded from
a single 32-bit peek, so any element whose coded width is 24 or more bits
(24-bit unshifted mono = 24, stereo = 25) lost the raw value's low bit(s)
and desynced the rest of the channel. A smooth 24-bit tone is the first
content whose opening residuals are large enough to escape at that width;
random data goes out as a whole-frame raw escape and 16-bit-derived
24-bit audio codes 16 bits after bytes_shifted, so neither ever hit it.

The encoder's mode-1 (double-difference) path and its EC_ALAC_MODE1 env
knob are gone: no real-world decoder accepts prediction type 1, so a knob
producing such files was a trap. The decoder keeps reading mode 1.
EC_ALAC_NO_SHIFT becomes a hidden AlacEncoder::set_byte_shift setter.
crates/ec-alac/src/decode.rsmodified+8 -3
@@ -108,11 +108,16 @@ fn golomb(bits: &mut Bits<'_>, m: u32, k: u32, maxbits: u32) -> u32 {
108108 let stream = bits.peek32();
109109 let pre = (!stream).leading_zeros();
110110 if pre >= MAX_PREFIX {
111- bits.pos += (MAX_PREFIX + maxbits) as usize;
112- return match maxbits {
111+ // The raw value can be up to 32 bits wide (a 24-bit stereo element
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 {
113116 0 => 0,
114- n => (stream << MAX_PREFIX) >> (32 - n),
117+ n => bits.peek32() >> (32 - n),
115118 };
119+ bits.pos += maxbits as usize;
120+ return raw;
116121 }
117122 bits.pos += pre as usize + 1;
118123 let mut result = pre * m;
crates/ec-alac/src/encode.rsmodified+16 -44
@@ -270,31 +270,13 @@ struct Candidate {
270270 bits: u64,
271271 }
272272
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-
287273 /// Cheapest of [`ORDER_CANDIDATES`] (plus the trivial order-0 "residuals are
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.
274+/// the samples" case) for one channel of true samples, each as mode 0 — the
275+/// only prediction type real-world decoders accept (decode.rs also undoes
276+/// mode 1's extra difference pass, but nothing here emits it).
294277 fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) -> Candidate {
295278 let mut orders: Vec<usize> = vec![0];
296279 orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len()));
297- let mode1 = mode1_allowed();
298280 let mut best: Option<Candidate> = None;
299281 for order in orders {
300282 let res = analyze(y, order, 9);
@@ -302,21 +284,6 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32)
302284 rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits);
303285 let bits = 16 + (order as u64) * 16 + cost.0;
304286
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-
320287 if best.as_ref().is_none_or(|b| bits < b.bits) {
321288 best = Some(Candidate {
322289 mode: 0,
@@ -359,7 +326,7 @@ fn write_plan<S: BitSink>(sink: &mut S, plan: &ChannelPlan) {
359326 /// One SCE (mono) or CPE (stereo) element, choosing per-element between raw
360327 /// (escape) and compressed, and for a pair, between direct L/R and a
361328 /// mid/side mix, whichever is smaller.
362-fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samples: usize) {
329+fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samples: usize, allow_shift: bool) {
363330 w.put(0, 16); // element instance tag + 12 reserved bits.
364331 let pair = planes.len() == 2;
365332 let channels = planes.len() as u32;
@@ -373,12 +340,7 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samp
373340 // compressing the sample whole. Only 0 and 1 are ever tried: 3 is the
374341 // format's escape sentinel (decode.rs:439), and a stream never carries
375342 // 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] };
343+ let shift_candidates: &[u32] = if bit_depth == 24 && allow_shift { &[0, 1] } else { &[0] };
382344
383345 let compressed = (samples >= 2).then(|| {
384346 shift_candidates
@@ -499,6 +461,7 @@ pub struct AlacEncoder {
499461 pending: Vec<i32>,
500462 packets: std::collections::VecDeque<Vec<u8>>,
501463 eof: bool,
464+ allow_shift: bool,
502465 }
503466
504467 impl AlacEncoder {
@@ -534,9 +497,18 @@ impl AlacEncoder {
534497 pending: Vec::new(),
535498 packets: std::collections::VecDeque::new(),
536499 eof: false,
500+ allow_shift: true,
537501 })
538502 }
539503
504+ /// Test-only: force bytes_shifted 0 even at 24 bits, so a test can
505+ /// measure both paths against the same source. Both outputs decode the
506+ /// same; this only trades size.
507+ #[doc(hidden)]
508+ pub fn set_byte_shift(&mut self, allow: bool) {
509+ self.allow_shift = allow;
510+ }
511+
540512 /// What this encoder states about the stream it writes.
541513 pub fn cookie(&self) -> &MagicCookie {
542514 &self.cookie
@@ -557,7 +529,7 @@ impl AlacEncoder {
557529 }
558530 let mut w = BitWriter::default();
559531 w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3);
560- write_element(&self.cookie, &mut w, &planes, n);
532+ write_element(&self.cookie, &mut w, &planes, n, self.allow_shift);
561533 w.put(ID_END, 3);
562534 w.finish()
563535 }
crates/ec-alac/tests/encode.rsmodified+78 -65
@@ -50,18 +50,47 @@ fn round_trip(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32,
5050 assert_eq!(decoded, samples, "{channels}ch {bit_depth}bit round trip");
5151 }
5252
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);
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;
6369 }
64- v
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)
6594 }
6695
6796 #[test]
@@ -92,11 +121,9 @@ fn twenty_four_bit_uses_byte_shift_when_cheaper() {
92121 let with_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder");
93122 let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).len()).sum();
94123
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");
124+ let mut without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder");
125+ without_shift.set_byte_shift(false);
98126 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") };
100127
101128 eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes");
102129 assert!(
@@ -106,25 +133,40 @@ fn twenty_four_bit_uses_byte_shift_when_cheaper() {
106133 }
107134
108135 #[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");
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}");
123159
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");
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+ }
128170 }
129171
130172 #[test]
@@ -176,29 +218,7 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() {
176218 let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096)
177219 .expect("encoder");
178220
179- let mut mp4 = ec_mp4::Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer");
180- let time_base = TimeBase::new(1, i64::from(spec.sample_rate));
181- let stream = mp4
182- .add_stream(StreamInfo::new(0, time_base, enc.codec_parameters().clone()))
183- .expect("add_stream");
184-
185- let per_frame = 4096 * spec.channels as usize;
186- let mut pts = 0i64;
187- for chunk in samples.chunks(per_frame) {
188- let n = chunk.len() / spec.channels as usize;
189- let data = enc.encode_frame(chunk);
190- let mut packet = Packet::new(stream, time_base, data).with_pts(pts);
191- packet.duration = Some(n as i64);
192- mp4.write_packet(&packet).expect("write_packet");
193- pts += n as i64;
194- }
195- mp4.finish().expect("finish");
196- let bytes = mp4.into_inner().into_inner();
197-
198- let dir = std::env::temp_dir().join(format!("ec-alac-mux-test-{}", std::process::id()));
199- std::fs::create_dir_all(&dir).unwrap();
200- let out_path = dir.join("out.m4a");
201- std::fs::write(&out_path, &bytes).expect("write m4a");
221+ let (dir, out_path) = mux_to_m4a(&enc, spec.channels as usize, spec.sample_rate, &samples);
202222
203223 // Sanity without an oracle: our own demuxer/decoder reads it back
204224 // bit-exact against the source PCM.
@@ -243,16 +263,9 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() {
243263 assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}");
244264 assert!(info.contains(&format!("channels={}", spec.channels)), "{info}");
245265
246- let decode = Command::new("ffmpeg")
247- .args(["-nostdin", "-v", "error", "-i"])
248- .arg(&out_path)
249- .args(["-f", "s16le", "-"])
250- .output()
251- .expect("ffmpeg");
252- assert!(decode.status.success(), "{}", String::from_utf8_lossy(&decode.stderr));
266+ let Some(stdout) = ffmpeg_decode(&out_path, "s16le") else { return };
253267 let want: Vec<i16> = samples.iter().map(|&s| s as i16).collect();
254- let got: Vec<i16> = decode
255- .stdout
268+ let got: Vec<i16> = stdout
256269 .chunks_exact(2)
257270 .map(|c| i16::from_le_bytes([c[0], c[1]]))
258271 .collect();
crates/ec-alac/tests/oracle.rsmodified+43 -0
@@ -129,3 +129,46 @@ fn truncated_frames_are_refused_without_panicking() {
129129 .is_empty()
130130 );
131131 }
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+}