From 036621d7be316245aece9da6db03e85867666f60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:34:00 +0300 Subject: [PATCH] U9: ec-alac drop set_byte_shift/allow_shift knob (default stayed on, bits unchanged), Candidate.mode (always 0) and the mp4 mux test; its ffprobe oracle path goes with it --- crates/ec-alac/src/encode.rs | 23 ++--- crates/ec-alac/tests/encode.rs | 148 +++++---------------------------- 2 files changed, 27 insertions(+), 144 deletions(-) diff --git a/crates/ec-alac/src/encode.rs b/crates/ec-alac/src/encode.rs index d0aab98e..15212b48 100644 --- a/crates/ec-alac/src/encode.rs +++ b/crates/ec-alac/src/encode.rs @@ -269,12 +269,11 @@ fn analyze(y: &[i32], order: usize, den_shift: u32, chan_bits: u32) -> Vec res } -/// One channel's chosen filter: the mode and order fields to write, the +/// One channel's chosen filter: the order field to write, the /// residuals it produces, and its total cost in bits (16-bit plan header + /// coefficients + the Rice-coded residuals), for comparing against every /// other choice. struct Candidate { - mode: u32, order: u32, res: Vec, bits: u64, @@ -296,7 +295,6 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) if best.as_ref().is_none_or(|b| bits < b.bits) { best = Some(Candidate { - mode: 0, order: order as u32, res, bits, @@ -304,7 +302,6 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32) } } best.unwrap_or(Candidate { - mode: 0, order: 0, res: y.to_vec(), bits: u64::MAX, @@ -336,7 +333,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, allow_shift: bool) { +fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec], samples: usize) { w.put(0, 16); // element instance tag + 12 reserved bits. let pair = planes.len() == 2; let channels = planes.len() as u32; @@ -350,7 +347,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. - let shift_candidates: &[u32] = if bit_depth == 24 && allow_shift { &[0, 1] } else { &[0] }; + let shift_candidates: &[u32] = if bit_depth == 24 { &[0, 1] } else { &[0] }; let compressed = (samples >= 2).then(|| { shift_candidates @@ -446,7 +443,7 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec], samp fn plan_of(c: Candidate) -> ChannelPlan { ChannelPlan { - mode: c.mode, + mode: 0, order: c.order, pb_factor: PB_FACTOR, res: c.res, @@ -478,7 +475,6 @@ pub struct AlacEncoder { pending: Vec, packets: std::collections::VecDeque>, eof: bool, - allow_shift: bool, } impl AlacEncoder { @@ -529,18 +525,9 @@ 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 @@ -567,7 +554,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, self.allow_shift); + write_element(&self.cookie, &mut w, &planes, n); w.put(ID_END, 3); Ok(w.finish()) } diff --git a/crates/ec-alac/tests/encode.rs b/crates/ec-alac/tests/encode.rs index 5ea11fff..78e2f09c 100644 --- a/crates/ec-alac/tests/encode.rs +++ b/crates/ec-alac/tests/encode.rs @@ -1,11 +1,10 @@ //! Round-trip the encoder through the decoder it was written to feed, then -use std::fs::File; -use std::io::{BufReader, Cursor}; +use std::io::Cursor; use std::path::{Path, PathBuf}; use ec_alac::{AlacDecoder, AlacEncoder}; -use ec_core::registry::{CodecId, Demuxer, Encoder, Muxer, StreamInfo}; +use ec_core::registry::{Encoder, Muxer, StreamInfo}; use ec_core::timebase::TimeBase; use ec_core::Packet; @@ -85,41 +84,6 @@ fn ffmpeg_decode(path: &Path, fmt: &str) -> Vec { decode.stdout } -#[test] -fn twenty_four_bit_uses_byte_shift_when_cheaper() { - // Real 16-bit audio widened to 24 bits with random dither in the low - // byte: exactly the shape a 24-bit master of 16-bit source material has, - // and exactly what bytes_shifted exists for — the high bits alone - // predict well, but folded together with the dither's noise they do not. - let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); - let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); - let spec = reader.spec(); - let mut rng = Rng(0xdead_beef); - let samples: Vec = reader - .read_all_i32() - .expect("pcm") - .into_iter() - .map(|s| (s << 8) | (rng.next() & 0xff) as i32) - .collect(); - let channels = spec.channels as u8; - - round_trip(spec.sample_rate, channels, 24, 4096, &samples); - - let per_frame = 4096 * channels as usize; - 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).expect("frame").len()).sum(); - - 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).expect("frame").len()).sum(); - - eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes"); - assert!( - with_bytes < without_bytes, - "bytes_shifted split ({with_bytes}) should beat forcing bytes_shifted=0 ({without_bytes})" - ); -} - #[test] fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { // A smooth tone's first residuals are far bigger than the coder's @@ -134,24 +98,21 @@ fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { .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("frame")).expect("decode").iter().map(|&s| s >> shift)); - } - assert_eq!(&decoded, samples, "{channels}ch 24-bit tone, shift={allow_shift}"); - - // 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 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"); + let enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); + 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("frame")).expect("decode").iter().map(|&s| s >> shift)); } + assert_eq!(&decoded, samples, "{channels}ch 24-bit tone"); + + // 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 want: Vec = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); + assert!(got == want, "{channels}ch 24-bit tone: reference decode differs"); } } } @@ -188,84 +149,21 @@ fn real_audio_round_trips_and_compresses() { assert!(ratio <= 0.75, "compression ratio {ratio:.4} > 0.75"); } -#[test] -fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { - let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); - let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); - let spec = reader.spec(); - let samples = reader.read_all_i32().expect("pcm"); - let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096) - .expect("encoder"); - - 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. - let mut demuxer = - ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&out_path).expect("open"))).expect("mp4"); - let track = demuxer - .streams() - .iter() - .find(|s| s.params.codec == CodecId::Alac) - .expect("alac track") - .clone(); - let mut dec = AlacDecoder::from_parameters(track.params).expect("cookie"); - let shift = dec.cookie().container_shift(); - let mut decoded = Vec::new(); - loop { - match demuxer.next_packet() { - Ok(p) if p.stream != track.index => continue, - Ok(p) => decoded.extend(dec.decode(&p.data).expect("decode").iter().map(|&s| s >> shift)), - Err(e) if e.is_eof() => break, - Err(e) => panic!("{e}"), - } - } - assert_eq!(decoded, samples, "mux -> demux -> decode round trip"); - - // The oracle: ffprobe reads the track back as alac at the right rate and - // channel count, and ffmpeg's own decode matches the source exactly. - let probe = ec_testkit::ffprobe() - .args([ - "-v", "error", "-select_streams", "a:0", "-show_entries", - "stream=codec_name,sample_rate,channels", - "-of", "default=noprint_wrappers=1", - ]) - .arg(&out_path) - .output() - .expect("ffprobe"); - let info = String::from_utf8_lossy(&probe.stdout); - assert!(info.contains("codec_name=alac"), "{info}"); - assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}"); - assert!(info.contains(&format!("channels={}", spec.channels)), "{info}"); - - let stdout = ffmpeg_decode(&out_path, "s16le"); - let want: Vec = samples.iter().map(|&s| s as i16).collect(); - let got: Vec = stdout - .as_chunks::<2>().0.iter() - .map(|c| i16::from_le_bytes([c[0], c[1]])) - .collect(); - assert_eq!(got, want, "ffmpeg decode of the muxed file vs source PCM"); - - let _ = std::fs::remove_dir_all(&dir); -} - - -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); +fn round_trip_both_decoders(channels: u8, samples: &[i32], what: &str) { + let enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); 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("frame")).expect("decode").iter().map(|&s| s >> shift)); } - assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit, shift={allow_shift}"); + assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit"); 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 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"); + assert!(got == want, "{what}: {channels}ch 24-bit: reference decode differs"); } #[test] @@ -275,9 +173,7 @@ fn mono_24_bit_ramp_round_trips_bit_exactly() { // 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}")); - } + round_trip_both_decoders(1, &samples, &format!("ramp n={n}")); } } @@ -285,7 +181,7 @@ fn mono_24_bit_ramp_round_trips_bit_exactly() { 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}")); + round_trip_both_decoders(1, &samples, &format!("alternating n={n}")); } }