forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_truehd.rs214 lines, 6.9 KiBHistoryRawDownload
1//! Dolby TrueHD in Matroska, decoded through `ec-truehd`.
2//!
3//! The fixtures are made here, at test time, by ffmpeg's own TrueHD encoder: a
4//! stereo and a 5.1 sine in a `.mka`. The stereo track is held to ffmpeg's
5//! decode sample for sample, since TrueHD is lossless and both sides land on
6//! the same 24-bit values. The 5.1 track reaches the timeline as the stereo
7//! pair every multichannel source does, so it is held to ffmpeg's own `-ac 2`
8//! fold by correlation instead (the fold's coefficients are edith's, not
9//! ffmpeg's, so the samples cannot be equal).
10//!
11//! Skipped, loudly, where ffmpeg is not installed.
12
13use std::path::Path;
14use std::process::Command;
15
16use engine::audio::AudioSession;
17use engine::scratch::Scratch;
18
19/// Whether `ffmpeg` runs here. Without it the tests are skipped, loudly.
20fn have_ffmpeg() -> bool {
21 Command::new("ffmpeg")
22 .arg("-version")
23 .output()
24 .is_ok_and(|o| o.status.success())
25}
26
27/// Encodes a two-second sine into a TrueHD Matroska file with `channels` channels.
28/// The guard is returned, not its path: dropping it removes the fixture.
29fn make_truehd(name: &str, channels: &str) -> Scratch {
30 let mka = Scratch::file(name, "mka");
31 let out = Command::new("ffmpeg")
32 .args(["-v", "error", "-y"])
33 .args(["-f", "lavfi", "-i", "sine=frequency=440:duration=2"])
34 .args(["-ac", channels, "-c:a", "truehd", "-strict", "-2"])
35 .arg(&*mka)
36 .output()
37 .expect("ffmpeg runs");
38 assert!(
39 out.status.success(),
40 "ffmpeg: {}",
41 String::from_utf8_lossy(&out.stderr)
42 );
43 mka
44}
45
46/// ffmpeg's decode of `path`'s first audio track as f32, `-ac` channels wide
47/// (0 keeps the file's own width), in the interleaved order it writes.
48fn ffmpeg_f32(path: &Path, channels: Option<&str>) -> Vec<f32> {
49 let mut cmd = Command::new("ffmpeg");
50 cmd.args(["-v", "error", "-i"])
51 .arg(path)
52 .args(["-map", "0:a:0"]);
53 if let Some(channels) = channels {
54 cmd.args(["-ac", channels]);
55 }
56 let out = cmd
57 .args(["-f", "f32le", "-"])
58 .output()
59 .expect("ffmpeg runs");
60 assert!(
61 out.status.success(),
62 "ffmpeg: {}",
63 String::from_utf8_lossy(&out.stderr)
64 );
65 out.stdout
66 .as_chunks::<4>().0.iter()
67 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
68 .collect()
69}
70
71/// ffmpeg's decode of `path`'s first audio track as its own 32-bit integers, at
72/// the width the file carries.
73fn ffmpeg_s32(path: &Path) -> Vec<i32> {
74 let out = Command::new("ffmpeg")
75 .args(["-v", "error", "-i"])
76 .arg(path)
77 .args(["-map", "0:a:0", "-f", "s32le", "-"])
78 .output()
79 .expect("ffmpeg runs");
80 assert!(
81 out.status.success(),
82 "ffmpeg: {}",
83 String::from_utf8_lossy(&out.stderr)
84 );
85 out.stdout
86 .as_chunks::<4>().0.iter()
87 .map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
88 .collect()
89}
90
91/// The interleaved samples of `path`'s first audio track, with its metadata.
92fn decode(path: &Path) -> (engine::audio::AudioMeta, Vec<f32>) {
93 let (meta, rx) = AudioSession::open(path)
94 .expect("opens")
95 .expect("has an audio track");
96 let mut samples = Vec::new();
97 for chunk in rx {
98 samples.extend_from_slice(&chunk.samples);
99 }
100 (meta, samples)
101}
102
103/// One channel out of an interleaved buffer.
104fn channel(interleaved: &[f32], channels: usize, index: usize) -> Vec<f32> {
105 interleaved
106 .iter()
107 .skip(index)
108 .step_by(channels)
109 .copied()
110 .collect()
111}
112
113/// Normalised correlation of two runs over their common length: 1.0 when they
114/// are the same waveform at the same offset, whatever their level.
115fn correlation(a: &[f32], b: &[f32]) -> f64 {
116 let n = a.len().min(b.len());
117 let (mut dot, mut aa, mut bb) = (0f64, 0f64, 0f64);
118 for (&x, &y) in a[..n].iter().zip(&b[..n]) {
119 dot += f64::from(x) * f64::from(y);
120 aa += f64::from(x) * f64::from(x);
121 bb += f64::from(y) * f64::from(y);
122 }
123 dot / (aa.sqrt() * bb.sqrt()).max(f64::MIN_POSITIVE)
124}
125
126#[test]
127fn stereo_truehd_in_matroska_opens_at_its_rate_and_channels() {
128 if !have_ffmpeg() {
129 eprintln!("skipped: no ffmpeg to encode the TrueHD fixture with");
130 return;
131 }
132 let mka = make_truehd("ve_truehd_stereo", "2");
133 let (meta, samples) = decode(&mka);
134 assert_eq!((meta.sample_rate, meta.channels), (44_100, 2));
135 assert!(!samples.is_empty(), "no sound out of the TrueHD track");
136}
137
138#[test]
139fn surround_truehd_in_matroska_reaches_the_timeline_as_a_pair() {
140 if !have_ffmpeg() {
141 eprintln!("skipped: no ffmpeg to encode the TrueHD fixture with");
142 return;
143 }
144 let mka = make_truehd("ve_truehd_51", "6");
145 let (meta, samples) = decode(&mka);
146 // The 5.1 presentation is folded to stereo at the decoder's door, as every
147 // multichannel source is; the rate is the stream's own.
148 assert_eq!((meta.sample_rate, meta.channels), (44_100, 2));
149 assert!(!samples.is_empty(), "no sound out of the 5.1 TrueHD track");
150}
151
152#[test]
153fn stereo_truehd_matches_ffmpeg_sample_for_sample() {
154 if !have_ffmpeg() {
155 eprintln!("skipped: no ffmpeg to encode and decode the reference with");
156 return;
157 }
158 let mka = make_truehd("ve_truehd_exact", "2");
159 let (meta, ours) = decode(&mka);
160 assert_eq!((meta.sample_rate, meta.channels), (44_100, 2));
161
162 let theirs = ffmpeg_s32(&mka);
163 assert_eq!(
164 ours.len(),
165 theirs.len(),
166 "{} samples out, {} from ffmpeg",
167 ours.len(),
168 theirs.len()
169 );
170 // edith's f32 is the 24-bit sample over 2^31: exact in f32, so the
171 // comparison is exact too, not a tolerance.
172 let mismatches = ours
173 .iter()
174 .zip(&theirs)
175 .filter(|(o, t)| f64::from(**o) * 2_147_483_648.0 != f64::from(**t))
176 .count();
177 assert_eq!(
178 mismatches,
179 0,
180 "{mismatches} of {} samples differ from ffmpeg",
181 ours.len()
182 );
183 assert!(
184 ours.iter().any(|s| s.abs() > 1e-3),
185 "the reference decode is silent; the fixture is wrong"
186 );
187}
188
189#[test]
190fn surround_truehd_folds_to_ffmpegs_stereo_by_correlation() {
191 if !have_ffmpeg() {
192 eprintln!("skipped: no ffmpeg to encode and decode the reference with");
193 return;
194 }
195 let mka = make_truehd("ve_truehd_51_fold", "6");
196 let (meta, ours) = decode(&mka);
197 assert_eq!(meta.channels, 2);
198
199 let theirs = ffmpeg_f32(&mka, Some("2"));
200 for index in 0..2 {
201 let level = ours
202 .iter()
203 .skip(index)
204 .step_by(2)
205 .map(|s| s.abs())
206 .fold(0f32, f32::max);
207 assert!(level > 1e-3, "timeline channel {index} is silent");
208 let score = correlation(&channel(&ours, 2, index), &channel(&theirs, 2, index));
209 assert!(
210 score > 0.99,
211 "timeline channel {index} correlates {score:.4} with ffmpeg's -ac 2 decode"
212 );
213 }
214}