forge
Explore
Log in

Don't you dare go Hollow

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

Browse files at this commit

036621d7be316245aece9da6db03e85867666f60Ahmet Kaan GümüşParent: 73ae260
crates/ec-alac/src/encode.rsmodified+5 -18
@@ -269,12 +269,11 @@ fn analyze(y: &[i32], order: usize, den_shift: u32, chan_bits: u32) -> Vec<i32>
269 res269 res
270 }270 }
271 271
272-/// One channel's chosen filter: the mode and order fields to write, the272+/// One channel's chosen filter: the order field to write, the
273 /// residuals it produces, and its total cost in bits (16-bit plan header +273 /// residuals it produces, and its total cost in bits (16-bit plan header +
274 /// coefficients + the Rice-coded residuals), for comparing against every274 /// coefficients + the Rice-coded residuals), for comparing against every
275 /// other choice.275 /// other choice.
276 struct Candidate {276 struct Candidate {
277- mode: u32,
278 order: u32,277 order: u32,
279 res: Vec<i32>,278 res: Vec<i32>,
280 bits: u64,279 bits: u64,
@@ -296,7 +295,6 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32)
296 295
297 if best.as_ref().is_none_or(|b| bits < b.bits) {296 if best.as_ref().is_none_or(|b| bits < b.bits) {
298 best = Some(Candidate {297 best = Some(Candidate {
299- mode: 0,
300 order: order as u32,298 order: order as u32,
301 res,299 res,
302 bits,300 bits,
@@ -304,7 +302,6 @@ fn best_candidate(cfg: &MagicCookie, y: &[i32], chan_bits: u32, pb_factor: u32)
304 }302 }
305 }303 }
306 best.unwrap_or(Candidate {304 best.unwrap_or(Candidate {
307- mode: 0,
308 order: 0,305 order: 0,
309 res: y.to_vec(),306 res: y.to_vec(),
310 bits: u64::MAX,307 bits: u64::MAX,
@@ -336,7 +333,7 @@ fn write_plan<S: BitSink>(sink: &mut S, plan: &ChannelPlan) {
336 /// One SCE (mono) or CPE (stereo) element, choosing per-element between raw333 /// One SCE (mono) or CPE (stereo) element, choosing per-element between raw
337 /// (escape) and compressed, and for a pair, between direct L/R and a334 /// (escape) and compressed, and for a pair, between direct L/R and a
338 /// mid/side mix, whichever is smaller.335 /// mid/side mix, whichever is smaller.
339-fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samples: usize, allow_shift: bool) {336+fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samples: usize) {
340 w.put(0, 16); // element instance tag + 12 reserved bits.337 w.put(0, 16); // element instance tag + 12 reserved bits.
341 let pair = planes.len() == 2;338 let pair = planes.len() == 2;
342 let channels = planes.len() as u32;339 let channels = planes.len() as u32;
@@ -350,7 +347,7 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samp
350 // compressing the sample whole. Only 0 and 1 are ever tried: 3 is the347 // compressing the sample whole. Only 0 and 1 are ever tried: 3 is the
351 // format's escape sentinel (decode.rs:439), and a stream never carries348 // format's escape sentinel (decode.rs:439), and a stream never carries
352 // more than one low byte's worth of headroom worth shifting off.349 // more than one low byte's worth of headroom worth shifting off.
353- let shift_candidates: &[u32] = if bit_depth == 24 && allow_shift { &[0, 1] } else { &[0] };350+ let shift_candidates: &[u32] = if bit_depth == 24 { &[0, 1] } else { &[0] };
354 351
355 let compressed = (samples >= 2).then(|| {352 let compressed = (samples >= 2).then(|| {
356 shift_candidates353 shift_candidates
@@ -446,7 +443,7 @@ fn write_element(cfg: &MagicCookie, w: &mut BitWriter, planes: &[Vec<i32>], samp
446 443
447 fn plan_of(c: Candidate) -> ChannelPlan {444 fn plan_of(c: Candidate) -> ChannelPlan {
448 ChannelPlan {445 ChannelPlan {
449- mode: c.mode,446+ mode: 0,
450 order: c.order,447 order: c.order,
451 pb_factor: PB_FACTOR,448 pb_factor: PB_FACTOR,
452 res: c.res,449 res: c.res,
@@ -478,7 +475,6 @@ pub struct AlacEncoder {
478 pending: Vec<i32>,475 pending: Vec<i32>,
479 packets: std::collections::VecDeque<Vec<u8>>,476 packets: std::collections::VecDeque<Vec<u8>>,
480 eof: bool,477 eof: bool,
481- allow_shift: bool,
482 }478 }
483 479
484 impl AlacEncoder {480 impl AlacEncoder {
@@ -529,18 +525,9 @@ impl AlacEncoder {
529 pending: Vec::new(),525 pending: Vec::new(),
530 packets: std::collections::VecDeque::new(),526 packets: std::collections::VecDeque::new(),
531 eof: false,527 eof: false,
532- allow_shift: true,
533 })528 })
534 }529 }
535 530
536- /// Test-only: force bytes_shifted 0 even at 24 bits, so a test can
537- /// measure both paths against the same source. Both outputs decode the
538- /// same; this only trades size.
539- #[doc(hidden)]
540- pub fn set_byte_shift(&mut self, allow: bool) {
541- self.allow_shift = allow;
542- }
543-
544 /// What this encoder states about the stream it writes.531 /// What this encoder states about the stream it writes.
545 pub fn cookie(&self) -> &MagicCookie {532 pub fn cookie(&self) -> &MagicCookie {
546 &self.cookie533 &self.cookie
@@ -567,7 +554,7 @@ impl AlacEncoder {
567 }554 }
568 let mut w = BitWriter::default();555 let mut w = BitWriter::default();
569 w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3);556 w.put(if channels == 2 { ID_CPE } else { ID_SCE }, 3);
570- write_element(&self.cookie, &mut w, &planes, n, self.allow_shift);557+ write_element(&self.cookie, &mut w, &planes, n);
571 w.put(ID_END, 3);558 w.put(ID_END, 3);
572 Ok(w.finish())559 Ok(w.finish())
573 }560 }
crates/ec-alac/tests/encode.rsmodified+22 -126
@@ -1,11 +1,10 @@
1 //! Round-trip the encoder through the decoder it was written to feed, then1 //! Round-trip the encoder through the decoder it was written to feed, then
2 2
3-use std::fs::File;3+use std::io::Cursor;
4-use std::io::{BufReader, Cursor};
5 use std::path::{Path, PathBuf};4 use std::path::{Path, PathBuf};
6 5
7 use ec_alac::{AlacDecoder, AlacEncoder};6 use ec_alac::{AlacDecoder, AlacEncoder};
8-use ec_core::registry::{CodecId, Demuxer, Encoder, Muxer, StreamInfo};7+use ec_core::registry::{Encoder, Muxer, StreamInfo};
9 use ec_core::timebase::TimeBase;8 use ec_core::timebase::TimeBase;
10 use ec_core::Packet;9 use ec_core::Packet;
11 10
@@ -85,41 +84,6 @@ fn ffmpeg_decode(path: &Path, fmt: &str) -> Vec<u8> {
85 decode.stdout84 decode.stdout
86 }85 }
87 86
88-#[test]
89-fn twenty_four_bit_uses_byte_shift_when_cheaper() {
90- // Real 16-bit audio widened to 24 bits with random dither in the low
91- // byte: exactly the shape a 24-bit master of 16-bit source material has,
92- // and exactly what bytes_shifted exists for — the high bits alone
93- // predict well, but folded together with the dither's noise they do not.
94- let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
95- let mut reader = ec_riff::WavReader::open(&path).expect("open wav");
96- let spec = reader.spec();
97- let mut rng = Rng(0xdead_beef);
98- let samples: Vec<i32> = reader
99- .read_all_i32()
100- .expect("pcm")
101- .into_iter()
102- .map(|s| (s << 8) | (rng.next() & 0xff) as i32)
103- .collect();
104- let channels = spec.channels as u8;
105-
106- round_trip(spec.sample_rate, channels, 24, 4096, &samples);
107-
108- let per_frame = 4096 * channels as usize;
109- let with_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder");
110- let with_bytes: usize = samples.chunks(per_frame).map(|c| with_shift.encode_frame(c).expect("frame").len()).sum();
111-
112- let mut without_shift = AlacEncoder::new(spec.sample_rate, channels, 24, 4096).expect("encoder");
113- without_shift.set_byte_shift(false);
114- let without_bytes: usize = samples.chunks(per_frame).map(|c| without_shift.encode_frame(c).expect("frame").len()).sum();
115-
116- eprintln!("24-bit shifted: {with_bytes} bytes, unshifted: {without_bytes} bytes");
117- assert!(
118- with_bytes < without_bytes,
119- "bytes_shifted split ({with_bytes}) should beat forcing bytes_shifted=0 ({without_bytes})"
120- );
121-}
122-
123 #[test]87 #[test]
124 fn twenty_four_bit_tonal_content_round_trips_bit_exactly() {88 fn twenty_four_bit_tonal_content_round_trips_bit_exactly() {
125 // A smooth tone's first residuals are far bigger than the coder's89 // 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() {
134 .collect();98 .collect();
135 let wide: Vec<i32> = tone.iter().map(|&s| (s << 8) | (rng.next() & 0xff) as i32).collect();99 let wide: Vec<i32> = tone.iter().map(|&s| (s << 8) | (rng.next() & 0xff) as i32).collect();
136 for samples in [&tone, &wide] {100 for samples in [&tone, &wide] {
137- for allow_shift in [true, false] {101+ let enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder");
138- let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder");102+ let mut dec = AlacDecoder::new(*enc.cookie());
139- enc.set_byte_shift(allow_shift);103+ let shift = enc.cookie().container_shift();
140- let mut dec = AlacDecoder::new(*enc.cookie());104+ let mut decoded = Vec::new();
141- let shift = enc.cookie().container_shift();105+ for chunk in samples.chunks(4096 * channels as usize) {
142- let mut decoded = Vec::new();106+ decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift));
143- for chunk in samples.chunks(4096 * channels as usize) {
144- decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift));
145- }
146- assert_eq!(&decoded, samples, "{channels}ch 24-bit tone, shift={allow_shift}");
147-
148- // And the reference decoder agrees with what we wrote.
149- let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples);
150- let got = ffmpeg_decode(&out_path, "s32le");
151- std::fs::remove_dir_all(&dir).ok();
152- let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect();
153- assert!(got == want, "{channels}ch 24-bit tone, shift={allow_shift}: reference decode differs");
154 }107 }
108+ assert_eq!(&decoded, samples, "{channels}ch 24-bit tone");
109+
110+ // And the reference decoder agrees with what we wrote.
111+ let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples);
112+ let got = ffmpeg_decode(&out_path, "s32le");
113+ std::fs::remove_dir_all(&dir).ok();
114+ let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect();
115+ assert!(got == want, "{channels}ch 24-bit tone: reference decode differs");
155 }116 }
156 }117 }
157 }118 }
@@ -188,84 +149,21 @@ fn real_audio_round_trips_and_compresses() {
188 assert!(ratio <= 0.75, "compression ratio {ratio:.4} > 0.75");149 assert!(ratio <= 0.75, "compression ratio {ratio:.4} > 0.75");
189 }150 }
190 151
191-#[test]152+fn round_trip_both_decoders(channels: u8, samples: &[i32], what: &str) {
192-fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() {153+ let enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder");
193- let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
194- let mut reader = ec_riff::WavReader::open(&path).expect("open wav");
195- let spec = reader.spec();
196- let samples = reader.read_all_i32().expect("pcm");
197- let enc = AlacEncoder::new(spec.sample_rate, spec.channels as u8, spec.bits_per_sample as u8, 4096)
198- .expect("encoder");
199-
200- let (dir, out_path) = mux_to_m4a(&enc, spec.channels as usize, spec.sample_rate, &samples);
201-
202- // Sanity without an oracle: our own demuxer/decoder reads it back
203- // bit-exact against the source PCM.
204- let mut demuxer =
205- ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&out_path).expect("open"))).expect("mp4");
206- let track = demuxer
207- .streams()
208- .iter()
209- .find(|s| s.params.codec == CodecId::Alac)
210- .expect("alac track")
211- .clone();
212- let mut dec = AlacDecoder::from_parameters(track.params).expect("cookie");
213- let shift = dec.cookie().container_shift();
214- let mut decoded = Vec::new();
215- loop {
216- match demuxer.next_packet() {
217- Ok(p) if p.stream != track.index => continue,
218- Ok(p) => decoded.extend(dec.decode(&p.data).expect("decode").iter().map(|&s| s >> shift)),
219- Err(e) if e.is_eof() => break,
220- Err(e) => panic!("{e}"),
221- }
222- }
223- assert_eq!(decoded, samples, "mux -> demux -> decode round trip");
224-
225- // The oracle: ffprobe reads the track back as alac at the right rate and
226- // channel count, and ffmpeg's own decode matches the source exactly.
227- let probe = ec_testkit::ffprobe()
228- .args([
229- "-v", "error", "-select_streams", "a:0", "-show_entries",
230- "stream=codec_name,sample_rate,channels",
231- "-of", "default=noprint_wrappers=1",
232- ])
233- .arg(&out_path)
234- .output()
235- .expect("ffprobe");
236- let info = String::from_utf8_lossy(&probe.stdout);
237- assert!(info.contains("codec_name=alac"), "{info}");
238- assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}");
239- assert!(info.contains(&format!("channels={}", spec.channels)), "{info}");
240-
241- let stdout = ffmpeg_decode(&out_path, "s16le");
242- let want: Vec<i16> = samples.iter().map(|&s| s as i16).collect();
243- let got: Vec<i16> = stdout
244- .as_chunks::<2>().0.iter()
245- .map(|c| i16::from_le_bytes([c[0], c[1]]))
246- .collect();
247- assert_eq!(got, want, "ffmpeg decode of the muxed file vs source PCM");
248-
249- let _ = std::fs::remove_dir_all(&dir);
250-}
251-
252-
253-fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, what: &str) {
254- let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder");
255- enc.set_byte_shift(allow_shift);
256 let mut dec = AlacDecoder::new(*enc.cookie());154 let mut dec = AlacDecoder::new(*enc.cookie());
257 let shift = enc.cookie().container_shift();155 let shift = enc.cookie().container_shift();
258 let mut decoded = Vec::new();156 let mut decoded = Vec::new();
259 for chunk in samples.chunks(4096 * channels as usize) {157 for chunk in samples.chunks(4096 * channels as usize) {
260 decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift));158 decoded.extend(dec.decode(&enc.encode_frame(chunk).expect("frame")).expect("decode").iter().map(|&s| s >> shift));
261 }159 }
262- assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit, shift={allow_shift}");160+ assert_eq!(&decoded, samples, "{what}: {channels}ch 24-bit");
263 161
264 let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples);162 let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples);
265 let got = ffmpeg_decode(&out_path, "s32le");163 let got = ffmpeg_decode(&out_path, "s32le");
266 std::fs::remove_dir_all(&dir).ok();164 std::fs::remove_dir_all(&dir).ok();
267 let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect();165 let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect();
268- assert!(got == want, "{what}: {channels}ch 24-bit, shift={allow_shift}: reference decode differs");166+ assert!(got == want, "{what}: {channels}ch 24-bit: reference decode differs");
269 }167 }
270 168
271 #[test]169 #[test]
@@ -275,9 +173,7 @@ fn mono_24_bit_ramp_round_trips_bit_exactly() {
275 // carries, so the encoder must wrap it the way the decoder does.173 // carries, so the encoder must wrap it the way the decoder does.
276 for n in [1015usize, 1016, 1024, 2048, 4096] {174 for n in [1015usize, 1016, 1024, 2048, 4096] {
277 let samples: Vec<i32> = (0..n).map(|i| ((i as i64 * 7919) % 8_000_000 - 4_000_000) as i32).collect();175 let samples: Vec<i32> = (0..n).map(|i| ((i as i64 * 7919) % 8_000_000 - 4_000_000) as i32).collect();
278- for allow_shift in [true, false] {176+ round_trip_both_decoders(1, &samples, &format!("ramp n={n}"));
279- round_trip_both_decoders(1, &samples, allow_shift, &format!("ramp n={n}"));
280- }
281 }177 }
282 }178 }
283 179
@@ -285,7 +181,7 @@ fn mono_24_bit_ramp_round_trips_bit_exactly() {
285 fn mono_24_bit_full_scale_alternating_round_trips() {181 fn mono_24_bit_full_scale_alternating_round_trips() {
286 for n in [512usize, 4096] {182 for n in [512usize, 4096] {
287 let samples: Vec<i32> = (0..n).map(|i| if i % 2 == 0 { 8_388_607 } else { -8_388_607 }).collect();183 let samples: Vec<i32> = (0..n).map(|i| if i % 2 == 0 { 8_388_607 } else { -8_388_607 }).collect();
288- round_trip_both_decoders(1, &samples, true, &format!("alternating n={n}"));184+ round_trip_both_decoders(1, &samples, &format!("alternating n={n}"));
289 }185 }
290 }186 }
291 187