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}")); } } diff --git a/crates/ec-flac/tests/level_depth_parity.rs b/crates/ec-flac/tests/level_depth_parity.rs deleted file mode 100644 index 4db4a706..00000000 --- a/crates/ec-flac/tests/level_depth_parity.rs +++ /dev/null @@ -1,330 +0,0 @@ -//! Parity with the flacenc export that ec-flac replaced. -//! -//! edith's old writer ran `flacenc::config::Encoder::default()` (4096-sample -//! fixed blocks, LPC to order 12, Rice partitions to order 6) on 16-bit input, -//! and `engine::flac_write` still asks for 16 bits. The 24-bit path is reachable -//! through the writer, so it is covered too. -//! -//! For every ec-flac level in [`levels`] and every case in [`CASES`], a -//! sine-plus-noise signal generated by ffmpeg (2.0 and 5.1) goes through -//! `ec_flac::encode` and is checked three ways: -//! -//! (a) ffmpeg decodes our stream back to the input PCM byte for byte; -//! (b) STREAMINFO carries the right rate, channels, bit depth and length, and -//! the MD5 of the input PCM (the MD5 is computed by `md5sum`, not by us); -//! (c) our size is at most [`MARGIN`] times the size ffmpeg's own FLAC encoder -//! produces at the matching `-compression_level`. -//! -//! ec-flac has no compression-level enum. Its levels are [`EncoderConfig`] -//! presets, paired with the ffmpeg level they sit nearest to (see [`levels`]). -//! -//! Run the table: -//! cargo test -p ec-flac --release --test level_depth_parity -- --nocapture - -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::Command; - -use ec_flac::decode::FlacReader; -use ec_flac::encode::{EncoderConfig, encode}; - -/// Largest accepted ratio of our size to ffmpeg's size at the matching level. -const MARGIN: f64 = 1.05; - -/// Seconds of signal per case. -const SECONDS: u32 = 5; - -/// (label, ec-flac settings, matching ffmpeg `-compression_level`). -fn levels() -> Vec<(&'static str, EncoderConfig, u8)> { - vec![ - ( - "ec L0 fixed", - EncoderConfig { - max_lpc_order: 0, - max_partition_order: 3, - ..EncoderConfig::default() - }, - 0, - ), - ("ec default (edith)", EncoderConfig::default(), 5), - ( - "ec L8 max", - EncoderConfig { - max_lpc_order: 32, - max_partition_order: 6, - ..EncoderConfig::default() - }, - 8, - ), - ] -} - -struct Case { - name: &'static str, - layout: &'static str, - channels: usize, - rate: u32, - bits: u32, -} - -const CASES: [Case; 4] = [ - Case { - name: "16-bit 2.0 44.1k", - layout: "stereo", - channels: 2, - rate: 44100, - bits: 16, - }, - Case { - name: "16-bit 5.1 48k", - layout: "5.1", - channels: 6, - rate: 48000, - bits: 16, - }, - Case { - name: "24-bit 2.0 48k", - layout: "stereo", - channels: 2, - rate: 48000, - bits: 24, - }, - Case { - name: "24-bit 5.1 48k", - layout: "5.1", - channels: 6, - rate: 48000, - bits: 24, - }, -]; - -fn ffmpeg(args: &[&str]) { - let status = ec_testkit::ffmpeg() - .args(["-hide_banner", "-loglevel", "error", "-y"]) - .args(args) - .status() - .expect("run ffmpeg (is it installed?)"); - assert!(status.success(), "ffmpeg {args:?} failed"); -} - -fn ffprobe_stream(path: &Path) -> (u32, u32, u32) { - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "a:0", - "-show_entries", - "stream=sample_rate,channels,bits_per_raw_sample", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .expect("run ffprobe"); - assert!(out.status.success(), "ffprobe failed on {}", path.display()); - let text = String::from_utf8(out.stdout).expect("ffprobe utf8"); - let fields: Vec = text - .trim() - .split(',') - .map(|f| f.parse().expect("ffprobe numeric field")) - .collect(); - // csv order: sample_rate, channels, bits_per_raw_sample - (fields[0], fields[1], fields[2]) -} - -fn md5_hex(path: &Path) -> String { - let out = Command::new("md5sum") - .arg(path) - .output() - .expect("run md5sum"); - assert!(out.status.success(), "md5sum failed"); - String::from_utf8_lossy(&out.stdout) - .split_whitespace() - .next() - .expect("md5sum digest") - .to_string() -} - -fn fmt_for(bits: u32) -> &'static str { - match bits { - 16 => "s16le", - 24 => "s24le", - _ => panic!("unsupported bit depth {bits}"), - } -} - -/// Sine plus noise, one sine per channel, generated by ffmpeg as raw PCM. -fn generate(dir: &Path, c: &Case) -> PathBuf { - let exprs: Vec = (0..c.channels) - .map(|i| { - let f = 220.0 * (i as f64 + 1.0); - format!("0.4*sin(2*PI*{f}*t)+0.08*(random({i})*2-1)") - }) - .collect(); - let src = format!( - "aevalsrc=exprs={}:s={}:d={}:c={}", - exprs.join("|"), - c.rate, - SECONDS, - c.layout - ); - let path = dir.join(format!("in-{}-{}-{}.raw", c.channels, c.bits, c.rate)); - ffmpeg(&[ - "-f", - "lavfi", - "-i", - &src, - "-f", - fmt_for(c.bits), - path.to_str().unwrap(), - ]); - path -} - -/// Little-endian signed PCM bytes to sign-extended samples. -fn to_samples(pcm: &[u8], bits: u32) -> Vec { - match bits { - 16 => pcm - .as_chunks::<2>() - .0 - .iter() - .map(|b| i16::from_le_bytes(*b) as i32) - .collect(), - 24 => pcm - .as_chunks::<3>() - .0 - .iter() - .map(|b| (((b[0] as i32) | ((b[1] as i32) << 8) | ((b[2] as i32) << 16)) << 8) >> 8) - .collect(), - _ => panic!("unsupported bit depth {bits}"), - } -} - -fn ffmpeg_reference_size(raw: &Path, c: &Case, level: u8, out: &Path) -> u64 { - ffmpeg(&[ - "-f", - fmt_for(c.bits), - "-ar", - &c.rate.to_string(), - "-ac", - &c.channels.to_string(), - "-i", - raw.to_str().unwrap(), - "-c:a", - "flac", - "-compression_level", - &level.to_string(), - out.to_str().unwrap(), - ]); - fs::metadata(out).expect("reference size").len() -} - -#[test] -fn level_and_depth_parity_with_ffmpeg_flac() { - let dir = std::env::temp_dir().join(format!("ec-flac-parity-{}", std::process::id())); - fs::create_dir_all(&dir).expect("create work dir"); - - println!(); - println!( - "| case | ec-flac level | ec-flac bytes | ffmpeg -compression_level | ffmpeg bytes | ratio | verdict |" - ); - println!("|---|---|---|---|---|---|---|"); - - let mut failures: Vec = Vec::new(); - - for c in &CASES { - let raw = generate(&dir, c); - let pcm = fs::read(&raw).expect("read generated pcm"); - let samples = to_samples(&pcm, c.bits); - let frames = (samples.len() / c.channels) as u64; - let md5_expected = md5_hex(&raw); - - for (label, config, ff_level) in levels() { - let tag = format!("{}-{}", c.bits, c.channels); - let flac_path = dir.join(format!("ours-{tag}-{ff_level}.flac")); - let back_path = dir.join(format!("back-{tag}-{ff_level}.raw")); - let ref_path = dir.join(format!("ref-{tag}-{ff_level}.flac")); - - // Encode. - let stream = encode(&config, &samples, c.channels, c.bits, c.rate) - .unwrap_or_else(|e| panic!("encode {} {label}: {e:?}", c.name)); - fs::write(&flac_path, &stream).expect("write our flac"); - let our_size = stream.len() as u64; - - // (b) STREAMINFO, read by our own parser. - let reader = FlacReader::new(&stream).expect("open our stream"); - let info = reader.stream_info().expect("streaminfo").clone(); - let mut bad = Vec::new(); - if info.sample_rate != c.rate { - bad.push(format!("rate {} != {}", info.sample_rate, c.rate)); - } - if usize::from(info.channels) != c.channels { - bad.push(format!("channels {} != {}", info.channels, c.channels)); - } - if u32::from(info.bits_per_sample) != c.bits { - bad.push(format!("bits {} != {}", info.bits_per_sample, c.bits)); - } - if info.total_samples != frames { - bad.push(format!("total_samples {} != {frames}", info.total_samples)); - } - if info.md5.iter().all(|&b| b == 0) { - bad.push("md5 is zero".to_string()); - } - let md5_stream: String = info.md5.iter().map(|b| format!("{b:02x}")).collect(); - if md5_stream != md5_expected { - bad.push(format!("md5 {md5_stream} != input {md5_expected}")); - } - - // (b) cross-checked by ffprobe on the file itself. - let (p_rate, p_ch, p_bits) = ffprobe_stream(&flac_path); - if (p_rate, p_ch as usize, p_bits) != (c.rate, c.channels, c.bits) { - bad.push(format!( - "ffprobe rate/ch/bits {p_rate}/{p_ch}/{p_bits} != {}/{}/{}", - c.rate, c.channels, c.bits - )); - } - - // (a) ffmpeg decodes our stream back to the input, byte for byte. - ffmpeg(&[ - "-i", - flac_path.to_str().unwrap(), - "-f", - fmt_for(c.bits), - back_path.to_str().unwrap(), - ]); - let back = fs::read(&back_path).expect("read decoded pcm"); - if back != pcm { - let first = back.iter().zip(&pcm).position(|(a, b)| a != b); - bad.push(format!( - "not bit-exact: lengths {} vs {}, first diff at byte {first:?}", - back.len(), - pcm.len() - )); - } - - // (c) size against ffmpeg's FLAC encoder at the matching level. - let ref_size = ffmpeg_reference_size(&raw, c, ff_level, &ref_path); - let ratio = our_size as f64 / ref_size as f64; - if ratio > MARGIN { - bad.push(format!("size ratio {ratio:.4} > {MARGIN}")); - } - - let verdict = if bad.is_empty() { "PASS" } else { "FAIL" }; - println!( - "| {} | {} | {} | {} | {} | {:.4} | {} |", - c.name, label, our_size, ff_level, ref_size, ratio, verdict - ); - for b in bad { - failures.push(format!("{} / {label}: {b}", c.name)); - } - } - } - - let _ = fs::remove_dir_all(&dir); - assert!( - failures.is_empty(), - "parity failures:\n{}", - failures.join("\n") - ); -} diff --git a/crates/ec-vorbis/src/decode.rs b/crates/ec-vorbis/src/decode.rs index 95fd8952..661f88b4 100644 --- a/crates/ec-vorbis/src/decode.rs +++ b/crates/ec-vorbis/src/decode.rs @@ -50,14 +50,6 @@ pub struct VorbisDecoder { drained: bool, /// Holds decoded samples until the page granules say which are the stream's. trim: GranuleTrim, - /// Per-block captured decoded residue: (half, per-channel integer residue). - /// Populated only when `enable_residue_capture` is set. - residue_capture: Vec<(usize, Vec>)>, - /// Per-block bit split captured alongside: (floor bits, residue bits, packet bits). - bit_split: Vec<(u64, u64, u64)>, - /// When true, `decode_audio` copies each block's residue (after inverse - /// coupling, before floor multiply) into `residue_capture`. - enable_residue_capture: bool, } impl VorbisDecoder { @@ -97,9 +89,6 @@ impl VorbisDecoder { frames: VecDeque::new(), drained: false, trim: GranuleTrim::new(channels), - residue_capture: Vec::new(), - bit_split: Vec::new(), - enable_residue_capture: false, ident, comments, setup, @@ -185,8 +174,6 @@ impl VorbisDecoder { } let mapping = &self.setup.mappings[mode.mapping]; - let packet_bits = data.len() as u64 * 8; - let before_floors = bits.remaining(); let mut floors = Vec::with_capacity(channels); let mut no_residue = Vec::with_capacity(channels); for &submap in mapping.mux.iter().take(channels) { @@ -201,7 +188,6 @@ impl VorbisDecoder { no_residue.push(state.is_unused()); floors.push(state); } - let after_floors = bits.remaining(); // A coupled pair shares its residue, so one live channel keeps both. for &(magnitude, angle) in &mapping.coupling { if !no_residue[magnitude] || !no_residue[angle] { @@ -266,20 +252,6 @@ impl VorbisDecoder { spectra[angle] = angles; } - if self.enable_residue_capture { - let after_residues = bits.remaining(); - self.bit_split.push(( - before_floors - after_floors, - after_floors - after_residues, - packet_bits, - )); - let captured: Vec> = spectra - .iter() - .map(|ch| ch.iter().map(|&v| v.round() as i32).collect()) - .collect(); - self.residue_capture.push((half, captured)); - } - // Floor times residue, then out of the frequency domain. let window = self.windows.get(mode.block_flag, previous_long, next_long); let mdct = match mode.block_flag { @@ -378,21 +350,6 @@ impl VorbisDecoder { self.trim.reset(); } - /// Enable per-block residue capture for offline histogram analysis. - pub fn enable_residue_capture(&mut self) { - self.enable_residue_capture = true; - } - - /// Take the captured per-block residue: each entry is `(half, per-channel integer residue)`. - pub fn take_residue_capture(&mut self) -> Vec<(usize, Vec>)> { - std::mem::take(&mut self.residue_capture) - } - - /// Take the per-block (floor bits, residue bits, packet bits) captured with the residue. - pub fn take_bit_split(&mut self) -> Vec<(u64, u64, u64)> { - std::mem::take(&mut self.bit_split) - } - } /// Vorbis channel order (§4.3.9) mapped onto [`ChannelLayout`]'s order. /// diff --git a/crates/ec-vorbis/src/encode.rs b/crates/ec-vorbis/src/encode.rs index 307fb2c8..4dd87772 100644 --- a/crates/ec-vorbis/src/encode.rs +++ b/crates/ec-vorbis/src/encode.rs @@ -246,30 +246,6 @@ struct BlockPlan { next_long: bool, } -/// Per-block rate-loop snapshot, captured when `enable_block_log` is set. -/// Used by the sweep to localise dropout seconds to their reservoir state. -#[derive(Debug, Clone, Copy)] -pub struct BlockLog { - /// Centre sample of the block (maps to seconds via `centre / sample_rate`). - pub centre: i64, - /// Block size in samples (2048 long, 256 short). - pub n: usize, - /// Whether this is a long (2048) block. - pub is_long: bool, - /// Whether this block is steady (long, surrounded by long blocks). - pub steady: bool, - /// Coded size of this block's packet in bits. - pub bits: u64, - /// Headroom (dB) actually applied to this block's floor fit. - pub headroom: f64, - /// `self.headroom` after `update_rate` adjusted it. - pub rate_headroom: f64, - /// `reservoir_debt` after `update_rate`. - pub reservoir: f64, - /// Bit target this block was judged against. - pub target: f64, -} - /// The block-switch scheduler's state between calls. #[derive(Debug, Clone, Copy)] enum Sched { @@ -335,16 +311,6 @@ pub struct VorbisEncoder { reservoir_debt: f64, finished: bool, packets: std::collections::VecDeque, - /// Per-block captured quantised residue: (half, per-channel quantised). - /// Populated only when `enable_residue_capture` is set. - residue_capture: Vec<(usize, Vec>)>, - /// Per-block rate-loop snapshots; populated only when `enable_block_log`. - block_log: Vec, - /// When true, `encode_block` records a [`BlockLog`] entry per block. - enable_block_log: bool, - /// When true, `encode_block` copies each block's quantised residue into - /// `residue_capture` for offline histogram analysis. - enable_residue_capture: bool, } impl VorbisEncoder { @@ -444,10 +410,6 @@ impl VorbisEncoder { class_book, residue_books, coupling, - residue_capture: Vec::new(), - enable_residue_capture: false, - block_log: Vec::new(), - enable_block_log: false, }) } @@ -466,31 +428,6 @@ impl VorbisEncoder { &self.params } - /// Enable per-block quantised-residue capture for offline histogram analysis. - pub fn enable_residue_capture(&mut self) { - self.enable_residue_capture = true; - } - - /// Take the captured per-block quantised residue: each entry is `(half, per-channel quantised)`. - pub fn take_residue_capture(&mut self) -> Vec<(usize, Vec>)> { - std::mem::take(&mut self.residue_capture) - } - - /// Enable per-block rate-loop capture for dropout diagnosis. - pub fn enable_block_log(&mut self) { - self.enable_block_log = true; - } - - /// Take the captured per-block rate-loop snapshots. - pub fn take_block_log(&mut self) -> Vec { - std::mem::take(&mut self.block_log) - } - - /// Frequency in Barks for a given Hz — public so tests can bin by band. - pub fn bark_hz(hz: f64) -> f64 { - bark(hz) - } - /// Push planar samples, one slice per channel in [`ec_core::ChannelLayout`] order. pub fn push_planar(&mut self, channels: &[&[f32]]) -> Result<()> { if channels.len() != usize::from(self.config.channels) { @@ -944,38 +881,6 @@ impl VorbisEncoder { break (floor_values, quantised); } }; - if self.enable_residue_capture { - // The bitstream stores the coupled magnitude/angle form; the - // decoder inverse-couples before floor multiply. Capture in that - // same per-channel domain so the histogram matches the decoder- - // side reference capture exactly (sanity: decoding our own .ogg - // reproduces these vectors). - // Main codes the full `half * channels` interleaved region (no - // HF truncation), so every bin below `half` is coded and the - // capture keeps the whole per-channel vector. - let coded = half; - let mut per_channel: Vec> = quantised - .iter() - .map(|ch| { - let mut v = ch[..coded].to_vec(); - v.resize(half, 0); - v - }) - .collect(); - for &(magnitude, angle) in &self.coupling { - let mut mags = std::mem::take(&mut per_channel[magnitude]); - let mut angs = std::mem::take(&mut per_channel[angle]); - for (m, a) in mags.iter_mut().zip(angs.iter_mut()) { - let (l, r) = decouple(*m, *a); - *m = l; - *a = r; - } - per_channel[magnitude] = mags; - per_channel[angle] = angs; - } - self.residue_capture.push((half, per_channel)); - } - let mut out = BitsOut::new(); out.bit(false); let mode = if plan.is_long { MODE_LONG } else { MODE_SHORT }; @@ -998,21 +903,7 @@ impl VorbisEncoder { let bits = out.len(); let delta = (self.centre + (self.prev_n + n) as i64 / 4) - self.centre; let steady = plan.is_long && plan.prev_long && plan.next_long; - let target = self.update_rate(bits, half, channels, delta, steady); - if self.enable_block_log { - let centre = self.centre + (self.prev_n + n) as i64 / 4; - self.block_log.push(BlockLog { - centre, - n, - is_long: plan.is_long, - steady, - bits, - headroom, - rate_headroom: self.headroom, - reservoir: self.reservoir_debt, - target, - }); - } + self.update_rate(bits, half, channels, delta, steady); out.finish() } @@ -1305,18 +1196,6 @@ fn couple(left: i32, right: i32) -> (i32, i32) { }, } } -/// Inverse square-polar coupling on integer residue — the exact inverse of -/// [`couple`] and the integer form of the decoder's §9.4.2 step. Used only to -/// bring the residue capture back to per-channel (magnitude/angle undone) so it -/// matches the decoder-side capture domain. -fn decouple(m: i32, a: i32) -> (i32, i32) { - match (m > 0, a > 0) { - (true, true) => (m, m - a), - (true, false) => (m + a, m), - (false, true) => (m, m + a), - (false, false) => (m - a, m), - } -} /// §7.2.2 `render_point`, which both sides of the floor coding need. fn predict(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { diff --git a/crates/ec-vorbis/src/lib.rs b/crates/ec-vorbis/src/lib.rs index bc0485f7..98fa653e 100644 --- a/crates/ec-vorbis/src/lib.rs +++ b/crates/ec-vorbis/src/lib.rs @@ -42,5 +42,5 @@ mod trim; mod window; pub use decode::{VorbisDecoder, channel_map}; -pub use encode::{BlockLog, EncoderConfig, VorbisEncoder}; +pub use encode::{EncoderConfig, VorbisEncoder}; pub use setup::{Comments, Identification}; diff --git a/crates/ec-vorbis/tests/oracle.rs b/crates/ec-vorbis/tests/oracle.rs index 88d4529f..85ad3dbe 100644 --- a/crates/ec-vorbis/tests/oracle.rs +++ b/crates/ec-vorbis/tests/oracle.rs @@ -530,242 +530,3 @@ fn a_short_input_keeps_its_own_length() { ); } } - -/// Noise-plus-tones: a signal with enough going on that the rate loop has -/// something to spend bits on, which a pure tone does not. -fn busy(channels: usize, rate: u32, samples: usize) -> Vec> { - let mut state = 0x2545_f491_4f6c_dd1du64; - let mut noise = move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - (state >> 40) as f32 / 8_388_608.0 - 1.0 - }; - (0..channels) - .map(|channel| { - (0..samples) - .map(|i| { - let t = i as f64 / f64::from(rate); - let hz = 300.0 * f64::from(channel as u32 + 1); - let tone = (2.0 * std::f64::consts::PI * hz * t).sin() as f32; - 0.35 * tone + 0.35 * noise() - }) - .collect() - }) - .collect() -} - -/// A hard silence-to-full-scale onset must not leak into the long block -/// before it: that block should now be coded with a short right window (or -/// the onset itself carried by a short block), which windows the leak out -/// instead of smearing it across ~46 ms the way an all-long-block encoder -/// does. -#[test] -fn onset_after_silence_has_no_pre_echo() { - // Onsets swept by phase (fractions of a second, so they land anywhere - // relative to the long hop) and by offset from the long-hop grid itself, - // since the short run's placement is decided per hop. Stereo carries - // distinct content per channel — a different tone on the right, starting - // 11 samples later — so coupling cannot hide a per-channel leak. The gap - // is measured over the WHOLE silence up to the onset, so a leak in the - // last few hundred samples before it cannot hide behind a guard band, and - // the peak is barred too. - let amp = 0.7f64; - for (rate, layouts) in [ - (44_100u32, &[1usize, 2][..]), - (48_000, &[1, 2, 6]), - (96_000, &[6]), - ] { - let grid = 16 * 1024usize; - let onsets = [0.3333f64, 0.5, 0.7321, 0.9137, 1.0] - .into_iter() - .map(|s| (s * f64::from(rate)) as usize) - .chain([0usize, 37, 512, 1000, 1023].into_iter().map(|o| grid + o)); - for onset in onsets { - for &channels in layouts { - let tone_len = rate as usize; - let mut source = vec![vec![0.0f32; onset + tone_len + 11 * channels]; channels]; - for (c, plane) in source.iter_mut().enumerate() { - let hz = 1_000.0 + 370.0 * c as f64; - let start = onset + 11 * c; - for i in 0..tone_len { - let t = i as f64 / f64::from(rate); - plane[start + i] = - (amp * (2.0 * std::f64::consts::PI * hz * t).sin()) as f32; - } - } - let name = format!("onset-{rate}-{channels}ch-{onset}.ogg"); - let path = encode_to_file(&source, rate, 128_000, &name); - - // The reference oracle must decode the short-block stream - // cleanly: no warnings, let alone errors. - let out = ec_testkit::ffmpeg() - .args(["-v", "warning", "-i"]) - .arg(&path) - .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) - .output() - .expect("ffmpeg runs"); - assert!( - out.stderr.is_empty(), - "{name}: oracle decode warnings: {}", - String::from_utf8_lossy(&out.stderr) - ); - - let tone_rms = rms(&source[0][onset..]); - let check = |label: &str, planes: &[Vec]| { - for (c, plane) in planes.iter().enumerate() { - let gap = &plane[..onset.min(plane.len())]; - let gap_rms = rms(gap); - let peak = gap.iter().fold(0.0f32, |m, v| m.max(v.abs())); - println!("{name}/{label} ch{c}: gap RMS {gap_rms:.6} peak {peak:.4}"); - assert!( - gap_rms <= 0.002 * tone_rms, - "{name}/{label} ch{c}: gap RMS {gap_rms:.6} vs tone RMS {tone_rms:.6}" - ); - assert!( - f64::from(peak) <= 0.01 * amp, - "{name}/{label} ch{c}: gap peak {peak:.4}" - ); - } - }; - let (ours, _) = our_decode(&path); - check("ours", &ours); - if let Some((theirs, _)) = ffmpeg_decode(&path) { - check("oracle", &theirs); - } - } - } - } -} - -#[test] -fn the_rate_loop_tracks_the_target_bitrate() { - let rate = 48_000u32; - let samples = rate as usize * 3; - let source = busy(2, rate, samples); - let mut measured = Vec::new(); - for target in [96_000i32, 128_000, 192_000] { - let path = encode_to_file( - &source, - rate, - target, - &format!("abr-{}k.ogg", target / 1000), - ); - let bytes = std::fs::metadata(&path).expect("file").len(); - let kbps = bytes as f64 * 8.0 * f64::from(rate) / samples as f64 / 1000.0; - println!("target {} kbps -> {kbps:.0} kbps", target / 1000); - measured.push(kbps); - } - // Monotone in the target, and within a quarter of it: the loop moves one - // quantiser gain, so it tracks rather than hits. - assert!( - measured[0] < measured[1] && measured[1] < measured[2], - "{measured:?}" - ); - for (kbps, target) in measured.iter().zip([96.0, 128.0, 192.0]) { - assert!( - (kbps - target).abs() / target < 0.25, - "{kbps:.0} kbps for a {target:.0} kbps target" - ); - } -} - -/// Quiet and sparse content must reach the target too: with the floor bounded -/// by the threshold of hearing, most partitions code as class 0 at any step, -/// so the rate loop's extra headroom has to lower that bound to find bits to -/// spend. The fixture is a sparse tone at -18 dBFS; the synthetic sources are -/// the busy and tonal signals at -40 dBFS, the tones over a -90 dBFS noise -/// floor (what any 16-bit source carries; a pure digital tone has nothing -/// outside its own bins for any step to find). Noise is incompressible, so the -/// quiet noise is held to the full-scale noise's own fidelity rather than a -/// fixed bar. -/// -/// The rate loop's step search bottoms out at the +-127 step range (36 dB -/// residue range + 12-point floor): once a quiet source's codable residue is -/// exhausted, no finer step can spend more bits without a second (cascade) -/// coding pass, which does not exist yet -- that cascade is the upgrade path. -/// So the contract is: measured kbps lands within +-25% of target, OR the -/// encode undershoots because there is nothing left to spend and the result -/// is transparent (corr >= 0.999 against the source). The monotone-in-target -/// spend check only applies where the case actually spends against target. -#[test] -fn quiet_content_reaches_the_target_or_is_transparent() { - let rate = 48_000u32; - let samples = rate as usize * 3; - let fixture = - ffmpeg_decode(&fixtures().join("audio/wav16-stereo-48000.wav")).expect("fixture decodes"); - assert_eq!(fixture.1, rate); - let attenuate = |mut source: Vec>| { - for channel in source.iter_mut() { - for value in channel.iter_mut() { - *value *= 0.01; - } - } - source - }; - let corr_at = |path: &Path, source: &[Vec]| { - let (decoded, _) = our_decode(path); - decoded - .iter() - .zip(source.iter()) - .map(|(channel, original)| { - let n = channel.len().min(original.len()); - correlation(&channel[..n], &original[..n]) - }) - .fold(1.0f64, f64::min) - }; - let loud = busy(2, rate, samples); - let loud_corr = corr_at( - &encode_to_file(&loud, rate, 128_000, "loud-128k.ogg"), - &loud, - ); - let quiet_noise = attenuate(loud); - let mut quiet_tones = attenuate(tones(2, rate, samples)); - for (channel, noise) in quiet_tones.iter_mut().zip(busy(2, rate, samples)) { - for (value, n) in channel.iter_mut().zip(noise) { - *value += n * 0.0001; - } - } - let cases = [ - ("fixture", &fixture.0, 0.99), - ("quiet-tones", &quiet_tones, 0.99), - ("quiet-noise", &quiet_noise, loud_corr - 0.02), - ]; - for (name, source, bar) in cases { - let mut measured = Vec::new(); - let mut spent = Vec::new(); - for target in [96_000i32, 128_000, 192_000] { - let path = encode_to_file( - source, - rate, - target, - &format!("{name}-{}k.ogg", target / 1000), - ); - let bytes = std::fs::metadata(&path).expect("file").len(); - let kbps = bytes as f64 * 8.0 * f64::from(rate) / source[0].len() as f64 / 1000.0; - let corr = corr_at(&path, source); - println!( - "{name}: target {} kbps -> {kbps:.0} kbps, corr {corr:.4}", - target / 1000 - ); - let target_kbps = f64::from(target) / 1000.0; - let within_25pct = (kbps - target_kbps).abs() / target_kbps < 0.25; - let transparent_undershoot = kbps < target_kbps && corr >= 0.999; - assert!( - within_25pct || transparent_undershoot, - "{name}: {kbps:.0} kbps for {target_kbps:.0} kbps target, corr {corr:.4}" - ); - spent.push(within_25pct); - measured.push(kbps); - if target == 128_000 { - assert!(corr >= bar, "{name}: corr {corr:.4} under {bar:.4}"); - } - } - if spent.iter().all(|&s| s) { - assert!( - measured[0] < measured[1] && measured[1] < measured[2], - "{name}: {measured:?}" - ); - } - } -}