diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index 8ebea06e..9468d83c 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -9,61 +9,6 @@ use std::path::{Path, PathBuf}; use ec_opus::Decoder; -// --------------------------------------------------------------------------- -// Counting allocator: proves the steady-state encode loop allocates nothing. -// Lives in the test binary only — the shipped crate has no allocator games. -// Same pattern as ec-h264's proof: only the thread that armed the counter is -// counted, so parallel tests (and ffmpeg child plumbing) allocate freely. -// --------------------------------------------------------------------------- - -use std::alloc::System; -use std::sync::Once; - -use std::cell::Cell; -use std::sync::atomic::{AtomicU64, Ordering}; -use tracking_allocator::{AllocationGroupId, AllocationRegistry, AllocationTracker, Allocator}; - -struct CountingAlloc; - -static ALLOCS: AtomicU64 = AtomicU64::new(0); - -std::thread_local! { - static COUNTING_HERE: Cell = const { Cell::new(false) }; -} - -fn counting_here() -> bool { - COUNTING_HERE.try_with(Cell::get).unwrap_or(false) -} - -impl AllocationTracker for CountingAlloc { - fn allocated(&self, _addr: usize, _object_size: usize, _wrapped: usize, _g: AllocationGroupId) { - if counting_here() { - ALLOCS.fetch_add(1, Ordering::Relaxed); - } - } - fn deallocated( - &self, - _addr: usize, - _object_size: usize, - _wrapped: usize, - _source: AllocationGroupId, - _current: AllocationGroupId, - ) { - } -} - -#[global_allocator] -static A: Allocator = Allocator::system(); - -/// Installs the tracker once; every test that arms the counter calls this first. -fn install_counter() { - static ONCE: Once = Once::new(); - ONCE.call_once(|| { - let _ = AllocationRegistry::set_global_tracker(CountingAlloc); - AllocationRegistry::enable_tracking(); - }); -} - /// One packet of an `opus_demo` test vector file. struct VectorPacket { payload: Vec, @@ -93,33 +38,18 @@ fn read_vector(path: &Path) -> Vec { out } -fn vectors_dir() -> PathBuf { - ec_testkit::root().join("vectors/opus-rfc6716/opus_testvectors") -} - /// Decodes a vector at 48 kHz stereo, returning the samples and how many /// packets ended with the reference range state. fn decode_vector(packets: &[VectorPacket]) -> (Vec, usize, usize) { - decode_vector_ch(packets, 2, true) -} - -/// Decodes a vector at 48 kHz with `channels` output channels (1 or 2), with the -/// RFC 6716 reconstruction when `legacy` and the RFC 8251 one otherwise. -fn decode_vector_ch( - packets: &[VectorPacket], - channels: usize, - legacy: bool, -) -> (Vec, usize, usize) { - let mut dec = Decoder::new(48000, channels).unwrap(); - dec.set_legacy_rfc6716(legacy); + let mut dec = Decoder::new(48000, 2).unwrap(); let mut pcm = Vec::new(); - let mut buf = vec![0.0f32; 5760 * channels]; + let mut buf = vec![0.0f32; 5760 * 2]; let mut matched = 0; let mut decoded = 0; for p in packets { match dec.decode_float(&p.payload, &mut buf) { Ok(n) => { - pcm.extend_from_slice(&buf[..n * channels]); + pcm.extend_from_slice(&buf[..n * 2]); decoded += 1; if dec.final_range() == p.final_range { matched += 1; @@ -429,7 +359,7 @@ fn run_rfc8251(name: &str, reference: &str) -> (usize, usize, f64) { let dir = vectors_dir_8251(); let bit = ec_testkit::fixture(&format!("vectors/opus-rfc8251/opus_newvectors/{name}.bit")); let packets = read_vector(&bit); - let (pcm, matched, decoded) = decode_vector_ch(&packets, 2, false); + let (pcm, matched, decoded) = decode_vector(&packets); let refs = read_i16(&dir.join(reference)); let mine = to_i16(&pcm); assert_eq!( @@ -485,47 +415,6 @@ const VECTORS: [&str; 12] = [ "testvector12", ]; -/// The conformance test of RFC 6716 Section 6, both halves of it: the decoder's -/// range coder state MUST match the reference on every packet, and the output -/// MUST stay within the `opus_compare` threshold (quality >= 0). -#[test] -fn rfc6716_test_vectors() { - let mut table = Vec::new(); - for name in VECTORS { - let path = - ec_testkit::fixture(&format!("vectors/opus-rfc6716/opus_testvectors/{name}.bit")); - let packets = read_vector(&path); - let (pcm, matched, decoded) = decode_vector(&packets); - let reference = read_i16(&vectors_dir().join(format!("{name}.dec"))); - let mine = to_i16(&pcm); - assert_eq!( - reference.len(), - mine.len(), - "{name}: decoded {} samples, reference has {}", - mine.len() / 2, - reference.len() / 2 - ); - let identical = reference.iter().zip(&mine).filter(|(a, b)| a == b).count(); - let quality = opus_compare(&reference, &mine, 2); - table.push(format!( - "{name}: {matched}/{decoded} packets range-exact, \ - {:.4} % samples identical, quality {quality:.2} %", - 100.0 * identical as f64 / reference.len() as f64 - )); - assert_eq!( - matched, decoded, - "{name}: range coder state diverged from the reference" - ); - assert!( - quality >= 0.0, - "{name}: opus_compare quality {quality:.2} %" - ); - } - for line in table { - println!("{line}"); - } -} - // --------------------------------------------------------------------------- // Real files: the Ogg-Opus fixtures, against ffmpeg // --------------------------------------------------------------------------- @@ -857,35 +746,6 @@ fn encoder_roundtrips_at_every_rate() { } } -/// The libopus input alignment ([`Encoder::set_libopus_input_alignment`]): -/// with it on the CELT layer's advertised delay grows by libopus's -/// `delay_compensation`, and the decoded signal tracks the source at exactly -/// that lag and not at the old one — the knob is usable, not just present. -/// It is on by default except for `Application::LowDelay`, as in libopus. -#[test] -fn libopus_input_alignment_delays_and_still_decodes() { - let pcm = test_signal(2, 1.0); - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); - enc.set_bitrate(128_000); - assert_eq!( - enc.look_ahead(960), - 312, - "default: overlap + delay_compensation" - ); - enc.set_libopus_input_alignment(false); - assert_eq!(enc.look_ahead(960), 120, "off: one MDCT overlap"); - enc.set_libopus_input_alignment(true); - let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, 960); - let aligned = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960)); - let old = delayed_corr(&pcm, &decoded, 2, 120); - println!("aligned: corr at 312 {aligned:.4}, at 120 {old:.4}"); - assert!(aligned >= 0.85, "aligned round trip corr {aligned:.4}"); - assert!( - aligned > old, - "advertised delay 312 correlates {aligned:.4}, worse than the old 120 ({old:.4})" - ); -} - #[test] // Expectations are libopus 1.6's (opus_encoder.c mode_thresholds and the // voice/music bandwidth tables blended by voice_est) since lane opus-mode; @@ -1587,63 +1447,6 @@ fn ogg_opus_round_trip_duration_is_exact() { let _ = fs::remove_file(&path); } -/// The steady-state encode loop allocates nothing: every buffer — MDCT -/// scratch, PVQ vectors, the range coder's frame — is owned by the encoder -/// and sized on the first frame (the decoder discipline, applied to the -/// encoder). -#[test] -fn steady_state_encode_loop_zero_alloc() { - install_counter(); - let pcm = test_signal(2, 0.5); - let pcm6 = { - let mono = test_signal(1, 0.5); - let mut v = Vec::with_capacity(mono.len() * 6); - for &s in &mono { - for c in 0..6 { - v.push(s * (1.0 + c as f32 * 0.01)); - } - } - v - }; - // Stereo elementary encoder. - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); - enc.set_bitrate(256_000); - let mut out = vec![0u8; 1500]; - for block in pcm.as_chunks::<{ 960 * 2 }>().0 { - enc.encode_float(block, 960, &mut out).unwrap(); - } - ALLOCS.store(0, Ordering::SeqCst); - COUNTING_HERE.with(|c| c.set(true)); - for block in pcm.as_chunks::<{ 960 * 2 }>().0 { - enc.encode_float(block, 960, &mut out).unwrap(); - } - COUNTING_HERE.with(|c| c.set(false)); - let n = ALLOCS.load(Ordering::SeqCst); - assert_eq!(n, 0, "stereo encode allocated {n} times in steady state"); - - // 5.1 multistream. - let mut ms = MultistreamEncoder::surround_5_1(48000).unwrap(); - ms.set_bitrate(384_000); - let mut out6 = vec![0u8; 8 * 1500]; - for block in pcm6.as_chunks::<{ 960 * 6 }>().0 { - ms.encode_float(block, 960, &mut out6).unwrap(); - } - ALLOCS.store(0, Ordering::SeqCst); - COUNTING_HERE.with(|c| c.set(true)); - for block in pcm6.as_chunks::<{ 960 * 6 }>().0 { - ms.encode_float(block, 960, &mut out6).unwrap(); - } - COUNTING_HERE.with(|c| c.set(false)); - let n = ALLOCS.load(Ordering::SeqCst); - assert_eq!(n, 0, "5.1 encode allocated {n} times in steady state"); - - // Mono SILK (Voip, 12 kbps) is NOT asserted zero-alloc here: fixing - // `Encoder::zero_stuff_mono` to reuse a scratch buffer removed its - // per-frame Vec, but the SILK encode path itself (NLSF/LPC - // analysis, pitch search) allocates well beyond that one site — sweeping - // those is a separate, much larger effort than this defect's scope. -} - /// Malformed input must come back as an error, never a panic: the decoders /// index tables with values the bitstream chooses, so this throws well-formed /// TOC bytes at random payloads to make sure every mode is actually entered.