forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

ffmpeg_parity.rs184 lines, 6.5 KiBHistoryRawDownload
1//! Per-channel parity with ffmpeg on dense, independent channels.
2//!
3//! The fixtures are generated here with ffmpeg, never committed: six
4//! independent pink-noise channels (one per 5.1 speaker, or two for 2.0) are
5//! encoded by ffmpeg's AC-3 encoder at a given bitrate, then decoded both by
6//! ffmpeg and by `ec-ac3` with default options. Noise at these bitrates leaves
7//! many zero-bit mantissas, so this exercises the dither for them as well as
8//! the coupled and rematrixed paths.
9//!
10//! Gate: per-channel correlation >= 0.999 for every layout and bitrate below,
11//! with the LFE (which carries only rounding-level content here) also held to
12//! the same correlation since it is not silent.
13//!
14//! Needs ffmpeg on PATH; without it the test skips loudly.
15
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19use ec_ac3::{Ac3Decoder, Options};
20use crate::common::have_ffmpeg;
21
22const MIN_CORR: f64 = 0.999;
23/// Seconds of noise per fixture. Long enough for a few hundred frames.
24const SECONDS: u32 = 10;
25
26/// Encodes `channels` independent pink-noise sources as one AC-3 stream at
27/// `bitrate` (e.g. "448k"), and returns the path of the `.ac3` file.
28fn encode(work: &Path, name: &str, channels: usize, bitrate: &str) -> PathBuf {
29 let out = work.join(format!("{name}.ac3"));
30 let mut args: Vec<String> = vec!["-nostdin".into(), "-v".into(), "error".into(), "-y".into()];
31 for seed in 1..=channels {
32 args.extend([
33 "-f".into(),
34 "lavfi".into(),
35 "-i".into(),
36 format!("anoisesrc=d={SECONDS}:c=pink:r=48000:a=0.2:seed={seed}"),
37 ]);
38 }
39 let graph = if channels == 6 {
40 let inputs: String = (0..6).map(|i| format!("[{i}:a]")).collect();
41 format!(
42 "{inputs}amerge=inputs=6,pan=5.1(side)|c0=c0|c1=c1|c2=c2|c3=c3|c4=c4|c5=c5[a]"
43 )
44 } else {
45 "[0:a][1:a]amerge=inputs=2,pan=stereo|c0=c0|c1=c1[a]".to_string()
46 };
47 args.extend([
48 "-filter_complex".into(),
49 graph,
50 "-map".into(),
51 "[a]".into(),
52 "-ar".into(),
53 "48000".into(),
54 "-c:a".into(),
55 "ac3".into(),
56 "-b:a".into(),
57 bitrate.into(),
58 "-f".into(),
59 "ac3".into(),
60 ]);
61 args.push(out.display().to_string());
62 let status = Command::new("ffmpeg").args(&args).status().expect("ffmpeg");
63 assert!(status.success(), "ffmpeg encode of {name} failed");
64 out
65}
66
67/// ffmpeg's decode of the stream as interleaved `f32`.
68fn reference(path: &Path, channels: usize) -> Vec<f32> {
69 let out = Command::new("ffmpeg")
70 .args(["-v", "error", "-nostdin", "-i"])
71 .arg(path)
72 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-ac"])
73 .arg(channels.to_string())
74 .arg("-")
75 .output()
76 .expect("ffmpeg");
77 assert!(out.status.success(), "ffmpeg decode failed");
78 out.stdout
79 .as_chunks::<4>()
80 .0
81 .iter()
82 .map(|c| f32::from_le_bytes(*c))
83 .collect()
84}
85
86/// Our decode with default options, and the channel count.
87fn decode(path: &Path) -> (Vec<f32>, usize) {
88 let data = std::fs::read(path).expect("encoded stream");
89 let mut decoder = Ac3Decoder::with_options(Options::default());
90 let (mut out, mut channels, mut pos) = (Vec::new(), 0, 0usize);
91 while pos + 6 <= data.len() {
92 if data[pos] != 0x0B || data[pos + 1] != 0x77 {
93 pos += 1;
94 continue;
95 }
96 let Ok(size) = ec_ac3::frame_size(&data[pos..]) else {
97 break;
98 };
99 if pos + size > data.len() {
100 break;
101 }
102 let frame = decoder
103 .decode_frame(&data[pos..pos + size])
104 .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
105 channels = frame.channels();
106 out.extend(
107 frame
108 .data[0]
109 .as_chunks::<4>()
110 .0
111 .iter()
112 .map(|c| f32::from_le_bytes(*c)),
113 );
114 pos += size;
115 }
116 (out, channels)
117}
118
119/// Pearson correlation of one channel of two interleaved streams.
120fn correlation(ours: &[f32], theirs: &[f32], channels: usize, ch: usize) -> f64 {
121 let a: Vec<f64> = ours[ch..].iter().step_by(channels).map(|v| f64::from(*v)).collect();
122 let b: Vec<f64> = theirs[ch..].iter().step_by(channels).map(|v| f64::from(*v)).collect();
123 let n = a.len().min(b.len()).max(1) as f64;
124 let (ma, mb) = (a.iter().sum::<f64>() / n, b.iter().sum::<f64>() / n);
125 let (mut cov, mut va, mut vb) = (0.0, 0.0, 0.0);
126 for (x, y) in a.iter().zip(&b) {
127 cov += (x - ma) * (y - mb);
128 va += (x - ma) * (x - ma);
129 vb += (y - mb) * (y - mb);
130 }
131 if va <= 0.0 || vb <= 0.0 {
132 1.0
133 } else {
134 cov / (va * vb).sqrt()
135 }
136}
137
138fn check(name: &str, channels: usize, bitrate: &str) {
139 if !have_ffmpeg() {
140 eprintln!("skip {name}: ffmpeg not on PATH");
141 return;
142 }
143 let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("ffmpeg-parity");
144 std::fs::create_dir_all(&work).expect("work dir");
145 let stream = encode(&work, name, channels, bitrate);
146 let (ours, decoded_channels) = decode(&stream);
147 let theirs = reference(&stream, channels);
148 assert_eq!(decoded_channels, channels, "{name}: channel count");
149 assert_eq!(ours.len(), theirs.len(), "{name}: sample count vs ffmpeg");
150
151 let mut worst = 1.0f64;
152 let mut per_channel = Vec::new();
153 for ch in 0..channels {
154 let corr = correlation(&ours, &theirs, channels, ch);
155 per_channel.push(format!("{corr:.6}"));
156 worst = worst.min(corr);
157 }
158 eprintln!("PARITY {name} {channels}ch {bitrate}: min corr {worst:.6} [{}]", per_channel.join(" "));
159 assert!(
160 worst >= MIN_CORR,
161 "{name}: min per-channel correlation {worst:.6} < {MIN_CORR} [{}]",
162 per_channel.join(" ")
163 );
164}
165
166/// (old test name, fixture name, channels, bitrate). Every case runs; all
167/// failing names are reported together.
168const CASES: &[(&str, &str, usize, &str)] = &[
169 ("ffmpeg_parity_5_1_448k_pink_noise", "pink-5.1-448k", 6, "448k"),
170 ("ffmpeg_parity_2_0_192k_pink_noise", "pink-2.0-192k", 2, "192k"),
171 ("ffmpeg_parity_5_1_640k_pink_noise", "pink-5.1-640k", 6, "640k"),
172];
173
174#[test]
175fn ffmpeg_parity_pink_noise() {
176 let mut failures = Vec::new();
177 for &(old, name, channels, bitrate) in CASES {
178 let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check(name, channels, bitrate)));
179 if ran.is_err() {
180 failures.push(old);
181 }
182 }
183 assert!(failures.is_empty(), "failed cases: {failures:?}");
184}