forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

dependent.rs317 lines, 11.5 KiBHistoryRawDownload
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//! The fixtures come from `scripts/gen-ac3dep-fixtures.sh`. Missing fixtures or
6//! a missing ffmpeg skip the comparison, as in `decode_matrix.rs`, unless
7//! `EC_REQUIRE_FIXTURES=1`, which makes an absent fixture a failure.
8
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use ec_ac3::{Ac3Decoder, Error, Options, eac3, frame_size};
13use ec_core::{ChannelLayout, ChannelPosition};
14
15/// Per-channel correlation floor and RMS ceiling, as in `decode_matrix.rs`.
16const MIN_CORR: f64 = 0.999;
17const MAX_RMS: f64 = 1e-3;
18
19fn fixtures() -> PathBuf {
20 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
21}
22
23/// Whether every path is present. A missing one skips the test, or fails it
24/// under `EC_REQUIRE_FIXTURES=1`.
25fn present(name: &str, paths: &[PathBuf]) -> bool {
26 let missing: Vec<_> = paths.iter().filter(|p| !p.exists()).collect();
27 if missing.is_empty() {
28 return true;
29 }
30 assert!(
31 std::env::var("EC_REQUIRE_FIXTURES").as_deref() != Ok("1"),
32 "{name}: fixture missing: {missing:?}"
33 );
34 eprintln!("skipping {name}: fixture missing: {missing:?}");
35 false
36}
37
38/// Whether ffmpeg and ffprobe run. Missing tools skip, or fail under
39/// `EC_REQUIRE_FIXTURES=1`.
40fn have_ffmpeg(name: &str) -> bool {
41 let ok = |tool: &str| {
42 Command::new(tool)
43 .arg("-version")
44 .output()
45 .is_ok_and(|o| o.status.success())
46 };
47 if ok("ffmpeg") && ok("ffprobe") {
48 return true;
49 }
50 assert!(
51 std::env::var("EC_REQUIRE_FIXTURES").as_deref() != Ok("1"),
52 "{name}: ffmpeg and ffprobe are required"
53 );
54 eprintln!("skipping {name}: ffmpeg or ffprobe missing");
55 false
56}
57
58/// ffprobe's `channel_layout` name for the first audio stream of `path`.
59fn ffprobe_layout(path: &Path) -> String {
60 let out = Command::new("ffprobe")
61 .args(["-v", "error", "-f", "eac3", "-select_streams", "a:0"])
62 .args(["-show_entries", "stream=channel_layout", "-of", "csv=p=0"])
63 .arg(path)
64 .output()
65 .expect("ffprobe");
66 String::from_utf8_lossy(&out.stdout).trim().to_owned()
67}
68
69/// ffmpeg's decode of `path` as interleaved `f32`, in ffmpeg's channel order.
70fn reference(path: &Path, channels: usize) -> Vec<Vec<f32>> {
71 let out = Command::new("ffmpeg")
72 .args(["-v", "error", "-f", "eac3", "-i"])
73 .arg(path)
74 .args(["-f", "f32le", "-"])
75 .output()
76 .expect("ffmpeg");
77 let all: Vec<f32> = out
78 .stdout
79 .as_chunks::<4>()
80 .0
81 .iter()
82 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
83 .collect();
84 (0..channels)
85 .map(|ch| all[ch..].iter().step_by(channels).copied().collect())
86 .collect()
87}
88
89/// Split a raw E-AC-3 stream into packets: an independent syncframe and the
90/// dependent substreams that follow it.
91fn packets(data: &[u8]) -> Vec<&[u8]> {
92 let mut starts = Vec::new();
93 let mut pos = 0;
94 while pos + 6 <= data.len() {
95 let Ok(size) = frame_size(&data[pos..]) else {
96 break;
97 };
98 let independent = eac3::bsi::parse(&data[pos + 2..])
99 .is_ok_and(|h| h.strmtyp == eac3::StreamType::Independent);
100 if independent {
101 starts.push(pos);
102 }
103 pos += size;
104 }
105 starts
106 .iter()
107 .enumerate()
108 .map(|(i, &s)| &data[s..starts.get(i + 1).copied().unwrap_or(data.len())])
109 .collect()
110}
111
112/// Our decode of every packet: interleaved samples, channels and the layout.
113fn decode(data: &[u8]) -> (Vec<f32>, usize, ChannelLayout) {
114 let mut decoder = Ac3Decoder::with_options(Options {
115 dither: false,
116 ..Options::default()
117 });
118 let (mut out, mut channels, mut layout) = (Vec::new(), 0, ChannelLayout::Mono);
119 for packet in packets(data) {
120 let frame = decoder
121 .decode_frame(packet)
122 .unwrap_or_else(|e| panic!("packet decode: {e}"));
123 channels = frame.channels();
124 layout = frame.layout.clone();
125 out.extend(
126 frame.data[0]
127 .as_chunks::<4>()
128 .0
129 .iter()
130 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])),
131 );
132 }
133 (out, channels, layout)
134}
135
136fn correlation(a: &[f32], b: &[f32]) -> (f64, f64, f64) {
137 let n = a.len().min(b.len());
138 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);
139 let mut max_abs = 0.0f64;
140 for i in 0..n {
141 let (x, y) = (f64::from(a[i]), f64::from(b[i]));
142 sa += x;
143 sb += y;
144 saa += x * x;
145 sbb += y * y;
146 sab += x * y;
147 sd += (x - y) * (x - y);
148 max_abs = max_abs.max((x - y).abs());
149 }
150 let n = n as f64;
151 let cov = sab / n - (sa / n) * (sb / n);
152 let va = saa / n - (sa / n).powi(2);
153 let vb = sbb / n - (sb / n).powi(2);
154 let corr = if va <= 0.0 || vb <= 0.0 {
155 1.0
156 } else {
157 cov / (va * vb).sqrt()
158 };
159 (corr, (sd / n).sqrt(), max_abs)
160}
161
162/// The per-channel comparison of our decode of `name` against ffmpeg's decode of
163/// the same file. The layout name is ffprobe's, so a wrong channel order fails
164/// here even when every channel holds the right signal.
165///
166/// With `side_from_core`, channels 6 and 7 (the core's Ls and Rs in a 7.1 layout)
167/// are compared against ffmpeg's decode of the 5.1 source instead. ffmpeg 8.1
168/// does not place them correctly once a dependent substream is appended to a
169/// core with a side pair: its side-left slot is silent and its side-right slot
170/// repeats the dependent's left channel. The core decode is ffmpeg's own
171/// unchanged 5.1 path, so it is the reference that ffmpeg itself gets right.
172fn check_against_ffmpeg(name: &str, ffprobe_name: &str, layout: &ChannelLayout, side_from_core: bool) {
173 let stream = fixtures().join(name);
174 let core = fixtures().join("ac3dep-src-5.1.eac3");
175 let mut paths = vec![stream.clone()];
176 if side_from_core {
177 paths.push(core.clone());
178 }
179 if !present(name, &paths) || !have_ffmpeg(name) {
180 return;
181 }
182 assert_eq!(ffprobe_layout(&stream), ffprobe_name, "{name}: ffprobe channel_layout");
183 let data = std::fs::read(&stream).expect("fixture");
184 let (ours, channels, ours_layout) = decode(&data);
185 assert_eq!(&ours_layout, layout, "{name}: layout");
186 assert_eq!(channels, layout.channel_count(), "{name}: channels");
187
188 let theirs = reference(&stream, channels);
189 let core_side = side_from_core.then(|| reference(&core, 6));
190 let frames = ours.len() / channels;
191 assert_eq!(frames, theirs[0].len(), "{name}: frame count vs ffmpeg");
192
193 println!("{name} ({ffprobe_name}): per-channel correlation / RMS delta / max abs error");
194 for (ch, from_ffmpeg) in theirs.iter().enumerate() {
195 let (expect, note) = match (&core_side, ch) {
196 (Some(c), 6) => (&c[4], " (core Ls, from the 5.1 decode)"),
197 (Some(c), 7) => (&c[5], " (core Rs, from the 5.1 decode)"),
198 _ => (from_ffmpeg, ""),
199 };
200 let a: Vec<f32> = ours[ch..].iter().step_by(channels).copied().collect();
201 let (corr, rms, max_abs) = correlation(&a, expect);
202 println!(" ch{ch}: {corr:.6} / {rms:.3e} / {max_abs:.3e}{note}");
203 assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}");
204 assert!(rms <= MAX_RMS, "{name} ch{ch}: RMS delta {rms:.8}");
205 }
206}
207
208#[test]
209fn seven_one_matches_ffmpeg() {
210 // Lrs/Rrs (BL/BR) are added to the core's side pair: 8 channels in 7.1 order.
211 check_against_ffmpeg("ac3dep-7.1-48000.eac3", "7.1", &ChannelLayout::Surround7_1, true);
212}
213
214#[test]
215fn seven_one_wide_matches_ffmpeg() {
216 // Lc/Rc (FLC/FRC) are added; canonical order puts them before the side pair.
217 let wide = ChannelLayout::Custom(vec![
218 ChannelPosition::FrontLeft,
219 ChannelPosition::FrontRight,
220 ChannelPosition::FrontCenter,
221 ChannelPosition::Lfe,
222 ChannelPosition::FrontLeftOfCenter,
223 ChannelPosition::FrontRightOfCenter,
224 ChannelPosition::SideLeft,
225 ChannelPosition::SideRight,
226 ]);
227 check_against_ffmpeg("ac3dep-7.1wide-48000.eac3", "7.1(wide-side)", &wide, true);
228}
229
230#[test]
231fn side_pair_replacement_matches_ffmpeg() {
232 // Ls/Rs replace the core's side pair: 6 channels, not 8.
233 let side = ChannelLayout::Custom(vec![
234 ChannelPosition::FrontLeft,
235 ChannelPosition::FrontRight,
236 ChannelPosition::FrontCenter,
237 ChannelPosition::Lfe,
238 ChannelPosition::SideLeft,
239 ChannelPosition::SideRight,
240 ]);
241 check_against_ffmpeg("ac3dep-repl-48000.eac3", "5.1(side)", &side, false);
242}
243
244#[test]
245fn side_pair_replacement_carries_the_dependent_signal() {
246 // The replaced pair is the dependent stereo source (880 Hz and 1320 Hz
247 // sines), not the core's: compare the side channels with ffmpeg's decode
248 // of that source on its own.
249 let dir = fixtures();
250 let repl = dir.join("ac3dep-repl-48000.eac3");
251 let src20 = dir.join("ac3dep-src-2.0.eac3");
252 if !present("ac3dep-repl-48000.eac3", &[repl.clone(), src20.clone()]) || !have_ffmpeg("replacement signal") {
253 return;
254 }
255 let data = std::fs::read(&repl).expect("fixture");
256 let (ours, channels, _) = decode(&data);
257 assert_eq!(channels, 6, "replacement keeps the 5.1 channel count");
258 let source = reference(&src20, 2);
259 for (side, src) in [(4usize, 0usize), (5, 1)] {
260 let a: Vec<f32> = ours[side..].iter().step_by(channels).copied().collect();
261 let (corr, rms, _) = correlation(&a, &source[src]);
262 println!("side channel {side} vs dependent source ch{src}: {corr:.6} / {rms:.3e}");
263 assert!(corr >= MIN_CORR, "side ch{side}: correlation {corr:.6} against the dependent source");
264 }
265}
266
267#[test]
268fn dependent_without_an_independent_is_named_not_decoded() {
269 let dir = fixtures();
270 let stream = dir.join("ac3dep-7.1-48000.eac3");
271 if !present("ac3dep-7.1-48000.eac3", std::slice::from_ref(&stream)) {
272 return;
273 }
274 let data = std::fs::read(&stream).expect("fixture");
275 let packet = packets(&data)[0];
276 // The dependent frame alone, as a first substream.
277 let size = frame_size(packet).expect("frame size");
278 let dep = &packet[size..];
279 let mut decoder = Ac3Decoder::new();
280 assert!(matches!(
281 decoder.decode_frame(dep),
282 Err(Error::Unsupported { .. })
283 ));
284}
285
286#[test]
287fn truncated_dependent_substream_is_an_error_not_a_panic() {
288 let dir = fixtures();
289 let stream = dir.join("ac3dep-7.1-48000.eac3");
290 if !present("ac3dep-7.1-48000.eac3", std::slice::from_ref(&stream)) {
291 return;
292 }
293 let data = std::fs::read(&stream).expect("fixture");
294 let packet = packets(&data)[0];
295 for cut in [1, 2, 8, 100, 500] {
296 let mut decoder = Ac3Decoder::new();
297 assert!(decoder.decode_frame(&packet[..packet.len() - cut]).is_err());
298 }
299}
300
301#[test]
302fn a_second_independent_substream_in_the_packet_is_still_refused() {
303 let dir = fixtures();
304 let src20 = dir.join("ac3dep-src-2.0.eac3");
305 if !present("ac3dep-src-2.0.eac3", std::slice::from_ref(&src20)) {
306 return;
307 }
308 let data = std::fs::read(&src20).expect("fixture");
309 let first = packets(&data)[0];
310 let mut two = first.to_vec();
311 two.extend_from_slice(first);
312 let mut decoder = Ac3Decoder::new();
313 assert!(matches!(
314 decoder.decode_frame(&two),
315 Err(Error::Unsupported { .. })
316 ));
317}