forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

opus_file_export.rs299 lines, 11.8 KiBHistoryRawDownload
1//! The standalone `.opus` export ([`Format::Opus`], [`engine::opus_write`]), read back with
2//! ffprobe and ffmpeg: codec, 48 kHz, channels, a duration exact to the millisecond, a clean
3//! decode, and the decode measured against the source (SNR); the 5.1 mapping-family-1 layout,
4//! a ranged export, and chapters as `CHAPTERxxx` comments. The -16 LUFS `podcast_opus` preset
5//! is measured in `export_presets.rs`. Without ffmpeg the tests say so and pass.
6//!
7//! ```text
8//! cargo test -p engine --release --test opus_file_export -- --nocapture
9//! ```
10
11use std::path::Path;
12use std::process::Command;
13use std::time::{Duration, Instant};
14
15use engine::export::{ExportSettings, Format};
16use engine::scratch::Scratch;
17use engine::PlaybackSession;
18
19const RATE: u32 = 48_000;
20
21fn have_ffmpeg() -> bool {
22 Command::new("ffmpeg").arg("-version").output().is_ok_and(|o| o.status.success())
23 && Command::new("ffprobe").arg("-version").output().is_ok_and(|o| o.status.success())
24}
25
26/// Speech-like stereo: a 140 Hz voice with harmonics under a 4 Hz syllable envelope, a
27/// different pitch on the right, at about -12 dBFS. `secs` long at `rate`.
28fn speechy(rate: u32, secs: f64) -> Vec<f32> {
29 let frames = (secs * f64::from(rate)) as usize;
30 let mut out = Vec::with_capacity(frames * 2);
31 for i in 0..frames {
32 let t = i as f64 / f64::from(rate);
33 let env = 0.55 + 0.45 * (t * 4.0 * std::f64::consts::TAU).sin();
34 let voice = |f0: f64| {
35 (1..=6).map(|h| (t * f0 * h as f64 * std::f64::consts::TAU).sin() / h as f64).sum::<f64>()
36 };
37 out.push((0.15 * env * voice(140.0)) as f32);
38 out.push((0.15 * env * voice(190.0)) as f32);
39 }
40 out
41}
42
43fn write_wav(path: &Path, rate: u32, channels: u16, samples: &[f32]) {
44 let data = (samples.len() * 2) as u32;
45 let mut wav = Vec::with_capacity(44 + data as usize);
46 wav.extend_from_slice(b"RIFF");
47 wav.extend_from_slice(&(36 + data).to_le_bytes());
48 wav.extend_from_slice(b"WAVEfmt ");
49 wav.extend_from_slice(&16u32.to_le_bytes());
50 wav.extend_from_slice(&1u16.to_le_bytes());
51 wav.extend_from_slice(&channels.to_le_bytes());
52 wav.extend_from_slice(&rate.to_le_bytes());
53 wav.extend_from_slice(&(rate * u32::from(channels) * 2).to_le_bytes());
54 wav.extend_from_slice(&(channels * 2).to_le_bytes());
55 wav.extend_from_slice(&16u16.to_le_bytes());
56 wav.extend_from_slice(b"data");
57 wav.extend_from_slice(&data.to_le_bytes());
58 for s in samples {
59 wav.extend_from_slice(&((s * 32767.0).round() as i16).to_le_bytes());
60 }
61 std::fs::write(path, wav).expect("write the source");
62}
63
64fn probe(path: &Path, args: &[&str]) -> String {
65 let out = Command::new("ffprobe")
66 .args(["-v", "error"])
67 .args(args)
68 .args(["-of", "csv=p=0"])
69 .arg(path)
70 .output()
71 .expect("ffprobe runs");
72 String::from_utf8_lossy(&out.stdout).trim().to_owned()
73}
74
75/// ffmpeg decodes the whole file with nothing to say on stderr.
76fn assert_clean_decode(path: &Path) {
77 let out = Command::new("ffmpeg")
78 .args(["-v", "error", "-i"])
79 .arg(path)
80 .args(["-f", "null", "-"])
81 .output()
82 .expect("ffmpeg runs");
83 assert!(out.status.success(), "ffmpeg decode failed");
84 let err = String::from_utf8_lossy(&out.stderr);
85 assert!(err.trim().is_empty(), "ffmpeg reported: {err}");
86}
87
88/// The file decoded by ffmpeg as interleaved f32 at 48 kHz.
89fn decode(path: &Path) -> Vec<f32> {
90 let out = Command::new("ffmpeg")
91 .args(["-v", "error", "-i"])
92 .arg(path)
93 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
94 .output()
95 .expect("ffmpeg runs");
96 assert!(out.status.success());
97 out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect()
98}
99
100/// SNR in dB of `got` against `want`, one channel of `channels`, over the middle (the codec's
101/// first and last frames excluded), at lag zero.
102fn snr(want: &[f32], got: &[f32], channels: usize, ch: usize) -> f64 {
103 let frames = want.len().min(got.len()) / channels;
104 let (mut sig, mut err) = (0f64, 0f64);
105 for i in 960..frames.saturating_sub(960) {
106 let (a, b) = (f64::from(want[i * channels + ch]), f64::from(got[i * channels + ch]));
107 sig += a * a;
108 err += (a - b) * (a - b);
109 }
110 10.0 * (sig / err.max(1e-20)).log10()
111}
112
113fn export(src: &Path, name: &str, settings: &ExportSettings) -> Scratch {
114 let session = PlaybackSession::open(src).expect("open the source");
115 let out = Scratch::file(&format!("ve_opusfile_{name}"), "opus");
116 let handle = session.export_to_with(&out, settings);
117 let deadline = Instant::now() + Duration::from_secs(300);
118 loop {
119 if let Some(result) = handle.result() {
120 result.expect("the export finishes");
121 break;
122 }
123 assert!(Instant::now() < deadline, "export never settled");
124 std::thread::sleep(Duration::from_millis(20));
125 }
126 assert_eq!(handle.progress(), 1.0);
127 out
128}
129
130/// The file's playing length in seconds, as ffprobe states it, less the pre-skip.
131///
132/// ffprobe's Ogg duration is the last granule over 48 kHz, pre-skip included -- a libopus file
133/// ffmpeg writes of a 3 s sine probes at 3.0065 s with its 312-sample pre-skip, and decodes to
134/// exactly 144000 samples. So the stated length is the granule, and the length a player plays
135/// is that less the pre-skip in `OpusHead`; both are checked, and the decode's sample count
136/// beside them in each test.
137fn duration(path: &Path) -> f64 {
138 let stated: f64 = probe(path, &["-show_entries", "format=duration"]).parse().expect("a duration");
139 let bytes = std::fs::read(path).unwrap();
140 let head = bytes.windows(8).position(|w| w == b"OpusHead").expect("an OpusHead");
141 let pre_skip = u16::from_le_bytes([bytes[head + 10], bytes[head + 11]]);
142 println!("ffprobe duration {stated:.6} s, pre-skip {pre_skip}");
143 stated - f64::from(pre_skip) / f64::from(RATE)
144}
145
146#[test]
147fn a_stereo_opus_export_probes_decodes_and_matches_its_source() {
148 if !have_ffmpeg() {
149 eprintln!("no ffmpeg: skipped");
150 return;
151 }
152 let src = Scratch::file("ve_opusfile_src", "wav");
153 let pcm = speechy(RATE, 3.0);
154 write_wav(&src, RATE, 2, &pcm);
155 let out = export(
156 &src,
157 "stereo",
158 &ExportSettings { format: Format::Opus, audio_kbps: Some(128), ..ExportSettings::default() },
159 );
160 assert_eq!(
161 probe(&out, &["-select_streams", "a:0", "-show_entries", "stream=codec_name,sample_rate,channels"]),
162 "opus,48000,2"
163 );
164 let d = duration(&out);
165 println!("stereo: duration {d:.6} s (timeline 3.000000)");
166 assert!((d - 3.0).abs() <= 0.001, "duration {d}");
167 assert_clean_decode(&out);
168 let got = decode(&out);
169 assert_eq!(got.len(), pcm.len(), "decoded to the sample");
170 let (l, r) = (snr(&pcm, &got, 2, 0), snr(&pcm, &got, 2, 1));
171 println!("stereo 128k: SNR L {l:.1} dB, R {r:.1} dB");
172 assert!(l > 20.0 && r > 20.0, "SNR {l} / {r}");
173 let tags = probe(&out, &["-show_entries", "stream_tags=encoder"]);
174 assert!(tags.contains("edith"), "encoder tag: {tags}");
175}
176
177#[test]
178fn a_44k_timeline_is_mixed_at_48k_for_opus() {
179 if !have_ffmpeg() {
180 eprintln!("no ffmpeg: skipped");
181 return;
182 }
183 let src = Scratch::file("ve_opusfile_src44", "wav");
184 write_wav(&src, 44_100, 2, &speechy(44_100, 2.0));
185 let out = export(&src, "44k", &ExportSettings { format: Format::Opus, ..ExportSettings::default() });
186 assert_eq!(probe(&out, &["-select_streams", "a:0", "-show_entries", "stream=sample_rate"]), "48000");
187 let d = duration(&out);
188 assert!((d - 2.0).abs() <= 0.001, "duration {d}");
189 assert_clean_decode(&out);
190 assert_eq!(decode(&out).len(), 2 * RATE as usize * 2, "two seconds at 48 kHz, to the sample");
191}
192
193#[test]
194fn a_ranged_opus_export_holds_exactly_the_range() {
195 if !have_ffmpeg() {
196 eprintln!("no ffmpeg: skipped");
197 return;
198 }
199 let src = Scratch::file("ve_opusfile_srcr", "wav");
200 let pcm = speechy(RATE, 4.0);
201 write_wav(&src, RATE, 2, &pcm);
202 // 30 fps audio-only canvas: frames 31..92 are 1.0333 s to 3.0667 s, 97600 samples.
203 let out = export(
204 &src,
205 "range",
206 &ExportSettings { format: Format::Opus, range: Some((31, 92)), ..ExportSettings::default() },
207 );
208 let want = 61.0 / 30.0;
209 let d = duration(&out);
210 println!("range: duration {d:.6} s (range {want:.6})");
211 assert!((d - want).abs() <= 0.001, "duration {d}");
212 assert_clean_decode(&out);
213 let got = decode(&out);
214 let from = 31 * 1600 * 2;
215 let slice = &pcm[from..from + 61 * 1600 * 2];
216 assert_eq!(got.len(), slice.len());
217 let s = snr(slice, &got, 2, 0);
218 println!("range: SNR L {s:.1} dB");
219 assert!(s > 20.0, "SNR {s}");
220}
221
222#[test]
223fn chapters_travel_as_vorbis_comments() {
224 if !have_ffmpeg() {
225 eprintln!("no ffmpeg: skipped");
226 return;
227 }
228 let src = Scratch::file("ve_opusfile_srcc", "wav");
229 write_wav(&src, RATE, 2, &speechy(RATE, 3.0));
230 let out = export(
231 &src,
232 "chapters",
233 &ExportSettings {
234 format: Format::Opus,
235 chapters: vec![(0, "Intro".into()), (1_500_000_000, "Middle".into())],
236 ..ExportSettings::default()
237 },
238 );
239 let listed = probe(&out, &["-show_chapters"]);
240 println!("chapters: {listed}");
241 assert!(listed.contains("Intro") && listed.contains("Middle"), "{listed}");
242 assert_eq!(listed.lines().count(), 2, "{listed}");
243 assert!(listed.contains("1.500000"), "{listed}");
244}
245
246/// 5.1, written straight through the writer (a timeline mix is at most stereo): family 1,
247/// four streams of which two coupled, and every WAV-order channel decoded back by ffmpeg in
248/// its own place.
249#[test]
250fn a_5_1_opus_file_is_mapping_family_1_with_every_channel_in_place() {
251 if !have_ffmpeg() {
252 eprintln!("no ffmpeg: skipped");
253 return;
254 }
255 let freqs = [300.0, 500.0, 700.0, 60.0, 1100.0, 1300.0];
256 let frames = RATE as usize * 2;
257 let mut pcm = Vec::with_capacity(frames * 6);
258 for i in 0..frames {
259 let t = i as f64 / f64::from(RATE);
260 for f in freqs {
261 pcm.push((0.2 * (t * f * std::f64::consts::TAU).sin()) as f32);
262 }
263 }
264 let out = Scratch::file("ve_opusfile_51", "opus");
265 let tags = engine::opus_write::Tags::default();
266 engine::opus_write::write(&out, &pcm, 6, RATE, 256, &tags, &mut |_| Ok(())).expect("write 5.1");
267 let bytes = std::fs::read(&out).unwrap();
268 let head = bytes.windows(8).position(|w| w == b"OpusHead").expect("an OpusHead");
269 assert_eq!(bytes[head + 9], 6, "channels");
270 assert_eq!(&bytes[head + 18..head + 21], &[1, 4, 2], "family 1, 4 streams, 2 coupled");
271 assert_eq!(&bytes[head + 21..head + 27], &[0, 4, 1, 2, 3, 5]);
272 assert_eq!(
273 probe(&out, &["-select_streams", "a:0", "-show_entries", "stream=codec_name,sample_rate,channels"]),
274 "opus,48000,6"
275 );
276 let d = duration(&out);
277 assert!((d - 2.0).abs() <= 0.001, "duration {d}");
278 assert_clean_decode(&out);
279 let got = decode(&out);
280 assert_eq!(got.len(), pcm.len());
281 for ch in 0..6 {
282 let s = snr(&pcm, &got, 6, ch);
283 println!("5.1 256k: channel {ch} SNR {s:.1} dB");
284 // The LFE (channel 3, a 60 Hz tone) is the hardest thing a CELT frame codes; the mapping
285 // claim is the next one, that each channel came back where it went in.
286 assert!(s > if ch == 3 { 8.0 } else { 20.0 }, "channel {ch}: SNR {s}");
287 for other in (0..6).filter(|&o| o != ch) {
288 let (mut num, mut a2, mut b2) = (0f64, 0f64, 0f64);
289 for i in 960..frames - 960 {
290 let (a, b) = (f64::from(pcm[i * 6 + other]), f64::from(got[i * 6 + ch]));
291 num += a * b;
292 a2 += a * a;
293 b2 += b * b;
294 }
295 let c = num / (a2 * b2).sqrt();
296 assert!(c.abs() < 0.1, "decoded channel {ch} carries source channel {other}: {c}");
297 }
298 }
299}