From 8f37471df628c112665487f50c2b40de581e365f 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:45 +0300 Subject: [PATCH] U12: ec-ac3 trim tests to ffmpeg_parity, packet_walk, real_library; make internal modules private; drop unused Imdct::reset --- crates/ec-ac3/src/lib.rs | 12 +- crates/ec-ac3/src/transform.rs | 6 - crates/ec-ac3/tests/it/decode_matrix.rs | 309 ------------------ crates/ec-ac3/tests/it/dependent.rs | 250 --------------- crates/ec-ac3/tests/it/encode_matrix.rs | 397 ------------------------ crates/ec-ac3/tests/it/main.rs | 3 - 6 files changed, 6 insertions(+), 971 deletions(-) delete mode 100644 crates/ec-ac3/tests/it/decode_matrix.rs delete mode 100644 crates/ec-ac3/tests/it/dependent.rs delete mode 100644 crates/ec-ac3/tests/it/encode_matrix.rs diff --git a/crates/ec-ac3/src/lib.rs b/crates/ec-ac3/src/lib.rs index 5ebefef4..da701f30 100644 --- a/crates/ec-ac3/src/lib.rs +++ b/crates/ec-ac3/src/lib.rs @@ -60,19 +60,19 @@ mod aht; mod aht_tables; -pub mod bitalloc; +mod bitalloc; pub mod bsi; pub mod eac3; -pub mod exps; -pub mod mantissa; +mod exps; +mod mantissa; pub mod syncinfo; -pub mod tables; -pub mod transform; +mod tables; +mod transform; mod decode; mod dependent; mod decoder; -pub mod encode; +mod encode; pub use decode::Syntax; pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options}; diff --git a/crates/ec-ac3/src/transform.rs b/crates/ec-ac3/src/transform.rs index 7aa74b29..551209ee 100644 --- a/crates/ec-ac3/src/transform.rs +++ b/crates/ec-ac3/src/transform.rs @@ -91,12 +91,6 @@ impl Imdct { } } - /// Drop the overlap-add tail; a seek makes it belong to frames that were - /// never decoded. - pub fn reset(delay: &mut [f32]) { - delay.fill(0.0); - } - fn long_transform(&mut self, coeffs: &[f32]) { // Step 2: pre-IFFT complex multiply. for k in 0..128 { diff --git a/crates/ec-ac3/tests/it/decode_matrix.rs b/crates/ec-ac3/tests/it/decode_matrix.rs deleted file mode 100644 index 706c5e73..00000000 --- a/crates/ec-ac3/tests/it/decode_matrix.rs +++ /dev/null @@ -1,309 +0,0 @@ -//! Fixture matrix: every generated AC-3 and E-AC-3 fixture decoded and -//! compared against ffmpeg, plus the header surface a container reads and the -//! no-panic contract on damaged input. -//! - -use std::path::Path; - -use ec_ac3::{Ac3Decoder, Downmix, Options, Syntax, bsi, eac3, syncinfo}; - -/// Per-channel correlation floor (rubric: audio-ac3 MUST). -const MIN_CORR: f64 = 0.999; -/// RMS delta ceiling on the fixture matrix, where both decoders see the same -/// synthetic material. -const MAX_RMS: f64 = 1e-3; - -/// ffmpeg's decode of `path` as interleaved `f32`. -fn reference(path: &Path) -> Vec { - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-i"]) - .arg(path) - .args(["-f", "f32le", "-"]) - .output() - .expect("ffmpeg"); - out.stdout - .as_chunks::<4>().0.iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect() -} - -/// Our decode of a raw elementary stream, and the channel count. -fn decode(path: &Path, options: Options) -> (Vec, usize) { - let data = std::fs::read(path).expect("fixture"); - let mut decoder = Ac3Decoder::with_options(options); - let (mut out, mut channels, mut pos) = (Vec::new(), 0, 0usize); - while pos + 6 <= data.len() { - if data[pos] != 0x0B || data[pos + 1] != 0x77 { - pos += 1; - continue; - } - let Ok(size) = ec_ac3::frame_size(&data[pos..]) else { - break; - }; - if pos + size > data.len() { - break; - } - let frame = decoder - .decode_frame(&data[pos..pos + size]) - .unwrap_or_else(|e| panic!("{}: {e}", path.display())); - channels = frame.channels(); - out.extend( - frame.data[0] - .as_chunks::<4>().0.iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), - ); - pos += size; - } - (out, channels) -} - -fn correlation(a: &[f32], b: &[f32]) -> (f64, f64) { - let n = a.len().min(b.len()); - let (mut sa, mut sb, mut saa, mut sbb, mut sab, mut sd) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0); - for i in 0..n { - let (x, y) = (f64::from(a[i]), f64::from(b[i])); - sa += x; - sb += y; - saa += x * x; - sbb += y * y; - sab += x * y; - sd += (x - y) * (x - y); - } - let n = n as f64; - let cov = sab / n - (sa / n) * (sb / n); - let va = saa / n - (sa / n).powi(2); - let vb = sbb / n - (sb / n).powi(2); - let corr = if va <= 0.0 || vb <= 0.0 { - 1.0 - } else { - cov / (va * vb).sqrt() - }; - (corr, (sd / n).sqrt()) -} - -#[test] -fn fixture_matrix_matches_ffmpeg() { - let mut checked = 0; - for entry in std::fs::read_dir(ec_testkit::root().join("audio")).expect("audio fixtures") { - let path = entry.expect("entry").path(); - let name = path.file_name().unwrap_or_default().to_string_lossy(); - if !(name.starts_with("ac3-") || name.starts_with("eac3-")) { - continue; - } - // Dither is "any reasonably random sequence" (ยง7.3.4), so two - // conformant decoders differ by exactly that noise. Comparing with it - // off is what isolates everything else; the with-dither run below - // bounds how much noise it adds. - let options = Options { - dither: false, - ..Options::default() - }; - let (ours, channels) = decode(&path, options); - let theirs = reference(&path); - assert!(channels > 0, "{name}: no channels"); - assert_eq!( - ours.len(), - theirs.len(), - "{name}: {} samples vs ffmpeg's {}", - ours.len(), - theirs.len() - ); - for ch in 0..channels { - let a: Vec = ours[ch..].iter().step_by(channels).copied().collect(); - let b: Vec = theirs[ch..].iter().step_by(channels).copied().collect(); - let (corr, rms) = correlation(&a, &b); - assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}"); - assert!(rms <= MAX_RMS, "{name} ch{ch}: RMS delta {rms:.8}"); - } - checked += 1; - } - assert!(checked >= 12, "only {checked} fixtures checked"); -} - -#[test] -fn dither_only_adds_noise_below_the_signal() { - let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); - let (with, channels) = decode(&path, Options::default()); - let (without, _) = decode( - &path, - Options { - dither: false, - ..Options::default() - }, - ); - assert_eq!(with.len(), without.len()); - let (corr, rms) = correlation(&with, &without); - assert!(channels == 6 && corr > 0.999, "correlation {corr:.6}"); - assert!(rms < 1e-3, "dither RMS {rms:.8}"); -} - -#[test] -fn headers_state_what_the_container_needs() { - let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); - let data = std::fs::read(&path).expect("fixture"); - // The exact call shape a container makes: syncinfo from the frame start, - // bsi from five bytes in. - let sync = syncinfo::parse(&data).expect("syncinfo"); - assert_eq!(sync.sample_rate, 48_000); - assert_eq!(sync.frame_size % 2, 0); - let bsi = bsi::parse(&data[5..]).expect("bsi"); - assert_eq!(bsi.nfchans, 5); - assert!(bsi.lfeon); - assert_eq!(bsi.channels, 6); - assert!((1..=31).contains(&bsi.dialnorm)); - - let eac3_path = ec_testkit::fixture("audio/eac3-5.1-48000.eac3"); - let data = std::fs::read(&eac3_path).expect("fixture"); - let hdr = eac3::bsi::parse(&data[2..]).expect("eac3 bsi"); - assert_eq!(hdr.sample_rate, 48_000); - assert_eq!(hdr.nfchans, 5); - assert!(hdr.bsi.lfeon); - assert_eq!( - hdr.frame_size, - ec_ac3::frame_size(&data).expect("frame size") - ); -} - -#[test] -fn frame_info_surfaces_the_metadata_the_rubric_asks_for() { - let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); - let data = std::fs::read(&path).expect("fixture"); - let size = ec_ac3::frame_size(&data).expect("frame size"); - let mut decoder = Ac3Decoder::new(); - decoder.decode_frame(&data[..size]).expect("decode"); - let info = decoder.frame_info().expect("frame info"); - assert_eq!(info.syntax, Syntax::Ac3); - assert_eq!(info.sample_rate, 48_000); - assert!((1..=31).contains(&info.dialnorm)); - // ffmpeg's encoder writes cmixlev 1 (-4.5 dB) and surmixlev 1 (-6 dB). - assert_eq!(info.center_mix_level, Some(0.595)); - assert_eq!(info.surround_mix_level, Some(0.5)); - assert_eq!(info.samples, 1536); -} - -#[test] -fn stereo_downmix_folds_five_one_without_clipping() { - let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); - let (stereo, channels) = decode( - &path, - Options { - downmix: Downmix::Stereo, - ..Options::default() - }, - ); - assert_eq!(channels, 2); - let (native, _) = decode(&path, Options::default()); - assert_eq!(stereo.len() * 3, native.len()); - assert!(stereo.iter().all(|v| v.abs() <= 1.0), "downmix clipped"); - assert!(stereo.iter().any(|v| v.abs() > 0.01), "downmix is silent"); - - let (mono, channels) = decode( - &path, - Options { - downmix: Downmix::Mono, - ..Options::default() - }, - ); - assert_eq!(channels, 1); - assert_eq!(mono.len() * 6, native.len()); -} - -#[test] -fn damaged_input_never_panics() { - let path = ec_testkit::fixture("audio/ac3-stereo-48000.ac3"); - let data = std::fs::read(&path).expect("fixture"); - let size = ec_ac3::frame_size(&data).expect("frame size"); - let frame = &data[..size]; - let mut decoder = Ac3Decoder::new(); - - // Every truncation. - for cut in 0..frame.len() { - let _ = decoder.decode_frame(&frame[..cut]); - } - // Every single-byte corruption at a stride that still hits every field - // class: header, side information, exponents, mantissas. - for pos in (0..frame.len()).step_by(7) { - let mut broken = frame.to_vec(); - broken[pos] ^= 0xA5; - let _ = decoder.decode_frame(&broken); - } - // Garbage that happens to start with a sync word. - let mut noise = vec![0x0B, 0x77]; - let mut state = 12345u32; - for _ in 0..4096 { - state = state.wrapping_mul(1_103_515_245).wrapping_add(12345); - noise.push((state >> 16) as u8); - } - let _ = decoder.decode_frame(&noise); -} - -/// A packet that carries a second frame after the first โ€” the shape a -/// Matroska block for 7.1 DD+ really has (independent substream plus its -/// dependent) โ€” must not decode to the first frame's samples in silence: -/// the tail is stream, and dropping it loses the extension channels without -/// a word. Built from two real frames of the fixture: the tail as it stands -/// (another independent frame) is refused as a second syncframe, and the -/// same packet with the tail's stream-type bits flipped to `dependent` is -/// refused as the dependent substream it then claims to be. The AC-3 path -/// answers the same way for an AC-3 tail. -#[test] -fn a_concatenated_tail_is_refused_by_name_not_dropped() { - for name in ["ac3-5.1-48000.ac3", "eac3-5.1-48000.eac3"] { - let data = std::fs::read(ec_testkit::fixture(&format!("audio/{name}"))).expect("fixture"); - let first = ec_ac3::frame_size(&data).expect("first frame size"); - let second = ec_ac3::frame_size(&data[first..]).expect("second frame size"); - let mut packet = data[..first].to_vec(); - packet.extend_from_slice(&data[first..first + second]); - - let mut dec = Ac3Decoder::new(); - let err = dec - .decode_frame(&packet) - .expect_err("{name}: the tail is stream, not padding"); - let text = err.to_string(); - eprintln!("{name}: {text}"); - assert!( - text.contains("second syncframe"), - "{name}: the independent tail must name itself: {text}" - ); - if name.starts_with("eac3") { - // Flip the tail's stream-type (bits 16..18 of a frame: the top - // two bits of byte 2) to `dependent`. The packet is then the - // shape a 7.1 DD+ block carries, and the refusal names the - // dependent substream. - let mut dep_packet = packet.clone(); - dep_packet[first + 2] = (dep_packet[first + 2] & 0x3F) | 0x40; - let err = dec - .decode_frame(&dep_packet) - .expect_err("the dependent tail is stream"); - let text = err.to_string(); - eprintln!("{name} (tail flipped to dependent): {text}"); - assert!( - text.contains("dependent substream"), - "the dependent tail must name itself: {text}" - ); - } - } -} - -/// The spec's own allowance: a container may pad a block around a frame, and -/// padding that is not itself a syncframe decodes exactly like the bare -/// frame โ€” sample for sample, whatever its length. -#[test] -fn padding_that_is_not_a_syncframe_still_decodes() { - let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); - let data = std::fs::read(&path).expect("fixture"); - let first = ec_ac3::frame_size(&data).expect("frame size"); - let frame = &data[..first]; - let mut dec = Ac3Decoder::new(); - let bare = dec.decode_frame(frame).expect("bare frame"); - for pad in [1usize, 6, 64, 1024] { - let mut padded = frame.to_vec(); - padded.resize(first + pad, 0x00); - let mut dec = Ac3Decoder::new(); - let got = dec.decode_frame(&padded).expect("padded frame decodes"); - assert!( - got.data[0].iter().eq(bare.data[0].iter()), - "pad of {pad} bytes changed the audio" - ); - } -} diff --git a/crates/ec-ac3/tests/it/dependent.rs b/crates/ec-ac3/tests/it/dependent.rs deleted file mode 100644 index 53044953..00000000 --- a/crates/ec-ac3/tests/it/dependent.rs +++ /dev/null @@ -1,250 +0,0 @@ -//! E-AC-3 dependent substreams, checked against ffmpeg's own decode of the same -//! spliced stream: its channel placement (the replace-or-add rule of Table E2.5) -//! and its channel order, which ffprobe names in `channel_layout`. -//! - -use std::path::Path; - -use ec_ac3::{Ac3Decoder, Error, Options, eac3, frame_size}; -use ec_core::{ChannelLayout, ChannelPosition}; - -/// Per-channel correlation floor and RMS ceiling, as in `decode_matrix.rs`. -const MIN_CORR: f64 = 0.999; -const MAX_RMS: f64 = 1e-3; - -/// ffprobe's `channel_layout` name for the first audio stream of `path`. -fn ffprobe_layout(path: &Path) -> String { - let out = ec_testkit::ffprobe() - .args(["-v", "error", "-f", "eac3", "-select_streams", "a:0"]) - .args(["-show_entries", "stream=channel_layout", "-of", "csv=p=0"]) - .arg(path) - .output() - .expect("ffprobe"); - String::from_utf8_lossy(&out.stdout).trim().to_owned() -} - -/// ffmpeg's decode of `path` as interleaved `f32`, in ffmpeg's channel order. -fn reference(path: &Path, channels: usize) -> Vec> { - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-f", "eac3", "-i"]) - .arg(path) - .args(["-f", "f32le", "-"]) - .output() - .expect("ffmpeg"); - let all: Vec = out - .stdout - .as_chunks::<4>() - .0 - .iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - (0..channels) - .map(|ch| all[ch..].iter().step_by(channels).copied().collect()) - .collect() -} - -/// Split a raw E-AC-3 stream into packets: an independent syncframe and the -/// dependent substreams that follow it. -fn packets(data: &[u8]) -> Vec<&[u8]> { - let mut starts = Vec::new(); - let mut pos = 0; - while pos + 6 <= data.len() { - let Ok(size) = frame_size(&data[pos..]) else { - break; - }; - let independent = eac3::bsi::parse(&data[pos + 2..]) - .is_ok_and(|h| h.strmtyp == eac3::StreamType::Independent); - if independent { - starts.push(pos); - } - pos += size; - } - starts - .iter() - .enumerate() - .map(|(i, &s)| &data[s..starts.get(i + 1).copied().unwrap_or(data.len())]) - .collect() -} - -/// Our decode of every packet: interleaved samples, channels and the layout. -fn decode(data: &[u8]) -> (Vec, usize, ChannelLayout) { - let mut decoder = Ac3Decoder::with_options(Options { - dither: false, - ..Options::default() - }); - let (mut out, mut channels, mut layout) = (Vec::new(), 0, ChannelLayout::Mono); - for packet in packets(data) { - let frame = decoder - .decode_frame(packet) - .unwrap_or_else(|e| panic!("packet decode: {e}")); - channels = frame.channels(); - layout = frame.layout.clone(); - out.extend( - frame.data[0] - .as_chunks::<4>() - .0 - .iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), - ); - } - (out, channels, layout) -} - -fn correlation(a: &[f32], b: &[f32]) -> (f64, f64, f64) { - let n = a.len().min(b.len()); - let (mut sa, mut sb, mut saa, mut sbb, mut sab, mut sd) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0); - let mut max_abs = 0.0f64; - for i in 0..n { - let (x, y) = (f64::from(a[i]), f64::from(b[i])); - sa += x; - sb += y; - saa += x * x; - sbb += y * y; - sab += x * y; - sd += (x - y) * (x - y); - max_abs = max_abs.max((x - y).abs()); - } - let n = n as f64; - let cov = sab / n - (sa / n) * (sb / n); - let va = saa / n - (sa / n).powi(2); - let vb = sbb / n - (sb / n).powi(2); - let corr = if va <= 0.0 || vb <= 0.0 { - 1.0 - } else { - cov / (va * vb).sqrt() - }; - (corr, (sd / n).sqrt(), max_abs) -} - -/// The per-channel comparison of our decode of `name` against ffmpeg's decode of -/// the same file. The layout name is ffprobe's, so a wrong channel order fails -/// here even when every channel holds the right signal. -/// -/// With `side_from_core`, channels 6 and 7 (the core's Ls and Rs in a 7.1 layout) -/// are compared against ffmpeg's decode of the 5.1 source instead. ffmpeg 8.1 -/// does not place them correctly once a dependent substream is appended to a -/// core with a side pair: its side-left slot is silent and its side-right slot -/// repeats the dependent's left channel. The core decode is ffmpeg's own -/// unchanged 5.1 path, so it is the reference that ffmpeg itself gets right. -fn check_against_ffmpeg(name: &str, ffprobe_name: &str, layout: &ChannelLayout, side_from_core: bool) { - let stream = ec_testkit::fixture(&format!("audio/{name}")); - let core_side = side_from_core.then(|| reference(&ec_testkit::fixture("audio/ac3dep-src-5.1.eac3"), 6)); - assert_eq!(ffprobe_layout(&stream), ffprobe_name, "{name}: ffprobe channel_layout"); - let data = std::fs::read(&stream).expect("fixture"); - let (ours, channels, ours_layout) = decode(&data); - assert_eq!(&ours_layout, layout, "{name}: layout"); - assert_eq!(channels, layout.channel_count(), "{name}: channels"); - - let theirs = reference(&stream, channels); - let frames = ours.len() / channels; - assert_eq!(frames, theirs[0].len(), "{name}: frame count vs ffmpeg"); - - println!("{name} ({ffprobe_name}): per-channel correlation / RMS delta / max abs error"); - for (ch, from_ffmpeg) in theirs.iter().enumerate() { - let (expect, note) = match (&core_side, ch) { - (Some(c), 6) => (&c[4], " (core Ls, from the 5.1 decode)"), - (Some(c), 7) => (&c[5], " (core Rs, from the 5.1 decode)"), - _ => (from_ffmpeg, ""), - }; - let a: Vec = ours[ch..].iter().step_by(channels).copied().collect(); - let (corr, rms, max_abs) = correlation(&a, expect); - println!(" ch{ch}: {corr:.6} / {rms:.3e} / {max_abs:.3e}{note}"); - assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}"); - assert!(rms <= MAX_RMS, "{name} ch{ch}: RMS delta {rms:.8}"); - } -} - -#[test] -fn seven_one_matches_ffmpeg() { - // Lrs/Rrs (BL/BR) are added to the core's side pair: 8 channels in 7.1 order. - check_against_ffmpeg("ac3dep-7.1-48000.eac3", "7.1", &ChannelLayout::Surround7_1, true); -} - -#[test] -fn seven_one_wide_matches_ffmpeg() { - // Lc/Rc (FLC/FRC) are added; canonical order puts them before the side pair. - let wide = ChannelLayout::Custom(vec![ - ChannelPosition::FrontLeft, - ChannelPosition::FrontRight, - ChannelPosition::FrontCenter, - ChannelPosition::Lfe, - ChannelPosition::FrontLeftOfCenter, - ChannelPosition::FrontRightOfCenter, - ChannelPosition::SideLeft, - ChannelPosition::SideRight, - ]); - check_against_ffmpeg("ac3dep-7.1wide-48000.eac3", "7.1(wide-side)", &wide, true); -} - -#[test] -fn side_pair_replacement_matches_ffmpeg() { - // Ls/Rs replace the core's side pair: 6 channels, not 8. - let side = ChannelLayout::Custom(vec![ - ChannelPosition::FrontLeft, - ChannelPosition::FrontRight, - ChannelPosition::FrontCenter, - ChannelPosition::Lfe, - ChannelPosition::SideLeft, - ChannelPosition::SideRight, - ]); - check_against_ffmpeg("ac3dep-repl-48000.eac3", "5.1(side)", &side, false); -} - -#[test] -fn side_pair_replacement_carries_the_dependent_signal() { - // The replaced pair is the dependent stereo source (880 Hz and 1320 Hz - // sines), not the core's: compare the side channels with ffmpeg's decode - // of that source on its own. - let repl = ec_testkit::fixture("audio/ac3dep-repl-48000.eac3"); - let src20 = ec_testkit::fixture("audio/ac3dep-src-2.0.eac3"); - let data = std::fs::read(&repl).expect("fixture"); - let (ours, channels, _) = decode(&data); - assert_eq!(channels, 6, "replacement keeps the 5.1 channel count"); - let source = reference(&src20, 2); - for (side, src) in [(4usize, 0usize), (5, 1)] { - let a: Vec = ours[side..].iter().step_by(channels).copied().collect(); - let (corr, rms, _) = correlation(&a, &source[src]); - println!("side channel {side} vs dependent source ch{src}: {corr:.6} / {rms:.3e}"); - assert!(corr >= MIN_CORR, "side ch{side}: correlation {corr:.6} against the dependent source"); - } -} - -#[test] -fn dependent_without_an_independent_is_named_not_decoded() { - let stream = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3"); - let data = std::fs::read(&stream).expect("fixture"); - let packet = packets(&data)[0]; - // The dependent frame alone, as a first substream. - let size = frame_size(packet).expect("frame size"); - let dep = &packet[size..]; - let mut decoder = Ac3Decoder::new(); - assert!(matches!( - decoder.decode_frame(dep), - Err(Error::Unsupported { .. }) - )); -} - -#[test] -fn truncated_dependent_substream_is_an_error_not_a_panic() { - let stream = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3"); - let data = std::fs::read(&stream).expect("fixture"); - let packet = packets(&data)[0]; - for cut in [1, 2, 8, 100, 500] { - let mut decoder = Ac3Decoder::new(); - assert!(decoder.decode_frame(&packet[..packet.len() - cut]).is_err()); - } -} - -#[test] -fn a_second_independent_substream_in_the_packet_is_still_refused() { - let src20 = ec_testkit::fixture("audio/ac3dep-src-2.0.eac3"); - let data = std::fs::read(&src20).expect("fixture"); - let first = packets(&data)[0]; - let mut two = first.to_vec(); - two.extend_from_slice(first); - let mut decoder = Ac3Decoder::new(); - assert!(matches!( - decoder.decode_frame(&two), - Err(Error::Unsupported { .. }) - )); -} diff --git a/crates/ec-ac3/tests/it/encode_matrix.rs b/crates/ec-ac3/tests/it/encode_matrix.rs deleted file mode 100644 index 518a724d..00000000 --- a/crates/ec-ac3/tests/it/encode_matrix.rs +++ /dev/null @@ -1,397 +0,0 @@ -//! Encoder coverage: frames our own decoder round-trips, and that ffmpeg -//! synthetic signals and on the real 16-bit fixtures, at every rate and -//! layout the encoder offers. - -use std::path::Path; - -use ec_ac3::{Ac3Decoder, Ac3Encoder, EncoderConfig}; - -/// 440 Hz tone for 1 s, then 0.5 s of silence, interleaved across `channels`. -fn tone_then_silence(sample_rate: u32, channels: usize) -> Vec { - let tone_samples = sample_rate as usize; - let silence_samples = sample_rate as usize / 2; - let mut out = Vec::with_capacity((tone_samples + silence_samples) * channels); - for n in 0..tone_samples { - let t = n as f32 / sample_rate as f32; - let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin(); - for _ in 0..channels { - out.push(v); - } - } - out.extend(std::iter::repeat_n(0.0f32, silence_samples * channels)); - out -} - -fn correlation(a: &[f32], b: &[f32]) -> f64 { - let n = a.len().min(b.len()); - if n == 0 { - return 0.0; - } - let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0); - for i in 0..n { - let (x, y) = (f64::from(a[i]), f64::from(b[i])); - sa += x; - sb += y; - saa += x * x; - sbb += y * y; - sab += x * y; - } - let n = n as f64; - let cov = sab / n - (sa / n) * (sb / n); - let va = (saa / n - (sa / n).powi(2)).max(0.0); - let vb = (sbb / n - (sb / n).powi(2)).max(0.0); - if va <= 0.0 || vb <= 0.0 { - return 1.0; // both flat (silence): trivially aligned - } - cov / (va.sqrt() * vb.sqrt()) -} - -/// Encoder priming, `Ac3Encoder::encoder_delay`: the decoded stream starts -/// with this many samples of silence per channel. -const DELAY: usize = 256; - -/// Lag-searched correlation on one channel after the priming is dropped, -/// +/- 64 samples of slack: a bug that shifts the audio by a block shows up -/// as ~0 here, where an unbounded search on a periodic signal would hide it. -fn best_lag_correlation(a: &[f32], b: &[f32]) -> f64 { - let b = &b[DELAY.min(b.len())..]; - let mut best = -1.0f64; - for lag in -64i32..=64 { - let (sa, sb): (&[f32], &[f32]) = if lag >= 0 { - (&a[lag as usize..], b) - } else { - (a, &b[(-lag) as usize..]) - }; - best = best.max(correlation(sa, sb)); - } - best -} - -/// Deinterleave channel `ch` of `channels`. -fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec { - interleaved - .iter() - .skip(ch) - .step_by(channels) - .copied() - .collect() -} - -fn read_wav(path: &Path) -> (Vec, u32, usize) { - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-i"]) - .arg(path) - .args(["-f", "f32le", "-"]) - .output() - .expect("ffmpeg"); - assert!(out.status.success(), "ffmpeg cannot read {}", path.display()); - let samples = out - .stdout - .as_chunks::<4>().0.iter() - .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect(); - let probe = ffprobe(path, "channels,sample_rate"); - let field = |key: &str| probe_field(&probe, key).and_then(|v| v.parse::().ok()); - (samples, field("sample_rate").unwrap(), field("channels").unwrap() as usize) -} - -fn ffprobe(path: &Path, entries: &str) -> String { - let out = ec_testkit::ffprobe() - .args(["-v", "error", "-select_streams", "a:0", "-show_entries"]) - .arg(format!("stream={entries}")) - .args(["-of", "default=noprint_wrappers=1"]) - .arg(path) - .output() - .expect("ffprobe"); - String::from_utf8_lossy(&out.stdout).into_owned() -} - -fn probe_field(text: &str, key: &str) -> Option { - text.lines() - .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) - .map(|v| v.trim().to_owned()) -} - -/// ffmpeg's decode of an AC-3 file, asserting it voiced no complaint. -fn oracle_decode(path: &Path) -> Vec { - let out = ec_testkit::ffmpeg() - .args(["-v", "warning", "-i"]) - .arg(path) - .args(["-f", "f32le", "-"]) - .output() - .expect("ffmpeg"); - let stderr = String::from_utf8_lossy(&out.stderr); - let complaint = stderr - .lines() - .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k))); - assert!(!complaint, "ffmpeg complained about {}:\n{stderr}", path.display()); - out.stdout - .as_chunks::<4>().0.iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect() -} - -fn encode_with_stats(config: EncoderConfig, pcm: &[f32]) -> (Vec, ec_ac3::EncodeStats) { - let mut enc = Ac3Encoder::new(config).unwrap(); - enc.push_pcm_f32(pcm).unwrap(); - enc.finish(); - let mut out = Vec::new(); - loop { - match enc.next_packet() { - Ok(frame) => out.extend_from_slice(&frame), - Err(e) if e.is_eof() => break, - Err(e) => panic!("{e}"), - } - } - (out, enc.stats()) -} - -fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec { - encode_with_stats(config, pcm).0 -} - -/// Worst per-channel lag-searched correlation between `want` and `got`. -fn worst_corr(want: &[f32], got: &[f32], channels: usize) -> f64 { - (0..channels) - .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch))) - .fold(1.0, f64::min) -} - -/// [`worst_corr`] over the full-bandwidth channels only: the LFE (family slot -/// 3 of six) is band-limited to 7 bins (~660 Hz at 48 kHz) by the standard, -/// so a fixture whose LFE carries full-band content can never correlate with -/// it; that channel is gated on our decoder agreeing with the oracle instead. -fn worst_fbw_corr(want: &[f32], got: &[f32], channels: usize) -> f64 { - (0..channels) - .filter(|&ch| !(channels == 6 && ch == 3)) - .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch))) - .fold(1.0, f64::min) -} - -/// Deterministic white noise, `len` interleaved samples. -fn noise(len: usize, seed: &mut u64) -> Vec { - (0..len) - .map(|_| { - *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0 - }) - .collect() -} - -fn decode_all(data: &[u8], channels: usize) -> Vec { - let mut decoder = Ac3Decoder::new(); - let mut out = Vec::new(); - let mut pos = 0; - while pos + 6 <= data.len() { - let size = ec_ac3::frame_size(&data[pos..]).unwrap(); - assert!(pos + size <= data.len(), "frame overruns the stream"); - let frame = decoder - .decode_frame(&data[pos..pos + size]) - .unwrap_or_else(|e| panic!("frame at byte {pos}: {e}")); - assert_eq!(frame.samples, 1536); - assert_eq!(frame.channels(), channels); - out.extend( - frame.data[0] - .as_chunks::<4>().0.iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])), - ); - pos += size; - } - out -} - -#[test] -fn silence_and_tone_frames_decode_in_our_decoder() { - for &(sample_rate, channels) in &[(48_000u32, 1u16), (48_000, 2), (48_000, 6), (44_100, 2)] { - let config = EncoderConfig { - sample_rate, - channels, - bitrate_kbps: if channels >= 5 { 384 } else { 192 }, - }; - let pcm = tone_then_silence(sample_rate, channels as usize); - let data = encode(config, &pcm); - assert!(!data.is_empty(), "{sample_rate} Hz {channels}ch: no frames"); - let decoded = decode_all(&data, channels as usize); - assert!(!decoded.is_empty()); - let corr = worst_corr(&pcm, &decoded, channels as usize); - assert!(corr >= 0.95, "{sample_rate} Hz {channels}ch: corr {corr}"); - } -} - -#[test] -fn oracle_accepts_our_frames() { - let config = EncoderConfig { - sample_rate: 48_000, - channels: 2, - bitrate_kbps: 192, - }; - let pcm = tone_then_silence(48_000, 2); - let data = encode(config, &pcm); - let dir = std::env::temp_dir(); - let path = dir.join("ec_ac3_encode_matrix_oracle.ac3"); - std::fs::write(&path, &data).unwrap(); - - let out = ec_testkit::ffmpeg() - .args(["-v", "warning", "-i"]) - .arg(&path) - .args(["-f", "f32le", "-"]) - .output() - .expect("ffmpeg"); - let stderr = String::from_utf8_lossy(&out.stderr); - let complaint = stderr - .lines() - .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k))); - assert!( - !complaint, - "ffmpeg complained about our frames:\n{stderr}" - ); - - let decoded: Vec = out - .stdout - .as_chunks::<4>().0.iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - for ch in 0..2 { - let want = take_channel(&pcm, 2, ch); - let got = take_channel(&decoded, 2, ch); - let corr = best_lag_correlation(&want, &got); - assert!(corr >= 0.95, "oracle channel {ch} corr {corr}"); - } - - let _ = std::fs::remove_file(Path::new(&path)); -} - - -/// The full fixture matrix: every wav16 fixture at its layout's bit rate, -/// through our decoder and the oracle, with ffprobe agreeing on what was -/// asked for. Prints the per-file numbers and the stereo strategy shares. -#[test] -fn real_fixtures_round_trip_through_our_decoder_and_the_oracle() { - let root = ec_testkit::root().join("audio"); - let mut failures = Vec::new(); - for layout in ["mono", "stereo", "5.1"] { - for rate in [48_000u32, 44_100] { - let path = root.join(format!("wav16-{layout}-{rate}.wav")); - let (pcm, sample_rate, channels) = read_wav(&path); - assert_eq!(sample_rate, rate); - let bitrate_kbps = match channels { 1 => 96, 2 => 192, _ => 448 }; - let config = EncoderConfig { sample_rate, channels: channels as u16, bitrate_kbps }; - let (data, stats) = encode_with_stats(config, &pcm); - let frame = ec_ac3::frame_size(&data).unwrap(); - assert_eq!(data.len() % frame, 0, "{layout} {rate}: frames are not all {frame} bytes"); - - let decoded = decode_all(&data, channels); - let ours = worst_fbw_corr(&pcm, &decoded, channels); - let out = std::env::temp_dir().join(format!("ec_ac3_encode_matrix_{layout}_{rate}.ac3")); - std::fs::write(&out, &data).unwrap(); - let oracle_pcm = oracle_decode(&out); - let oracle = worst_fbw_corr(&pcm, &oracle_pcm, channels); - if channels == 6 { - let lfe = correlation(&take_channel(&decoded, 6, 3), &take_channel(&oracle_pcm, 6, 3)); - assert!(lfe >= 0.99, "{layout} {rate}: LFE ours vs oracle corr {lfe}"); - } - let probe = ffprobe(&out, "channels,channel_layout,sample_rate,bit_rate"); - let _ = std::fs::remove_file(&out); - - let total = (stats.d15 + stats.d25 + stats.d45 + stats.reuse) as f64; - let share = |n: u64| n as f64 / total * 100.0; - eprintln!( - "{layout} {rate}: {} frames, ours {ours:.4} oracle {oracle:.4}, csnroffst mean {:.1}, fill {:.1}%, blksw {}, D15 {:.1}% D25 {:.1}% D45 {:.1}% REUSE {:.1}%", - stats.frames, - stats.csnroffst_sum as f64 / stats.frames as f64, - stats.bits_used as f64 / stats.bits_budget as f64 * 100.0, - stats.blksw_blocks, - share(stats.d15), share(stats.d25), share(stats.d45), share(stats.reuse), - ); - if ours < 0.99 || oracle < 0.99 { - failures.push(format!("{layout} {rate}: ours {ours:.4} oracle {oracle:.4}")); - } - assert!(stats.bits_used * 10 > stats.bits_budget * 9, "{layout} {rate}: rate loop left bits unused: {stats:?}"); - let expect_layout = match channels { 1 => "mono", 2 => "stereo", _ => "5.1" }; - assert_eq!(probe_field(&probe, "channels").as_deref(), Some(channels.to_string().as_str()), "{probe}"); - assert!(probe_field(&probe, "channel_layout").is_some_and(|l| l.starts_with(expect_layout)), "{probe}"); - assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some(rate.to_string().as_str()), "{probe}"); - assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some((bitrate_kbps * 1000).to_string().as_str()), "{probe}"); - } - } - assert!(failures.is_empty(), "corr < 0.99:\n{}", failures.join("\n")); -} - -/// A train of sharp attacks (decaying 2 kHz bursts, 25 per second) over a -/// quiet noise floor: every attack is a block switch, and the stream still -/// round-trips through both decoders. -#[test] -fn click_train_switches_blocks_and_still_round_trips() { - let channels = 2; - let mut pcm = noise(48_000 * channels, &mut 11u64); - for v in &mut pcm { - *v *= 0.01; - } - for n in (500..48_000).step_by(1900) { - for i in 0..200 { - let v = 0.8 * (-(i as f32) / 40.0).exp() * (i as f32 * 2.0 * std::f32::consts::PI * 2000.0 / 48_000.0).sin(); - for ch in 0..channels { - pcm[(n + i) * channels + ch] += v; - } - } - } - let config = EncoderConfig { sample_rate: 48_000, channels: 2, bitrate_kbps: 192 }; - let (data, stats) = encode_with_stats(config, &pcm); - assert!(stats.blksw_blocks >= 20, "{stats:?}"); - let corr = worst_corr(&pcm, &decode_all(&data, channels), channels); - eprintln!("click train: ours {corr:.4}, {stats:?}"); - assert!(corr >= 0.95, "click train corr {corr}"); - let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3"); - std::fs::write(&out, &data).unwrap(); - let corr = worst_corr(&pcm, &oracle_decode(&out), channels); - let _ = std::fs::remove_file(&out); - eprintln!("click train: oracle {corr:.4}"); - assert!(corr >= 0.95, "click train oracle corr {corr}"); -} - -#[test] -fn tone_at_32khz_round_trips() { - let rate = 32_000; - let pcm: Vec = (0..rate as usize * 2) - .flat_map(|n| { - let t = n as f32 / rate as f32; - let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin(); - [v, 0.5 * v] - }) - .collect(); - let config = EncoderConfig { sample_rate: rate, channels: 2, bitrate_kbps: 96 }; - let data = encode(config, &pcm); - let corr = worst_corr(&pcm, &decode_all(&data, 2), 2); - assert!(corr >= 0.99, "32 kHz ours corr {corr}"); - let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3"); - std::fs::write(&out, &data).unwrap(); - let corr = worst_corr(&pcm, &oracle_decode(&out), 2); - let probe = ffprobe(&out, "sample_rate,bit_rate"); - let _ = std::fs::remove_file(&out); - assert!(corr >= 0.99, "32 kHz oracle corr {corr}"); - assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}"); - assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}"); -} - -/// 200 random (rate, channels, bit rate) configurations, two frames of -/// noise each: nothing panics and our decoder takes every frame. -#[test] -fn random_configs_never_panic_and_always_decode() { - let (mut seed, mut noise_seed) = (99u64, 7u64); - let mut next = |n: u64| { - seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); - (seed >> 33) % n - }; - for _ in 0..200 { - let sample_rate = ec_ac3::tables::SAMPLE_RATE[next(3) as usize]; - let channels = next(6) as u16 + 1; - let bitrate_kbps = ec_ac3::tables::BIT_RATE_KBPS[next(ec_ac3::tables::BIT_RATE_KBPS.len() as u64) as usize]; - let config = EncoderConfig { sample_rate, channels, bitrate_kbps }; - let pcm = noise(1536 * 2 * channels as usize, &mut noise_seed); - let data = encode(config, &pcm); - let decoded = decode_all(&data, channels as usize); - assert!(decoded.len() >= pcm.len() + 256, "{config:?}: {} of {} samples", decoded.len(), pcm.len()); - } -} - - diff --git a/crates/ec-ac3/tests/it/main.rs b/crates/ec-ac3/tests/it/main.rs index 9f8b0b9b..155c80b7 100644 --- a/crates/ec-ac3/tests/it/main.rs +++ b/crates/ec-ac3/tests/it/main.rs @@ -1,9 +1,6 @@ //! One integration-test binary for ec-ac3; each module is one former `tests/*.rs` file. #![forbid(unsafe_code)] -mod decode_matrix; -mod dependent; -mod encode_matrix; mod ffmpeg_parity; mod packet_walk; mod real_library;