diff --git a/crates/ec-alac/src/decode.rs b/crates/ec-alac/src/decode.rs index f17918b1..f9175f4d 100644 --- a/crates/ec-alac/src/decode.rs +++ b/crates/ec-alac/src/decode.rs @@ -108,11 +108,16 @@ fn golomb(bits: &mut Bits<'_>, m: u32, k: u32, maxbits: u32) -> u32 { let stream = bits.peek32(); let pre = (!stream).leading_zeros(); if pre >= MAX_PREFIX { - bits.pos += (MAX_PREFIX + maxbits) as usize; - return match maxbits { + // The raw value can be up to 32 bits wide (a 24-bit stereo element + // codes 25), so it does not fit in the same 32-bit peek as the + // prefix: step past the prefix and peek again. + bits.pos += MAX_PREFIX as usize; + let raw = match maxbits { 0 => 0, - n => (stream << MAX_PREFIX) >> (32 - n), + n => bits.peek32() >> (32 - n), }; + bits.pos += maxbits as usize; + return raw; } bits.pos += pre as usize + 1; let mut result = pre * m; diff --git a/crates/ec-alac/src/encode.rs b/crates/ec-alac/src/encode.rs index f001d63b..5ff06bc3 100644 --- a/crates/ec-alac/src/encode.rs +++ b/crates/ec-alac/src/encode.rs @@ -270,31 +270,13 @@ struct Candidate { bits: u64, } -/// Whether [`best_candidate`] may pick mode 1 (decode.rs:510-529's -/// double-difference pass): off by default. decode.rs, written from the -/// published format description, parses and reconstructs it correctly (see -/// `mode_one_is_chosen_on_smooth_signal` below, which forces this on to -/// prove it), but real-world ALAC decoders reject any prediction type other -/// than 0 outright — confirmed against this crate's own oracle test, which -/// failed with an `unknown prediction type` decode error the one time this -/// was left enabled. Kept as a knob rather than deleted so the capability -/// stays reachable for a future stream that is known never to cross a -/// third-party decoder, and so its cost math stays exercised by a real test. -fn mode1_allowed() -> bool { - std::env::var_os("EC_ALAC_MODE1").is_some() -} - /// Cheapest of [`ORDER_CANDIDATES`] (plus the trivial order-0 "residuals are -/// the samples" case) for one channel of true samples, each order tried as -/// mode 0 (the filter alone) and, when [`mode1_allowed`], also as mode 1: a -/// first-order pre-difference ahead of the same filter. Mode 1's residuals -/// are `analyze`'s inverse of that pass: run the filter forward as usual, -/// then difference *that* result with the order-31 sentinel — decode.rs -/// undoes it in the same order, integrating first and filtering second. +/// the samples" case) for one channel of true samples, each as mode 0 — the +/// only prediction type real-world decoders accept (decode.rs also undoes +/// mode 1's extra difference pass, but nothing here emits it). fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) -> Candidate { let mut orders: Vec = vec![0]; orders.extend(ORDER_CANDIDATES.iter().copied().filter(|&o| o < y.len())); - let mode1 = mode1_allowed(); let mut best: Option = None; for order in orders { let res = analyze(y, order, 9); @@ -302,21 +284,6 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) rice_encode(&mut cost, cfg, pb_factor, &res, chan_bits); let bits = 16 + (order as u64) * 16 + cost.0; - if mode1 { - let res1 = analyze(&res, ORDER_DIFF, 0); - let mut cost1 = CostSink::default(); - rice_encode(&mut cost1, cfg, pb_factor, &res1, chan_bits); - let bits1 = 16 + (order as u64) * 16 + cost1.0; - if best.as_ref().is_none_or(|b| bits1 < b.bits) { - best = Some(Candidate { - mode: 1, - order: order as u32, - res: res1, - bits: bits1, - }); - } - } - if best.as_ref().is_none_or(|b| bits < b.bits) { best = Some(Candidate { mode: 0, @@ -359,7 +326,7 @@ fn write_plan(sink: &mut S, plan: &ChannelPlan) { /// One SCE (mono) or CPE (stereo) element, choosing per-element between raw /// (escape) and compressed, and for a pair, between direct L/R and a /// mid/side mix, whichever is smaller. -fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec], samples: usize) { +fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec], samples: usize, allow_shift: bool) { w.put(0, 16); // element instance tag + 12 reserved bits. let pair = planes.len() == 2; let channels = planes.len() as u32; @@ -373,12 +340,7 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec], samp // compressing the sample whole. Only 0 and 1 are ever tried: 3 is the // format's escape sentinel (decode.rs:439), and a stream never carries // more than one low byte's worth of headroom worth shifting off. - // EC_ALAC_NO_SHIFT forces bytes_shifted 0 even at 24 bits — a test-only - // knob so a test can measure both paths against the same source - // (`twenty_four_bit_uses_byte_shift_when_cheaper`), not a real-world - // interop concern like `mode1_allowed`'s. - let no_shift = std::env::var_os("EC_ALAC_NO_SHIFT").is_some(); - let shift_candidates: &[u32] = if bit_depth == 24 && !no_shift { &[0, 1] } else { &[0] }; + let shift_candidates: &[u32] = if bit_depth == 24 && allow_shift { &[0, 1] } else { &[0] }; let compressed = (samples >= 2).then(|| { shift_candidates @@ -499,6 +461,7 @@ pub struct AlacEncoder { pending: Vec, packets: std::collections::VecDeque>, eof: bool, + allow_shift: bool, } impl AlacEncoder { @@ -534,9 +497,18 @@ impl AlacEncoder { pending: Vec::new(), packets: std::collections::VecDeque::new(), eof: false, + allow_shift: true, }) } + /// Test-only: force bytes_shifted 0 even at 24 bits, so a test can + /// measure both paths against the same source. Both outputs decode the + /// same; this only trades size. + #[doc(hidden)] + pub fn set_byte_shift(&mut self, allow: bool) { + self.allow_shift = allow; + } + /// What this encoder states about the stream it writes. pub fn cookie(&self) -> &MagicCookie { &self.cookie @@ -557,7 +529,7 @@ impl AlacEncoder { } let mut w = BitWriter::default(); w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3); - write_element(&self.cookie, &mut w, &planes, n); + write_element(&self.cookie, &mut w, &planes, n, self.allow_shift); w.put(ID_END, 3); w.finish() } diff --git a/crates/ec-alac/tests/encode.rs b/crates/ec-alac/tests/encode.rs index 23baffd3..2a3afc2c 100644 --- a/crates/ec-alac/tests/encode.rs +++ b/crates/ec-alac/tests/encode.rs @@ -50,18 +50,47 @@ fn round_trip(sample_rate: u32, channels: u8, bit_depth: u8, frame_length: u32, assert_eq!(decoded, samples, "{channels}ch {bit_depth}bit round trip"); } -/// One bit field starting at bit `start` of `data`, MSB-first — enough to -/// reach into a compressed mono frame's plan header (which starts at bit 39: -/// 3 element-tag + 16 instance/reserved + 1 partial + 2 bytes_shifted + 1 -/// escape + 8 mix_bits + 8 mix_res) without pulling in the decoder's own -/// private bit reader. -fn bits_at(data: &[u8], start: usize, n: usize) -> u32 { - let mut v = 0u32; - for i in 0..n { - let pos = start + i; - v = (v << 1) | u32::from((data[pos / 8] >> (7 - pos % 8)) & 1); +/// Encode `samples` frame by frame through a real mp4 mux into a fresh temp +/// file, returned with its directory (delete it when done). +fn mux_to_m4a(enc: &AlacEncoder, channels: usize, sample_rate: u32, samples: &[i32]) -> (PathBuf, PathBuf) { + let mut mp4 = ec_mp4::Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); + let time_base = TimeBase::new(1, i64::from(sample_rate)); + let stream = mp4 + .add_stream(StreamInfo::new(0, time_base, enc.codec_parameters().clone())) + .expect("add_stream"); + let mut pts = 0i64; + for chunk in samples.chunks(4096 * channels) { + let n = chunk.len() / channels; + let data = enc.encode_frame(chunk); + let mut packet = Packet::new(stream, time_base, data).with_pts(pts); + packet.duration = Some(n as i64); + mp4.write_packet(&packet).expect("write_packet"); + pts += n as i64; } - v + mp4.finish().expect("finish"); + let bytes = mp4.into_inner().into_inner(); + // Tests run in parallel in one process: a per-call serial keeps them out + // of each other's directories. + static SERIAL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("ec-alac-mux-test-{}-{serial}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let out_path = dir.join("out.m4a"); + std::fs::write(&out_path, &bytes).expect("write m4a"); + (dir, out_path) +} + +/// ffmpeg's decode of `path` in raw format `fmt`, or None when no oracle is +/// installed. +fn ffmpeg_decode(path: &Path, fmt: &str) -> Option> { + let decode = Command::new("ffmpeg") + .args(["-nostdin", "-v", "error", "-i"]) + .arg(path) + .args(["-f", fmt, "-"]) + .output() + .ok()?; + assert!(decode.status.success(), "{}", String::from_utf8_lossy(&decode.stderr)); + Some(decode.stdout) } #[test] @@ -92,11 +121,9 @@ fn twenty_four_bit_uses_byte_shift_when_cheaper() { let with_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).len()).sum(); - // SAFETY: single-threaded test-only env toggle, restored before return. - unsafe { std::env::set_var("EC_ALAC_NO_SHIFT", "1") }; - let without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); + let mut without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder"); + without_shift.set_byte_shift(false); let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).len()).sum(); - unsafe { std::env::remove_var("EC_ALAC_NO_SHIFT") }; eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes"); assert!( @@ -106,25 +133,40 @@ fn twenty_four_bit_uses_byte_shift_when_cheaper() { } #[test] -fn mode_one_is_chosen_on_smooth_signal() { - // A pure ramp: its first difference is a near-constant, which mode 1's - // extra difference squeezes to near zero — cheaper than any order-0 - // filter's residual stream, which stays at the ramp's own value. - let n = 4096usize; - let samples: Vec = (0..n as i32).map(|i| 100 + i * 3).collect(); - - unsafe { std::env::set_var("EC_ALAC_MODE1", "1") }; - let enc = AlacEncoder::new(48_000, 1, 16, 4096).expect("encoder"); - let packet = enc.encode_frame(&samples); - unsafe { std::env::remove_var("EC_ALAC_MODE1") }; - - let mode = bits_at(&packet, 39, 4); - assert_eq!(mode, 1, "mode 1 should win the cost comparison on a pure ramp"); +fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { + // A smooth tone's first residuals are far bigger than the coder's + // starting mean allows, so they go out as 24-bit raw escapes — the one + // Golomb shape random data (whole-frame escape) and 16-bit-derived 24-bit + // audio (bytes_shifted 1, 16 coded bits) never produce. + let mut rng = Rng(0x0bad_cafe); + let n = 4096 * 2 + 777; + for channels in [1u8, 2] { + let tone: Vec = (0..n * channels as usize) + .map(|i| (2000.0 * (i as f64 / 64.0).sin()) as i32) + .collect(); + let wide: Vec = tone.iter().map(|&s| (s << 8) | (rng.next() & 0xff) as i32).collect(); + for samples in [&tone, &wide] { + for allow_shift in [true, false] { + 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, "{channels}ch 24-bit tone, shift={allow_shift}"); - let mut dec = AlacDecoder::new(*enc.cookie()); - let shift = enc.cookie().container_shift(); - let decoded: Vec = dec.decode(&packet).expect("decode").iter().map(|&s| s >> shift).collect(); - assert_eq!(decoded, samples, "mode 1 round trip"); + // And the reference decoder agrees with what we wrote. + 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 { continue }; + let want: Vec = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); + assert!(got == want, "{channels}ch 24-bit tone, shift={allow_shift}: reference decode differs"); + } + } + } } #[test] @@ -176,29 +218,7 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) .expect("encoder"); - let mut mp4 = ec_mp4::Mp4Muxer::new(Cursor::new(Vec::new())).expect("muxer"); - let time_base = TimeBase::new(1, i64::from(spec.sample_rate)); - let stream = mp4 - .add_stream(StreamInfo::new(0, time_base, enc.codec_parameters().clone())) - .expect("add_stream"); - - let per_frame = 4096 * spec.channels as usize; - let mut pts = 0i64; - for chunk in samples.chunks(per_frame) { - let n = chunk.len() / spec.channels as usize; - let data = enc.encode_frame(chunk); - let mut packet = Packet::new(stream, time_base, data).with_pts(pts); - packet.duration = Some(n as i64); - mp4.write_packet(&packet).expect("write_packet"); - pts += n as i64; - } - mp4.finish().expect("finish"); - let bytes = mp4.into_inner().into_inner(); - - let dir = std::env::temp_dir().join(format!("ec-alac-mux-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let out_path = dir.join("out.m4a"); - std::fs::write(&out_path, &bytes).expect("write m4a"); + let (dir, out_path) = mux_to_m4a(&enc, spec.channels as usize, spec.sample_rate, &samples); // Sanity without an oracle: our own demuxer/decoder reads it back // bit-exact against the source PCM. @@ -243,16 +263,9 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}"); assert!(info.contains(&format!("channels={}", spec.channels)), "{info}"); - let decode = Command::new("ffmpeg") - .args(["-nostdin", "-v", "error", "-i"]) - .arg(&out_path) - .args(["-f", "s16le", "-"]) - .output() - .expect("ffmpeg"); - assert!(decode.status.success(), "{}", String::from_utf8_lossy(&decode.stderr)); + let Some(stdout) = ffmpeg_decode(&out_path, "s16le") else { return }; let want: Vec = samples.iter().map(|&s| s as i16).collect(); - let got: Vec = decode - .stdout + let got: Vec = stdout .chunks_exact(2) .map(|c| i16::from_le_bytes([c[0], c[1]])) .collect(); diff --git a/crates/ec-alac/tests/oracle.rs b/crates/ec-alac/tests/oracle.rs index 88482493..50478455 100644 --- a/crates/ec-alac/tests/oracle.rs +++ b/crates/ec-alac/tests/oracle.rs @@ -129,3 +129,46 @@ fn truncated_frames_are_refused_without_panicking() { .is_empty() ); } + +/// A 24-bit tone with a dithered low byte, encoded by the reference encoder: +/// its first residuals escape to raw 24-bit values — a Golomb shape none of +/// the checked-in fixtures (16-bit, or 24-bit with a shifted low byte) carry. +#[test] +fn reference_encoded_24_bit_tone_decodes_bit_exactly() { + if Command::new("ffmpeg").arg("-version").output().is_err() { + eprintln!("ffmpeg absent — skipping"); + return; + } + let dir = std::env::temp_dir().join(format!("ec-alac-tone-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("tmp"); + let raw = dir.join("tone.raw"); + let m4a = dir.join("tone.m4a"); + let mut seed = 0x0bad_cafeu32; + let pcm: Vec = (0..48_000 * 2) + .flat_map(|i| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let s = ((2000.0 * (i as f64 / 64.0).sin()) as i32) << 8 | (seed & 0xff) as i32; + s.to_le_bytes() + }) + .collect(); + std::fs::write(&raw, &pcm).expect("raw"); + let enc = Command::new("ffmpeg") + .args(["-nostdin", "-y", "-v", "error", "-f", "s32le", "-ar", "48000", "-ac", "2", "-i"]) + .arg(&raw) + .args(["-c:a", "alac", "-sample_fmt", "s32p"]) + .arg(&m4a) + .output() + .expect("ffmpeg"); + assert!(enc.status.success(), "{}", String::from_utf8_lossy(&enc.stderr)); + + let (cookie, got) = decode(&m4a); + assert_eq!(cookie.bit_depth, 24); + let shift = cookie.container_shift(); + let got: Vec = got.iter().flat_map(|&s| (s >> shift << 8).to_le_bytes()).collect(); + let want = ffmpeg(&m4a, "s32le"); + std::fs::remove_dir_all(&dir).ok(); + assert_eq!(got.len(), want.len()); + assert!(got == want, "reference-encoded 24-bit tone: our decode differs from the reference decode"); +}