forge
Explore
Log in

Don't you dare go Hollow

U12: ec-ac3 trim tests to ffmpeg_parity, packet_walk, real_library; make internal modules private; drop unused Imdct::reset

Browse files at this commit

8f37471df628c112665487f50c2b40de581e365fAhmet Kaan GümüşParent: 8122b34
crates/ec-ac3/src/lib.rsmodified+6 -6
@@ -60,19 +60,19 @@
6060 mod aht;
6161 mod aht_tables;
6262
63-pub mod bitalloc;
63+mod bitalloc;
6464 pub mod bsi;
6565 pub mod eac3;
66-pub mod exps;
67-pub mod mantissa;
66+mod exps;
67+mod mantissa;
6868 pub mod syncinfo;
69-pub mod tables;
70-pub mod transform;
69+mod tables;
70+mod transform;
7171
7272 mod decode;
7373 mod dependent;
7474 mod decoder;
75-pub mod encode;
75+mod encode;
7676
7777 pub use decode::Syntax;
7878 pub use decoder::{Ac3Decoder, Downmix, FrameInfo, Options};
crates/ec-ac3/src/transform.rsmodified+0 -6
@@ -91,12 +91,6 @@ impl Imdct {
9191 }
9292 }
9393
94- /// Drop the overlap-add tail; a seek makes it belong to frames that were
95- /// never decoded.
96- pub fn reset(delay: &mut [f32]) {
97- delay.fill(0.0);
98- }
99-
10094 fn long_transform(&mut self, coeffs: &[f32]) {
10195 // Step 2: pre-IFFT complex multiply.
10296 for k in 0..128 {
crates/ec-ac3/tests/it/decode_matrix.rsdeleted+0 -309
@@ -1,309 +0,0 @@
1-//! Fixture matrix: every generated AC-3 and E-AC-3 fixture decoded and
2-//! compared against ffmpeg, plus the header surface a container reads and the
3-//! no-panic contract on damaged input.
4-//!
5-
6-use std::path::Path;
7-
8-use ec_ac3::{Ac3Decoder, Downmix, Options, Syntax, bsi, eac3, syncinfo};
9-
10-/// Per-channel correlation floor (rubric: audio-ac3 MUST).
11-const MIN_CORR: f64 = 0.999;
12-/// RMS delta ceiling on the fixture matrix, where both decoders see the same
13-/// synthetic material.
14-const MAX_RMS: f64 = 1e-3;
15-
16-/// ffmpeg's decode of `path` as interleaved `f32`.
17-fn reference(path: &Path) -> Vec<f32> {
18- let out = ec_testkit::ffmpeg()
19- .args(["-v", "error", "-i"])
20- .arg(path)
21- .args(["-f", "f32le", "-"])
22- .output()
23- .expect("ffmpeg");
24- out.stdout
25- .as_chunks::<4>().0.iter()
26- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
27- .collect()
28-}
29-
30-/// Our decode of a raw elementary stream, and the channel count.
31-fn decode(path: &Path, options: Options) -> (Vec<f32>, usize) {
32- let data = std::fs::read(path).expect("fixture");
33- let mut decoder = Ac3Decoder::with_options(options);
34- let (mut out, mut channels, mut pos) = (Vec::new(), 0, 0usize);
35- while pos + 6 <= data.len() {
36- if data[pos] != 0x0B || data[pos + 1] != 0x77 {
37- pos += 1;
38- continue;
39- }
40- let Ok(size) = ec_ac3::frame_size(&data[pos..]) else {
41- break;
42- };
43- if pos + size > data.len() {
44- break;
45- }
46- let frame = decoder
47- .decode_frame(&data[pos..pos + size])
48- .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
49- channels = frame.channels();
50- out.extend(
51- frame.data[0]
52- .as_chunks::<4>().0.iter()
53- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
54- );
55- pos += size;
56- }
57- (out, channels)
58-}
59-
60-fn correlation(a: &[f32], b: &[f32]) -> (f64, f64) {
61- let n = a.len().min(b.len());
62- 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);
63- for i in 0..n {
64- let (x, y) = (f64::from(a[i]), f64::from(b[i]));
65- sa += x;
66- sb += y;
67- saa += x * x;
68- sbb += y * y;
69- sab += x * y;
70- sd += (x - y) * (x - y);
71- }
72- let n = n as f64;
73- let cov = sab / n - (sa / n) * (sb / n);
74- let va = saa / n - (sa / n).powi(2);
75- let vb = sbb / n - (sb / n).powi(2);
76- let corr = if va <= 0.0 || vb <= 0.0 {
77- 1.0
78- } else {
79- cov / (va * vb).sqrt()
80- };
81- (corr, (sd / n).sqrt())
82-}
83-
84-#[test]
85-fn fixture_matrix_matches_ffmpeg() {
86- let mut checked = 0;
87- for entry in std::fs::read_dir(ec_testkit::root().join("audio")).expect("audio fixtures") {
88- let path = entry.expect("entry").path();
89- let name = path.file_name().unwrap_or_default().to_string_lossy();
90- if !(name.starts_with("ac3-") || name.starts_with("eac3-")) {
91- continue;
92- }
93- // Dither is "any reasonably random sequence" (§7.3.4), so two
94- // conformant decoders differ by exactly that noise. Comparing with it
95- // off is what isolates everything else; the with-dither run below
96- // bounds how much noise it adds.
97- let options = Options {
98- dither: false,
99- ..Options::default()
100- };
101- let (ours, channels) = decode(&path, options);
102- let theirs = reference(&path);
103- assert!(channels > 0, "{name}: no channels");
104- assert_eq!(
105- ours.len(),
106- theirs.len(),
107- "{name}: {} samples vs ffmpeg's {}",
108- ours.len(),
109- theirs.len()
110- );
111- for ch in 0..channels {
112- let a: Vec<f32> = ours[ch..].iter().step_by(channels).copied().collect();
113- let b: Vec<f32> = theirs[ch..].iter().step_by(channels).copied().collect();
114- let (corr, rms) = correlation(&a, &b);
115- assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}");
116- assert!(rms <= MAX_RMS, "{name} ch{ch}: RMS delta {rms:.8}");
117- }
118- checked += 1;
119- }
120- assert!(checked >= 12, "only {checked} fixtures checked");
121-}
122-
123-#[test]
124-fn dither_only_adds_noise_below_the_signal() {
125- let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
126- let (with, channels) = decode(&path, Options::default());
127- let (without, _) = decode(
128- &path,
129- Options {
130- dither: false,
131- ..Options::default()
132- },
133- );
134- assert_eq!(with.len(), without.len());
135- let (corr, rms) = correlation(&with, &without);
136- assert!(channels == 6 && corr > 0.999, "correlation {corr:.6}");
137- assert!(rms < 1e-3, "dither RMS {rms:.8}");
138-}
139-
140-#[test]
141-fn headers_state_what_the_container_needs() {
142- let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
143- let data = std::fs::read(&path).expect("fixture");
144- // The exact call shape a container makes: syncinfo from the frame start,
145- // bsi from five bytes in.
146- let sync = syncinfo::parse(&data).expect("syncinfo");
147- assert_eq!(sync.sample_rate, 48_000);
148- assert_eq!(sync.frame_size % 2, 0);
149- let bsi = bsi::parse(&data[5..]).expect("bsi");
150- assert_eq!(bsi.nfchans, 5);
151- assert!(bsi.lfeon);
152- assert_eq!(bsi.channels, 6);
153- assert!((1..=31).contains(&bsi.dialnorm));
154-
155- let eac3_path = ec_testkit::fixture("audio/eac3-5.1-48000.eac3");
156- let data = std::fs::read(&eac3_path).expect("fixture");
157- let hdr = eac3::bsi::parse(&data[2..]).expect("eac3 bsi");
158- assert_eq!(hdr.sample_rate, 48_000);
159- assert_eq!(hdr.nfchans, 5);
160- assert!(hdr.bsi.lfeon);
161- assert_eq!(
162- hdr.frame_size,
163- ec_ac3::frame_size(&data).expect("frame size")
164- );
165-}
166-
167-#[test]
168-fn frame_info_surfaces_the_metadata_the_rubric_asks_for() {
169- let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
170- let data = std::fs::read(&path).expect("fixture");
171- let size = ec_ac3::frame_size(&data).expect("frame size");
172- let mut decoder = Ac3Decoder::new();
173- decoder.decode_frame(&data[..size]).expect("decode");
174- let info = decoder.frame_info().expect("frame info");
175- assert_eq!(info.syntax, Syntax::Ac3);
176- assert_eq!(info.sample_rate, 48_000);
177- assert!((1..=31).contains(&info.dialnorm));
178- // ffmpeg's encoder writes cmixlev 1 (-4.5 dB) and surmixlev 1 (-6 dB).
179- assert_eq!(info.center_mix_level, Some(0.595));
180- assert_eq!(info.surround_mix_level, Some(0.5));
181- assert_eq!(info.samples, 1536);
182-}
183-
184-#[test]
185-fn stereo_downmix_folds_five_one_without_clipping() {
186- let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
187- let (stereo, channels) = decode(
188- &path,
189- Options {
190- downmix: Downmix::Stereo,
191- ..Options::default()
192- },
193- );
194- assert_eq!(channels, 2);
195- let (native, _) = decode(&path, Options::default());
196- assert_eq!(stereo.len() * 3, native.len());
197- assert!(stereo.iter().all(|v| v.abs() <= 1.0), "downmix clipped");
198- assert!(stereo.iter().any(|v| v.abs() > 0.01), "downmix is silent");
199-
200- let (mono, channels) = decode(
201- &path,
202- Options {
203- downmix: Downmix::Mono,
204- ..Options::default()
205- },
206- );
207- assert_eq!(channels, 1);
208- assert_eq!(mono.len() * 6, native.len());
209-}
210-
211-#[test]
212-fn damaged_input_never_panics() {
213- let path = ec_testkit::fixture("audio/ac3-stereo-48000.ac3");
214- let data = std::fs::read(&path).expect("fixture");
215- let size = ec_ac3::frame_size(&data).expect("frame size");
216- let frame = &data[..size];
217- let mut decoder = Ac3Decoder::new();
218-
219- // Every truncation.
220- for cut in 0..frame.len() {
221- let _ = decoder.decode_frame(&frame[..cut]);
222- }
223- // Every single-byte corruption at a stride that still hits every field
224- // class: header, side information, exponents, mantissas.
225- for pos in (0..frame.len()).step_by(7) {
226- let mut broken = frame.to_vec();
227- broken[pos] ^= 0xA5;
228- let _ = decoder.decode_frame(&broken);
229- }
230- // Garbage that happens to start with a sync word.
231- let mut noise = vec![0x0B, 0x77];
232- let mut state = 12345u32;
233- for _ in 0..4096 {
234- state = state.wrapping_mul(1_103_515_245).wrapping_add(12345);
235- noise.push((state >> 16) as u8);
236- }
237- let _ = decoder.decode_frame(&noise);
238-}
239-
240-/// A packet that carries a second frame after the first — the shape a
241-/// Matroska block for 7.1 DD+ really has (independent substream plus its
242-/// dependent) — must not decode to the first frame's samples in silence:
243-/// the tail is stream, and dropping it loses the extension channels without
244-/// a word. Built from two real frames of the fixture: the tail as it stands
245-/// (another independent frame) is refused as a second syncframe, and the
246-/// same packet with the tail's stream-type bits flipped to `dependent` is
247-/// refused as the dependent substream it then claims to be. The AC-3 path
248-/// answers the same way for an AC-3 tail.
249-#[test]
250-fn a_concatenated_tail_is_refused_by_name_not_dropped() {
251- for name in ["ac3-5.1-48000.ac3", "eac3-5.1-48000.eac3"] {
252- let data = std::fs::read(ec_testkit::fixture(&format!("audio/{name}"))).expect("fixture");
253- let first = ec_ac3::frame_size(&data).expect("first frame size");
254- let second = ec_ac3::frame_size(&data[first..]).expect("second frame size");
255- let mut packet = data[..first].to_vec();
256- packet.extend_from_slice(&data[first..first + second]);
257-
258- let mut dec = Ac3Decoder::new();
259- let err = dec
260- .decode_frame(&packet)
261- .expect_err("{name}: the tail is stream, not padding");
262- let text = err.to_string();
263- eprintln!("{name}: {text}");
264- assert!(
265- text.contains("second syncframe"),
266- "{name}: the independent tail must name itself: {text}"
267- );
268- if name.starts_with("eac3") {
269- // Flip the tail's stream-type (bits 16..18 of a frame: the top
270- // two bits of byte 2) to `dependent`. The packet is then the
271- // shape a 7.1 DD+ block carries, and the refusal names the
272- // dependent substream.
273- let mut dep_packet = packet.clone();
274- dep_packet[first + 2] = (dep_packet[first + 2] & 0x3F) | 0x40;
275- let err = dec
276- .decode_frame(&dep_packet)
277- .expect_err("the dependent tail is stream");
278- let text = err.to_string();
279- eprintln!("{name} (tail flipped to dependent): {text}");
280- assert!(
281- text.contains("dependent substream"),
282- "the dependent tail must name itself: {text}"
283- );
284- }
285- }
286-}
287-
288-/// The spec's own allowance: a container may pad a block around a frame, and
289-/// padding that is not itself a syncframe decodes exactly like the bare
290-/// frame — sample for sample, whatever its length.
291-#[test]
292-fn padding_that_is_not_a_syncframe_still_decodes() {
293- let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
294- let data = std::fs::read(&path).expect("fixture");
295- let first = ec_ac3::frame_size(&data).expect("frame size");
296- let frame = &data[..first];
297- let mut dec = Ac3Decoder::new();
298- let bare = dec.decode_frame(frame).expect("bare frame");
299- for pad in [1usize, 6, 64, 1024] {
300- let mut padded = frame.to_vec();
301- padded.resize(first + pad, 0x00);
302- let mut dec = Ac3Decoder::new();
303- let got = dec.decode_frame(&padded).expect("padded frame decodes");
304- assert!(
305- got.data[0].iter().eq(bare.data[0].iter()),
306- "pad of {pad} bytes changed the audio"
307- );
308- }
309-}
crates/ec-ac3/tests/it/dependent.rsdeleted+0 -250
@@ -1,250 +0,0 @@
1-//! E-AC-3 dependent substreams, checked against ffmpeg's own decode of the same
2-//! spliced stream: its channel placement (the replace-or-add rule of Table E2.5)
3-//! and its channel order, which ffprobe names in `channel_layout`.
4-//!
5-
6-use std::path::Path;
7-
8-use ec_ac3::{Ac3Decoder, Error, Options, eac3, frame_size};
9-use ec_core::{ChannelLayout, ChannelPosition};
10-
11-/// Per-channel correlation floor and RMS ceiling, as in `decode_matrix.rs`.
12-const MIN_CORR: f64 = 0.999;
13-const MAX_RMS: f64 = 1e-3;
14-
15-/// ffprobe's `channel_layout` name for the first audio stream of `path`.
16-fn ffprobe_layout(path: &Path) -> String {
17- let out = ec_testkit::ffprobe()
18- .args(["-v", "error", "-f", "eac3", "-select_streams", "a:0"])
19- .args(["-show_entries", "stream=channel_layout", "-of", "csv=p=0"])
20- .arg(path)
21- .output()
22- .expect("ffprobe");
23- String::from_utf8_lossy(&out.stdout).trim().to_owned()
24-}
25-
26-/// ffmpeg's decode of `path` as interleaved `f32`, in ffmpeg's channel order.
27-fn reference(path: &Path, channels: usize) -> Vec<Vec<f32>> {
28- let out = ec_testkit::ffmpeg()
29- .args(["-v", "error", "-f", "eac3", "-i"])
30- .arg(path)
31- .args(["-f", "f32le", "-"])
32- .output()
33- .expect("ffmpeg");
34- let all: Vec<f32> = out
35- .stdout
36- .as_chunks::<4>()
37- .0
38- .iter()
39- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
40- .collect();
41- (0..channels)
42- .map(|ch| all[ch..].iter().step_by(channels).copied().collect())
43- .collect()
44-}
45-
46-/// Split a raw E-AC-3 stream into packets: an independent syncframe and the
47-/// dependent substreams that follow it.
48-fn packets(data: &[u8]) -> Vec<&[u8]> {
49- let mut starts = Vec::new();
50- let mut pos = 0;
51- while pos + 6 <= data.len() {
52- let Ok(size) = frame_size(&data[pos..]) else {
53- break;
54- };
55- let independent = eac3::bsi::parse(&data[pos + 2..])
56- .is_ok_and(|h| h.strmtyp == eac3::StreamType::Independent);
57- if independent {
58- starts.push(pos);
59- }
60- pos += size;
61- }
62- starts
63- .iter()
64- .enumerate()
65- .map(|(i, &s)| &data[s..starts.get(i + 1).copied().unwrap_or(data.len())])
66- .collect()
67-}
68-
69-/// Our decode of every packet: interleaved samples, channels and the layout.
70-fn decode(data: &[u8]) -> (Vec<f32>, usize, ChannelLayout) {
71- let mut decoder = Ac3Decoder::with_options(Options {
72- dither: false,
73- ..Options::default()
74- });
75- let (mut out, mut channels, mut layout) = (Vec::new(), 0, ChannelLayout::Mono);
76- for packet in packets(data) {
77- let frame = decoder
78- .decode_frame(packet)
79- .unwrap_or_else(|e| panic!("packet decode: {e}"));
80- channels = frame.channels();
81- layout = frame.layout.clone();
82- out.extend(
83- frame.data[0]
84- .as_chunks::<4>()
85- .0
86- .iter()
87- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
88- );
89- }
90- (out, channels, layout)
91-}
92-
93-fn correlation(a: &[f32], b: &[f32]) -> (f64, f64, f64) {
94- let n = a.len().min(b.len());
95- 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);
96- let mut max_abs = 0.0f64;
97- for i in 0..n {
98- let (x, y) = (f64::from(a[i]), f64::from(b[i]));
99- sa += x;
100- sb += y;
101- saa += x * x;
102- sbb += y * y;
103- sab += x * y;
104- sd += (x - y) * (x - y);
105- max_abs = max_abs.max((x - y).abs());
106- }
107- let n = n as f64;
108- let cov = sab / n - (sa / n) * (sb / n);
109- let va = saa / n - (sa / n).powi(2);
110- let vb = sbb / n - (sb / n).powi(2);
111- let corr = if va <= 0.0 || vb <= 0.0 {
112- 1.0
113- } else {
114- cov / (va * vb).sqrt()
115- };
116- (corr, (sd / n).sqrt(), max_abs)
117-}
118-
119-/// The per-channel comparison of our decode of `name` against ffmpeg's decode of
120-/// the same file. The layout name is ffprobe's, so a wrong channel order fails
121-/// here even when every channel holds the right signal.
122-///
123-/// With `side_from_core`, channels 6 and 7 (the core's Ls and Rs in a 7.1 layout)
124-/// are compared against ffmpeg's decode of the 5.1 source instead. ffmpeg 8.1
125-/// does not place them correctly once a dependent substream is appended to a
126-/// core with a side pair: its side-left slot is silent and its side-right slot
127-/// repeats the dependent's left channel. The core decode is ffmpeg's own
128-/// unchanged 5.1 path, so it is the reference that ffmpeg itself gets right.
129-fn check_against_ffmpeg(name: &str, ffprobe_name: &str, layout: &ChannelLayout, side_from_core: bool) {
130- let stream = ec_testkit::fixture(&format!("audio/{name}"));
131- let core_side = side_from_core.then(|| reference(&ec_testkit::fixture("audio/ac3dep-src-5.1.eac3"), 6));
132- assert_eq!(ffprobe_layout(&stream), ffprobe_name, "{name}: ffprobe channel_layout");
133- let data = std::fs::read(&stream).expect("fixture");
134- let (ours, channels, ours_layout) = decode(&data);
135- assert_eq!(&ours_layout, layout, "{name}: layout");
136- assert_eq!(channels, layout.channel_count(), "{name}: channels");
137-
138- let theirs = reference(&stream, channels);
139- let frames = ours.len() / channels;
140- assert_eq!(frames, theirs[0].len(), "{name}: frame count vs ffmpeg");
141-
142- println!("{name} ({ffprobe_name}): per-channel correlation / RMS delta / max abs error");
143- for (ch, from_ffmpeg) in theirs.iter().enumerate() {
144- let (expect, note) = match (&core_side, ch) {
145- (Some(c), 6) => (&c[4], " (core Ls, from the 5.1 decode)"),
146- (Some(c), 7) => (&c[5], " (core Rs, from the 5.1 decode)"),
147- _ => (from_ffmpeg, ""),
148- };
149- let a: Vec<f32> = ours[ch..].iter().step_by(channels).copied().collect();
150- let (corr, rms, max_abs) = correlation(&a, expect);
151- println!(" ch{ch}: {corr:.6} / {rms:.3e} / {max_abs:.3e}{note}");
152- assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}");
153- assert!(rms <= MAX_RMS, "{name} ch{ch}: RMS delta {rms:.8}");
154- }
155-}
156-
157-#[test]
158-fn seven_one_matches_ffmpeg() {
159- // Lrs/Rrs (BL/BR) are added to the core's side pair: 8 channels in 7.1 order.
160- check_against_ffmpeg("ac3dep-7.1-48000.eac3", "7.1", &ChannelLayout::Surround7_1, true);
161-}
162-
163-#[test]
164-fn seven_one_wide_matches_ffmpeg() {
165- // Lc/Rc (FLC/FRC) are added; canonical order puts them before the side pair.
166- let wide = ChannelLayout::Custom(vec![
167- ChannelPosition::FrontLeft,
168- ChannelPosition::FrontRight,
169- ChannelPosition::FrontCenter,
170- ChannelPosition::Lfe,
171- ChannelPosition::FrontLeftOfCenter,
172- ChannelPosition::FrontRightOfCenter,
173- ChannelPosition::SideLeft,
174- ChannelPosition::SideRight,
175- ]);
176- check_against_ffmpeg("ac3dep-7.1wide-48000.eac3", "7.1(wide-side)", &wide, true);
177-}
178-
179-#[test]
180-fn side_pair_replacement_matches_ffmpeg() {
181- // Ls/Rs replace the core's side pair: 6 channels, not 8.
182- let side = ChannelLayout::Custom(vec![
183- ChannelPosition::FrontLeft,
184- ChannelPosition::FrontRight,
185- ChannelPosition::FrontCenter,
186- ChannelPosition::Lfe,
187- ChannelPosition::SideLeft,
188- ChannelPosition::SideRight,
189- ]);
190- check_against_ffmpeg("ac3dep-repl-48000.eac3", "5.1(side)", &side, false);
191-}
192-
193-#[test]
194-fn side_pair_replacement_carries_the_dependent_signal() {
195- // The replaced pair is the dependent stereo source (880 Hz and 1320 Hz
196- // sines), not the core's: compare the side channels with ffmpeg's decode
197- // of that source on its own.
198- let repl = ec_testkit::fixture("audio/ac3dep-repl-48000.eac3");
199- let src20 = ec_testkit::fixture("audio/ac3dep-src-2.0.eac3");
200- let data = std::fs::read(&repl).expect("fixture");
201- let (ours, channels, _) = decode(&data);
202- assert_eq!(channels, 6, "replacement keeps the 5.1 channel count");
203- let source = reference(&src20, 2);
204- for (side, src) in [(4usize, 0usize), (5, 1)] {
205- let a: Vec<f32> = ours[side..].iter().step_by(channels).copied().collect();
206- let (corr, rms, _) = correlation(&a, &source[src]);
207- println!("side channel {side} vs dependent source ch{src}: {corr:.6} / {rms:.3e}");
208- assert!(corr >= MIN_CORR, "side ch{side}: correlation {corr:.6} against the dependent source");
209- }
210-}
211-
212-#[test]
213-fn dependent_without_an_independent_is_named_not_decoded() {
214- let stream = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3");
215- let data = std::fs::read(&stream).expect("fixture");
216- let packet = packets(&data)[0];
217- // The dependent frame alone, as a first substream.
218- let size = frame_size(packet).expect("frame size");
219- let dep = &packet[size..];
220- let mut decoder = Ac3Decoder::new();
221- assert!(matches!(
222- decoder.decode_frame(dep),
223- Err(Error::Unsupported { .. })
224- ));
225-}
226-
227-#[test]
228-fn truncated_dependent_substream_is_an_error_not_a_panic() {
229- let stream = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3");
230- let data = std::fs::read(&stream).expect("fixture");
231- let packet = packets(&data)[0];
232- for cut in [1, 2, 8, 100, 500] {
233- let mut decoder = Ac3Decoder::new();
234- assert!(decoder.decode_frame(&packet[..packet.len() - cut]).is_err());
235- }
236-}
237-
238-#[test]
239-fn a_second_independent_substream_in_the_packet_is_still_refused() {
240- let src20 = ec_testkit::fixture("audio/ac3dep-src-2.0.eac3");
241- let data = std::fs::read(&src20).expect("fixture");
242- let first = packets(&data)[0];
243- let mut two = first.to_vec();
244- two.extend_from_slice(first);
245- let mut decoder = Ac3Decoder::new();
246- assert!(matches!(
247- decoder.decode_frame(&two),
248- Err(Error::Unsupported { .. })
249- ));
250-}
crates/ec-ac3/tests/it/encode_matrix.rsdeleted+0 -397
@@ -1,397 +0,0 @@
1-//! Encoder coverage: frames our own decoder round-trips, and that ffmpeg
2-//! synthetic signals and on the real 16-bit fixtures, at every rate and
3-//! layout the encoder offers.
4-
5-use std::path::Path;
6-
7-use ec_ac3::{Ac3Decoder, Ac3Encoder, EncoderConfig};
8-
9-/// 440 Hz tone for 1 s, then 0.5 s of silence, interleaved across `channels`.
10-fn tone_then_silence(sample_rate: u32, channels: usize) -> Vec<f32> {
11- let tone_samples = sample_rate as usize;
12- let silence_samples = sample_rate as usize / 2;
13- let mut out = Vec::with_capacity((tone_samples + silence_samples) * channels);
14- for n in 0..tone_samples {
15- let t = n as f32 / sample_rate as f32;
16- let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
17- for _ in 0..channels {
18- out.push(v);
19- }
20- }
21- out.extend(std::iter::repeat_n(0.0f32, silence_samples * channels));
22- out
23-}
24-
25-fn correlation(a: &[f32], b: &[f32]) -> f64 {
26- let n = a.len().min(b.len());
27- if n == 0 {
28- return 0.0;
29- }
30- let (mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0);
31- for i in 0..n {
32- let (x, y) = (f64::from(a[i]), f64::from(b[i]));
33- sa += x;
34- sb += y;
35- saa += x * x;
36- sbb += y * y;
37- sab += x * y;
38- }
39- let n = n as f64;
40- let cov = sab / n - (sa / n) * (sb / n);
41- let va = (saa / n - (sa / n).powi(2)).max(0.0);
42- let vb = (sbb / n - (sb / n).powi(2)).max(0.0);
43- if va <= 0.0 || vb <= 0.0 {
44- return 1.0; // both flat (silence): trivially aligned
45- }
46- cov / (va.sqrt() * vb.sqrt())
47-}
48-
49-/// Encoder priming, `Ac3Encoder::encoder_delay`: the decoded stream starts
50-/// with this many samples of silence per channel.
51-const DELAY: usize = 256;
52-
53-/// Lag-searched correlation on one channel after the priming is dropped,
54-/// +/- 64 samples of slack: a bug that shifts the audio by a block shows up
55-/// as ~0 here, where an unbounded search on a periodic signal would hide it.
56-fn best_lag_correlation(a: &[f32], b: &[f32]) -> f64 {
57- let b = &b[DELAY.min(b.len())..];
58- let mut best = -1.0f64;
59- for lag in -64i32..=64 {
60- let (sa, sb): (&[f32], &[f32]) = if lag >= 0 {
61- (&a[lag as usize..], b)
62- } else {
63- (a, &b[(-lag) as usize..])
64- };
65- best = best.max(correlation(sa, sb));
66- }
67- best
68-}
69-
70-/// Deinterleave channel `ch` of `channels`.
71-fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec<f32> {
72- interleaved
73- .iter()
74- .skip(ch)
75- .step_by(channels)
76- .copied()
77- .collect()
78-}
79-
80-fn read_wav(path: &Path) -> (Vec<f32>, u32, usize) {
81- let out = ec_testkit::ffmpeg()
82- .args(["-v", "error", "-i"])
83- .arg(path)
84- .args(["-f", "f32le", "-"])
85- .output()
86- .expect("ffmpeg");
87- assert!(out.status.success(), "ffmpeg cannot read {}", path.display());
88- let samples = out
89- .stdout
90- .as_chunks::<4>().0.iter()
91- .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
92- .collect();
93- let probe = ffprobe(path, "channels,sample_rate");
94- let field = |key: &str| probe_field(&probe, key).and_then(|v| v.parse::<u32>().ok());
95- (samples, field("sample_rate").unwrap(), field("channels").unwrap() as usize)
96-}
97-
98-fn ffprobe(path: &Path, entries: &str) -> String {
99- let out = ec_testkit::ffprobe()
100- .args(["-v", "error", "-select_streams", "a:0", "-show_entries"])
101- .arg(format!("stream={entries}"))
102- .args(["-of", "default=noprint_wrappers=1"])
103- .arg(path)
104- .output()
105- .expect("ffprobe");
106- String::from_utf8_lossy(&out.stdout).into_owned()
107-}
108-
109-fn probe_field(text: &str, key: &str) -> Option<String> {
110- text.lines()
111- .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
112- .map(|v| v.trim().to_owned())
113-}
114-
115-/// ffmpeg's decode of an AC-3 file, asserting it voiced no complaint.
116-fn oracle_decode(path: &Path) -> Vec<f32> {
117- let out = ec_testkit::ffmpeg()
118- .args(["-v", "warning", "-i"])
119- .arg(path)
120- .args(["-f", "f32le", "-"])
121- .output()
122- .expect("ffmpeg");
123- let stderr = String::from_utf8_lossy(&out.stderr);
124- let complaint = stderr
125- .lines()
126- .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k)));
127- assert!(!complaint, "ffmpeg complained about {}:\n{stderr}", path.display());
128- out.stdout
129- .as_chunks::<4>().0.iter()
130- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
131- .collect()
132-}
133-
134-fn encode_with_stats(config: EncoderConfig, pcm: &[f32]) -> (Vec<u8>, ec_ac3::EncodeStats) {
135- let mut enc = Ac3Encoder::new(config).unwrap();
136- enc.push_pcm_f32(pcm).unwrap();
137- enc.finish();
138- let mut out = Vec::new();
139- loop {
140- match enc.next_packet() {
141- Ok(frame) => out.extend_from_slice(&frame),
142- Err(e) if e.is_eof() => break,
143- Err(e) => panic!("{e}"),
144- }
145- }
146- (out, enc.stats())
147-}
148-
149-fn encode(config: EncoderConfig, pcm: &[f32]) -> Vec<u8> {
150- encode_with_stats(config, pcm).0
151-}
152-
153-/// Worst per-channel lag-searched correlation between `want` and `got`.
154-fn worst_corr(want: &[f32], got: &[f32], channels: usize) -> f64 {
155- (0..channels)
156- .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch)))
157- .fold(1.0, f64::min)
158-}
159-
160-/// [`worst_corr`] over the full-bandwidth channels only: the LFE (family slot
161-/// 3 of six) is band-limited to 7 bins (~660 Hz at 48 kHz) by the standard,
162-/// so a fixture whose LFE carries full-band content can never correlate with
163-/// it; that channel is gated on our decoder agreeing with the oracle instead.
164-fn worst_fbw_corr(want: &[f32], got: &[f32], channels: usize) -> f64 {
165- (0..channels)
166- .filter(|&ch| !(channels == 6 && ch == 3))
167- .map(|ch| best_lag_correlation(&take_channel(want, channels, ch), &take_channel(got, channels, ch)))
168- .fold(1.0, f64::min)
169-}
170-
171-/// Deterministic white noise, `len` interleaved samples.
172-fn noise(len: usize, seed: &mut u64) -> Vec<f32> {
173- (0..len)
174- .map(|_| {
175- *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
176- ((*seed >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
177- })
178- .collect()
179-}
180-
181-fn decode_all(data: &[u8], channels: usize) -> Vec<f32> {
182- let mut decoder = Ac3Decoder::new();
183- let mut out = Vec::new();
184- let mut pos = 0;
185- while pos + 6 <= data.len() {
186- let size = ec_ac3::frame_size(&data[pos..]).unwrap();
187- assert!(pos + size <= data.len(), "frame overruns the stream");
188- let frame = decoder
189- .decode_frame(&data[pos..pos + size])
190- .unwrap_or_else(|e| panic!("frame at byte {pos}: {e}"));
191- assert_eq!(frame.samples, 1536);
192- assert_eq!(frame.channels(), channels);
193- out.extend(
194- frame.data[0]
195- .as_chunks::<4>().0.iter()
196- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
197- );
198- pos += size;
199- }
200- out
201-}
202-
203-#[test]
204-fn silence_and_tone_frames_decode_in_our_decoder() {
205- for &(sample_rate, channels) in &[(48_000u32, 1u16), (48_000, 2), (48_000, 6), (44_100, 2)] {
206- let config = EncoderConfig {
207- sample_rate,
208- channels,
209- bitrate_kbps: if channels >= 5 { 384 } else { 192 },
210- };
211- let pcm = tone_then_silence(sample_rate, channels as usize);
212- let data = encode(config, &pcm);
213- assert!(!data.is_empty(), "{sample_rate} Hz {channels}ch: no frames");
214- let decoded = decode_all(&data, channels as usize);
215- assert!(!decoded.is_empty());
216- let corr = worst_corr(&pcm, &decoded, channels as usize);
217- assert!(corr >= 0.95, "{sample_rate} Hz {channels}ch: corr {corr}");
218- }
219-}
220-
221-#[test]
222-fn oracle_accepts_our_frames() {
223- let config = EncoderConfig {
224- sample_rate: 48_000,
225- channels: 2,
226- bitrate_kbps: 192,
227- };
228- let pcm = tone_then_silence(48_000, 2);
229- let data = encode(config, &pcm);
230- let dir = std::env::temp_dir();
231- let path = dir.join("ec_ac3_encode_matrix_oracle.ac3");
232- std::fs::write(&path, &data).unwrap();
233-
234- let out = ec_testkit::ffmpeg()
235- .args(["-v", "warning", "-i"])
236- .arg(&path)
237- .args(["-f", "f32le", "-"])
238- .output()
239- .expect("ffmpeg");
240- let stderr = String::from_utf8_lossy(&out.stderr);
241- let complaint = stderr
242- .lines()
243- .any(|l| ["error", "invalid", "crc"].iter().any(|k| l.to_ascii_lowercase().contains(k)));
244- assert!(
245- !complaint,
246- "ffmpeg complained about our frames:\n{stderr}"
247- );
248-
249- let decoded: Vec<f32> = out
250- .stdout
251- .as_chunks::<4>().0.iter()
252- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
253- .collect();
254- for ch in 0..2 {
255- let want = take_channel(&pcm, 2, ch);
256- let got = take_channel(&decoded, 2, ch);
257- let corr = best_lag_correlation(&want, &got);
258- assert!(corr >= 0.95, "oracle channel {ch} corr {corr}");
259- }
260-
261- let _ = std::fs::remove_file(Path::new(&path));
262-}
263-
264-
265-/// The full fixture matrix: every wav16 fixture at its layout's bit rate,
266-/// through our decoder and the oracle, with ffprobe agreeing on what was
267-/// asked for. Prints the per-file numbers and the stereo strategy shares.
268-#[test]
269-fn real_fixtures_round_trip_through_our_decoder_and_the_oracle() {
270- let root = ec_testkit::root().join("audio");
271- let mut failures = Vec::new();
272- for layout in ["mono", "stereo", "5.1"] {
273- for rate in [48_000u32, 44_100] {
274- let path = root.join(format!("wav16-{layout}-{rate}.wav"));
275- let (pcm, sample_rate, channels) = read_wav(&path);
276- assert_eq!(sample_rate, rate);
277- let bitrate_kbps = match channels { 1 => 96, 2 => 192, _ => 448 };
278- let config = EncoderConfig { sample_rate, channels: channels as u16, bitrate_kbps };
279- let (data, stats) = encode_with_stats(config, &pcm);
280- let frame = ec_ac3::frame_size(&data).unwrap();
281- assert_eq!(data.len() % frame, 0, "{layout} {rate}: frames are not all {frame} bytes");
282-
283- let decoded = decode_all(&data, channels);
284- let ours = worst_fbw_corr(&pcm, &decoded, channels);
285- let out = std::env::temp_dir().join(format!("ec_ac3_encode_matrix_{layout}_{rate}.ac3"));
286- std::fs::write(&out, &data).unwrap();
287- let oracle_pcm = oracle_decode(&out);
288- let oracle = worst_fbw_corr(&pcm, &oracle_pcm, channels);
289- if channels == 6 {
290- let lfe = correlation(&take_channel(&decoded, 6, 3), &take_channel(&oracle_pcm, 6, 3));
291- assert!(lfe >= 0.99, "{layout} {rate}: LFE ours vs oracle corr {lfe}");
292- }
293- let probe = ffprobe(&out, "channels,channel_layout,sample_rate,bit_rate");
294- let _ = std::fs::remove_file(&out);
295-
296- let total = (stats.d15 + stats.d25 + stats.d45 + stats.reuse) as f64;
297- let share = |n: u64| n as f64 / total * 100.0;
298- eprintln!(
299- "{layout} {rate}: {} frames, ours {ours:.4} oracle {oracle:.4}, csnroffst mean {:.1}, fill {:.1}%, blksw {}, D15 {:.1}% D25 {:.1}% D45 {:.1}% REUSE {:.1}%",
300- stats.frames,
301- stats.csnroffst_sum as f64 / stats.frames as f64,
302- stats.bits_used as f64 / stats.bits_budget as f64 * 100.0,
303- stats.blksw_blocks,
304- share(stats.d15), share(stats.d25), share(stats.d45), share(stats.reuse),
305- );
306- if ours < 0.99 || oracle < 0.99 {
307- failures.push(format!("{layout} {rate}: ours {ours:.4} oracle {oracle:.4}"));
308- }
309- assert!(stats.bits_used * 10 > stats.bits_budget * 9, "{layout} {rate}: rate loop left bits unused: {stats:?}");
310- let expect_layout = match channels { 1 => "mono", 2 => "stereo", _ => "5.1" };
311- assert_eq!(probe_field(&probe, "channels").as_deref(), Some(channels.to_string().as_str()), "{probe}");
312- assert!(probe_field(&probe, "channel_layout").is_some_and(|l| l.starts_with(expect_layout)), "{probe}");
313- assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some(rate.to_string().as_str()), "{probe}");
314- assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some((bitrate_kbps * 1000).to_string().as_str()), "{probe}");
315- }
316- }
317- assert!(failures.is_empty(), "corr < 0.99:\n{}", failures.join("\n"));
318-}
319-
320-/// A train of sharp attacks (decaying 2 kHz bursts, 25 per second) over a
321-/// quiet noise floor: every attack is a block switch, and the stream still
322-/// round-trips through both decoders.
323-#[test]
324-fn click_train_switches_blocks_and_still_round_trips() {
325- let channels = 2;
326- let mut pcm = noise(48_000 * channels, &mut 11u64);
327- for v in &mut pcm {
328- *v *= 0.01;
329- }
330- for n in (500..48_000).step_by(1900) {
331- for i in 0..200 {
332- 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();
333- for ch in 0..channels {
334- pcm[(n + i) * channels + ch] += v;
335- }
336- }
337- }
338- let config = EncoderConfig { sample_rate: 48_000, channels: 2, bitrate_kbps: 192 };
339- let (data, stats) = encode_with_stats(config, &pcm);
340- assert!(stats.blksw_blocks >= 20, "{stats:?}");
341- let corr = worst_corr(&pcm, &decode_all(&data, channels), channels);
342- eprintln!("click train: ours {corr:.4}, {stats:?}");
343- assert!(corr >= 0.95, "click train corr {corr}");
344- let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3");
345- std::fs::write(&out, &data).unwrap();
346- let corr = worst_corr(&pcm, &oracle_decode(&out), channels);
347- let _ = std::fs::remove_file(&out);
348- eprintln!("click train: oracle {corr:.4}");
349- assert!(corr >= 0.95, "click train oracle corr {corr}");
350-}
351-
352-#[test]
353-fn tone_at_32khz_round_trips() {
354- let rate = 32_000;
355- let pcm: Vec<f32> = (0..rate as usize * 2)
356- .flat_map(|n| {
357- let t = n as f32 / rate as f32;
358- let v = 0.5 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
359- [v, 0.5 * v]
360- })
361- .collect();
362- let config = EncoderConfig { sample_rate: rate, channels: 2, bitrate_kbps: 96 };
363- let data = encode(config, &pcm);
364- let corr = worst_corr(&pcm, &decode_all(&data, 2), 2);
365- assert!(corr >= 0.99, "32 kHz ours corr {corr}");
366- let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3");
367- std::fs::write(&out, &data).unwrap();
368- let corr = worst_corr(&pcm, &oracle_decode(&out), 2);
369- let probe = ffprobe(&out, "sample_rate,bit_rate");
370- let _ = std::fs::remove_file(&out);
371- assert!(corr >= 0.99, "32 kHz oracle corr {corr}");
372- assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}");
373- assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}");
374-}
375-
376-/// 200 random (rate, channels, bit rate) configurations, two frames of
377-/// noise each: nothing panics and our decoder takes every frame.
378-#[test]
379-fn random_configs_never_panic_and_always_decode() {
380- let (mut seed, mut noise_seed) = (99u64, 7u64);
381- let mut next = |n: u64| {
382- seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
383- (seed >> 33) % n
384- };
385- for _ in 0..200 {
386- let sample_rate = ec_ac3::tables::SAMPLE_RATE[next(3) as usize];
387- let channels = next(6) as u16 + 1;
388- let bitrate_kbps = ec_ac3::tables::BIT_RATE_KBPS[next(ec_ac3::tables::BIT_RATE_KBPS.len() as u64) as usize];
389- let config = EncoderConfig { sample_rate, channels, bitrate_kbps };
390- let pcm = noise(1536 * 2 * channels as usize, &mut noise_seed);
391- let data = encode(config, &pcm);
392- let decoded = decode_all(&data, channels as usize);
393- assert!(decoded.len() >= pcm.len() + 256, "{config:?}: {} of {} samples", decoded.len(), pcm.len());
394- }
395-}
396-
397-
crates/ec-ac3/tests/it/main.rsmodified+0 -3
@@ -1,9 +1,6 @@
11 //! One integration-test binary for ec-ac3; each module is one former `tests/*.rs` file.
22 #![forbid(unsafe_code)]
33
4-mod decode_matrix;
5-mod dependent;
6-mod encode_matrix;
74 mod ffmpeg_parity;
85 mod packet_walk;
96 mod real_library;