forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

opus_export.rs484 lines, 18.9 KiBHistoryRawDownload
1//! Opus on the way *out*: an edited Opus source leaves a Matroska export as
2//! Opus instead of being turned into AAC, and comes back in through this
3//! project's own door -- symphonia's mkv reader for the container, `ruopus` for
4//! the packets, which is the pair a film already plays through.
5//!
6//! Three claims, and each is measured rather than asserted from the code:
7//!
8//! * the file really carries an `A_OPUS` track with an `OpusHead` in its
9//! `CodecPrivate`, and what comes back out of it correlates with the mix that
10//! went in -- sample-aligned, so the pre-skip in that header is the encoder's
11//! real lookahead and not a number somebody hoped for;
12//! * a timeline nobody has touched still *copies* its AAC packets rather than
13//! taking the new encoder: Opus is what an edit costs, never what a passthrough
14//! costs;
15//! * and the envelope itself -- 48 kHz, stereo, at most
16//! `OPUS_MAX_KBPS` -- is a measurement of `opus-rs 0.1.26` and is pinned here,
17//! so the day the crate is bumped past its high-rate bug this suite says so.
18//!
19//! Nothing here needs a GPU: the picture is 320x180 and HEVC's intra encoder is
20//! software by construction, so the whole file runs anywhere. Add
21//! `EDITH_OPUS_FILM=<path to a real-library Opus mkv>` to run the film case too
22//! -- it is skipped without it, since no film lives in this repo.
23
24use std::path::{Path, PathBuf};
25use std::process::Command;
26use std::sync::Once;
27use std::time::{Duration, Instant};
28
29use engine::export::{ExportSettings, Format};
30use engine::project::{LaneKind, Source, Speed};
31use engine::scale::FitPolicy;
32use engine::scratch::Scratch;
33use engine::{AudioSession, Clip, ExportHandle, Project};
34
35/// The picture: 320x180 at 24 fps, 30 s (`scripts/gen_fixtures.sh`). Its own
36/// sound is mono Opus and is deliberately left off the audio lane -- see
37/// [`a_mono_mix_keeps_the_aac_path`].
38const VIDEO: &str = "test_seek_chirp.mkv";
39/// The sound: 5.1 Opus, 440 Hz in FL and 880 Hz in BR, folded to stereo on the
40/// way to the timeline -- so the mix this export encodes *is* an Opus source's,
41/// at the only rate Opus has.
42const OPUS: &str = "test_opus_51.mka";
43/// One Opus frame, in samples per channel: what the tail of an export may be
44/// padded by.
45const OPUS_FRAME_SAMPLES: usize = 960;
46/// The AAC source whose packets a copy must still win with.
47const AAC: &str = "test_av.mp4";
48
49fn asset(name: &str) -> PathBuf {
50 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
51 .join("../../assets")
52 .join(name)
53}
54
55fn out_path(name: &str) -> Scratch {
56 Scratch::file(&format!("ve_opus_{name}"), "mkv")
57}
58
59fn pin_software() {
60 static PIN: Once = Once::new();
61 PIN.call_once(|| unsafe {
62 std::env::set_var("VE_SW", "1");
63 std::env::set_var("VE_SW_ENC", "1");
64 });
65}
66
67fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
68 let started = Instant::now();
69 while !handle.is_finished() {
70 assert!(
71 started.elapsed() < limit,
72 "export did not finish in {limit:?}"
73 );
74 std::thread::sleep(Duration::from_millis(10));
75 }
76 handle.result().expect("a finished export has an outcome")
77}
78
79/// One second of picture with one second of `sound` under it, cut from
80/// `sound_in` seconds into that file: an edit, so nothing here can be a copy.
81fn project(video: &Path, sound: &Path, sound_in: u32) -> Project {
82 let clip = |source, in_frame, out_frame| Clip {
83 fade_in: 0,
84 fade_out: 0,
85 transition_out: 0,
86 start: 0,
87 in_frame,
88 out_frame,
89 source,
90 link: None,
91 eq: None,
92 color: None,
93 fit: FitPolicy::default(),
94 speed: Speed::NORMAL,
95 transform: None,
96 };
97 // The sound is source **0** on purpose: the timeline takes its rate and its
98 // width from the first source that has any, so a project whose first source
99 // is a mono-track video file is a mono timeline whatever plays on its audio
100 // lane -- which is the engine's rule, not this test's, and the one that
101 // decides whether Opus is reachable at all.
102 Project::from_parts(
103 vec![Source::new(sound, 0), Source::new(video, 0)],
104 vec![
105 (LaneKind::Video, vec![clip(1, 0, 24)]),
106 (
107 LaneKind::Audio,
108 vec![clip(0, sound_in * 24, sound_in * 24 + 24)],
109 ),
110 ],
111 Vec::new(),
112 Vec::new(),
113 Vec::new(),
114 )
115 .expect("a picture lane and an audio lane")
116}
117
118fn export(name: &str, project: Project, video: &Path) -> Scratch {
119 pin_software();
120 let out = out_path(name);
121 let (meta, _) = engine::demux::Demuxer::open(video).expect("probe the picture");
122 let handle = engine::export::start(
123 project,
124 meta,
125 &out,
126 &ExportSettings {
127 format: Format::Hevc,
128 ..Default::default()
129 },
130 None,
131 );
132 wait(&handle, Duration::from_secs(600)).expect("the export finishes");
133 out
134}
135
136/// Interleaved samples of a written file through the engine's own reader: the
137/// door an import comes in through, and for an Opus track that is symphonia's
138/// mkv reader handing `CodecPrivate` and blocks to `ruopus`.
139fn decode(path: &Path) -> (engine::AudioMeta, Vec<f32>) {
140 let (meta, chunks) = AudioSession::open(path)
141 .expect("reopen the export")
142 .expect("the export has audio");
143 let mut samples = Vec::new();
144 for chunk in chunks {
145 samples.extend(chunk.samples);
146 }
147 (meta, samples)
148}
149
150/// The best normalised correlation of `got` against `want` over the first
151/// `lags` samples of offset, and the offset that reached it: a lossy codec
152/// changes the samples, so what says "this is the same sound in the same place"
153/// is the shape, and where the shape sits.
154fn align(want: &[f32], got: &[f32], lags: usize) -> (f64, usize) {
155 let window = 12_000.min(want.len()).min(got.len().saturating_sub(lags));
156 assert!(window > 1000, "not enough sound to correlate");
157 let (mut best, mut at) = (-2.0, 0);
158 for lag in 0..lags {
159 let c = corr(&want[..window], &got[lag..lag + window]);
160 if c > best {
161 best = c;
162 at = lag;
163 }
164 }
165 (best, at)
166}
167
168fn corr(a: &[f32], b: &[f32]) -> f64 {
169 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
170 for (x, y) in a.iter().zip(b) {
171 num += f64::from(*x) * f64::from(*y);
172 da += f64::from(*x) * f64::from(*x);
173 db += f64::from(*y) * f64::from(*y);
174 }
175 num / (da.sqrt() * db.sqrt()).max(1e-12)
176}
177
178/// One channel of an interleaved buffer.
179fn chan(samples: &[f32], channels: usize, which: usize) -> Vec<f32> {
180 samples
181 .iter()
182 .skip(which)
183 .step_by(channels)
184 .copied()
185 .collect()
186}
187
188/// The claim: a cut of an Opus source, exported as a Matroska file, carries an
189/// Opus track -- and that track is this project's own mix, in the right place.
190#[test]
191fn an_edited_opus_source_leaves_a_matroska_export_as_opus() {
192 let out = export(
193 "cut",
194 project(&asset(VIDEO), &asset(OPUS), 1),
195 &asset(VIDEO),
196 );
197
198 // The container, before any decoder: `A_OPUS` with an `OpusHead` in its
199 // `CodecPrivate`, and no AAC track anywhere near it.
200 let bytes = std::fs::read(&*out).expect("read the export back");
201 let head = find(&bytes, b"OpusHead").expect("an OpusHead in the CodecPrivate");
202 assert!(find(&bytes, b"A_OPUS").is_some(), "the track says A_OPUS");
203 assert!(find(&bytes, b"A_AAC").is_none(), "and nothing says A_AAC");
204 assert_eq!(bytes[head + 9], 2, "OpusHead: stereo");
205 // The pre-skip: the encoder's lookahead plus the warm-up frame it throws
206 // away, which is what `export::tests` measures the sound starting at.
207 assert_eq!(
208 u16::from_le_bytes([bytes[head + 10], bytes[head + 11]]),
209 1080,
210 "OpusHead: pre-skip"
211 );
212 assert_eq!(
213 u32::from_le_bytes(bytes[head + 12..head + 16].try_into().unwrap()),
214 48_000,
215 "OpusHead: 48 kHz"
216 );
217 assert_eq!(bytes[head + 18], 0, "OpusHead: mapping family 0");
218
219 // ...and what a decoder makes of it, against the very second of the source
220 // the timeline cut out. The reader drops the pre-skip off the front, so a
221 // correct header lands the sound at zero: any leftover offset here is
222 // exactly the codec delay this file failed to declare.
223 let (meta, got) = decode(&out);
224 assert_eq!(meta.sample_rate, 48_000, "Opus reads back at 48 kHz");
225 assert_eq!(meta.channels, 2);
226 let (_, want) = {
227 let (m, chunks) = AudioSession::open_segments(asset(OPUS), &[(1.0, 2.0)])
228 .expect("open the source")
229 .expect("the source has sound");
230 let mut s = Vec::new();
231 for chunk in chunks {
232 s.extend(chunk.samples);
233 }
234 (m, s)
235 };
236 // The fixture's two channels are *pure* sines, so a lag search on them is
237 // ambiguous by whole periods (440 Hz is 109.09 samples) and cannot be the
238 // alignment check -- that one is unambiguous in `export::tests`, on a signal
239 // with no period, and lands on the declared pre-skip exactly. What is
240 // checked here is the pair a periodic signal *can* answer: the sound is the
241 // source's, and it is in the right place to within a sample at lag zero.
242 assert!(
243 got.len() >= want.len() - 2 && got.len() <= want.len() + OPUS_FRAME_SAMPLES * 2,
244 "the track is {} samples where the timeline is {}",
245 got.len(),
246 want.len()
247 );
248 for (which, name) in [(0, "left"), (1, "right")] {
249 let (w, g) = (chan(&want, 2, which), chan(&got, 2, which));
250 let span = w.len().min(g.len());
251 let aligned = corr(&w[..span], &g[..span]);
252 assert!(
253 aligned >= 0.98,
254 "{name}: correlation {aligned:.4} against the source at lag zero -- \
255 the export is either not this sound or not in this place"
256 );
257 // Past the first frame, where the encoder's cold start is behind it:
258 // 0.997 left and 0.993 right, measured, against 0.9948/0.9825 with the
259 // head in. That gap *is* the ramp the pre-skip cannot cover, and it is
260 // asserted from both sides so neither can drift unnoticed.
261 let settled = corr(&w[OPUS_FRAME_SAMPLES..span], &g[OPUS_FRAME_SAMPLES..span]);
262 assert!(
263 settled >= 0.99,
264 "{name}: correlation {settled:.4} past the first frame"
265 );
266 // ...and the head specifically, which is what the pre-skip and the
267 // warm-up frame are for. Measured at 128 kbps: 0.990 left, 0.953 right,
268 // where the same export with no warm-up frame scored 0.9788 left and a
269 // mis-declared pre-skip would score far less than either. The gap to the
270 // 0.99 above is one frame of cold start -- `opus-rs 0.1.26` opens about
271 // 6 dB down whatever is fed in ahead of it (two warm-up frames change
272 // this in no decimal place) -- so this threshold is that ramp stated
273 // rather than a shrug.
274 let head = corr(&w[..12_000], &g[..12_000]);
275 assert!(head >= 0.94, "{name}: the first 250 ms correlate {head:.4}");
276 }
277
278 // A second implementation on the same bytes, where the box has one: ffmpeg
279 // decoding what we wrote is the check that the file is Opus by the format's
280 // rules and not merely by ours -- pre-skip included, since ffmpeg drops it
281 // off the front exactly as this project's reader does.
282 if let Some(pcm) = ffmpeg_decode(&out) {
283 let (w, g) = (chan(&want, 2, 0), chan(&pcm, 2, 0));
284 let span = w.len().min(g.len());
285 assert!(
286 span + 4 >= w.len(),
287 "ffmpeg read {span} samples of a {} sample track",
288 w.len()
289 );
290 let c = corr(&w[..span], &g[..span]);
291 assert!(
292 c >= 0.99,
293 "ffmpeg's decode correlates {c:.4} with the source"
294 );
295 }
296}
297
298/// The other half of the seat: an untouched AAC timeline still *copies*, even
299/// into the container that would otherwise encode Opus. A copy is bit-exact and
300/// an encode is a generation of loss, so the new encoder must never be reached
301/// where the old passthrough still applies.
302#[test]
303fn an_untouched_timeline_still_copies_its_aac_into_an_mkv() {
304 let source = asset(AAC);
305 let out = export("copy", project(&source, &source, 0), &source);
306 let bytes = std::fs::read(&*out).expect("read the export back");
307 assert!(find(&bytes, b"A_AAC").is_some(), "the copy stays AAC");
308 assert!(
309 find(&bytes, b"A_OPUS").is_none(),
310 "an untouched lane took the Opus encoder instead of copying"
311 );
312}
313
314/// A mono mix keeps AAC, and that is a *measurement* and not a preference:
315/// `opus-rs 0.1.26` mis-encodes mono at rates it is asked for here (see the
316/// envelope test in `export.rs`), so the file that would play back wrong is
317/// never written. `test_seek_chirp.mkv` carries mono Opus, which is exactly the
318/// source that would tempt this path.
319#[test]
320fn a_mono_mix_keeps_the_aac_path() {
321 let source = asset(VIDEO);
322 let out = export("mono", project(&source, &source, 1), &source);
323 let bytes = std::fs::read(&*out).expect("read the export back");
324 assert!(
325 find(&bytes, b"A_AAC").is_some(),
326 "a mono mix is written as AAC"
327 );
328 assert!(find(&bytes, b"A_OPUS").is_none());
329}
330
331/// A real library, not a fixture: a real Opus film, cut, exported, read back.
332/// The path comes from the environment because no film's name belongs in this
333/// repository; without it the test says so and passes.
334#[test]
335fn a_real_library_opus_film_exports_as_opus() {
336 let Some(film) = std::env::var_os("EDITH_OPUS_FILM").map(PathBuf::from) else {
337 eprintln!("EDITH_OPUS_FILM unset: the film case is skipped");
338 return;
339 };
340 // The fixture's picture under the film's *sound*: what is on trial here is
341 // an Opus track off a real library -- 5.1, folded to stereo on the way in
342 // -- and decoding a 1080p AV1 film would drag a VA-API plugin into a test
343 // about audio.
344 let out = export("film", project(&asset(VIDEO), &film, 600), &asset(VIDEO));
345 let bytes = std::fs::read(&*out).expect("read the export back");
346 assert!(
347 find(&bytes, b"A_OPUS").is_some(),
348 "the film's sound stays Opus"
349 );
350 let (meta, got) = decode(&out);
351 assert_eq!((meta.sample_rate, meta.channels), (48_000, 2));
352 let (_, want) = {
353 let (_, chunks) = AudioSession::open_segments(&film, &[(600.0, 601.0)])
354 .expect("open the film")
355 .expect("the film has sound");
356 let mut s = Vec::new();
357 for chunk in chunks {
358 s.extend(chunk.samples);
359 }
360 ((), s)
361 };
362 // Film sound is broadband and has no period, so unlike the tone fixture the
363 // lag here is unambiguous: the peak is where the sound is.
364 let (c, lag) = align(&chan(&want, 2, 0), &chan(&got, 2, 0), 400);
365 // What ffprobe makes of the same file, printed rather than parsed -- run
366 // with `--nocapture` and this is the line that says `Audio: opus`.
367 if let Ok(probe) = Command::new("ffprobe")
368 .args(["-hide_banner"])
369 .arg(&*out)
370 .output()
371 {
372 eprint!("{}", String::from_utf8_lossy(&probe.stderr));
373 }
374 eprintln!("the film's span: correlation {c:.4} at lag {lag}");
375 assert!(c >= 0.99, "the film's span correlates {c:.4} at lag {lag}");
376 assert!(lag <= 2, "the film's span starts {lag} samples late");
377}
378
379/// Where `needle` first sits in `hay`.
380fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
381 hay.windows(needle.len()).position(|w| w == needle)
382}
383
384/// ffmpeg's own decode of a file, interleaved f32 at 48 kHz stereo. `None`
385/// where the box has no ffmpeg -- the test is about the file, not about this
386/// machine's packages.
387fn ffmpeg_decode(path: &Path) -> Option<Vec<f32>> {
388 let out = Command::new("ffmpeg")
389 .args(["-v", "error", "-i"])
390 .arg(path)
391 .args([
392 "-map", "0:a:0", "-f", "f32le", "-ar", "48000", "-ac", "2", "-",
393 ])
394 .output()
395 .ok()?;
396 assert!(
397 out.status.success(),
398 "ffmpeg refused the exported Opus track: {}",
399 String::from_utf8_lossy(&out.stderr)
400 );
401 Some(
402 out.stdout
403 .chunks_exact(4)
404 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
405 .collect(),
406 )
407}
408
409/// The one line the card shows while an export runs, where the picture is
410/// copied and the sound is not. Two lanes of work meet in that sentence -- the
411/// video copy path writes it, the Opus seat decides its second half -- and the
412/// half that matters is *measured*: the copy branch used to publish the
413/// prediction the card already shows, which would have named Opus on an export
414/// that quietly fell back to AAC.
415///
416/// The picture is `test_hevc.mkv` untouched, so it is copied block for block;
417/// the sound is the 5.1 Opus source folded to the stereo mix Opus is reachable
418/// at, so it is encoded. Nothing in the file is decoded to prove this -- the
419/// container is read back for the track ids, which is what the two paths
420/// actually wrote.
421#[test]
422fn a_copied_picture_names_the_sound_it_was_written_with() {
423 pin_software();
424 let video = asset("test_hevc.mkv");
425 let sound = asset(OPUS);
426 let (meta, _) = engine::demux::Demuxer::open(&video).expect("probe the picture");
427 let frames = meta.frame_count;
428 let clip = |source, out_frame| Clip {
429 fade_in: 0,
430 fade_out: 0,
431 transition_out: 0,
432 start: 0,
433 in_frame: 0,
434 out_frame,
435 source,
436 link: None,
437 eq: None,
438 color: None,
439 fit: FitPolicy::default(),
440 speed: Speed::NORMAL,
441 transform: None,
442 };
443 // The sound is source 0, for the reason [`project`] gives: the timeline
444 // takes its rate and its width from the first source that has any.
445 let project = Project::from_parts(
446 vec![Source::new(&sound, 0), Source::new(&video, 0)],
447 vec![
448 (LaneKind::Video, vec![clip(1, frames)]),
449 (LaneKind::Audio, vec![clip(0, frames)]),
450 ],
451 Vec::new(),
452 Vec::new(),
453 Vec::new(),
454 )
455 .expect("a picture lane and an audio lane");
456 let out = out_path("copy_line");
457 let handle = engine::export::start(
458 project,
459 meta,
460 &out,
461 &ExportSettings {
462 format: Format::Hevc,
463 ..Default::default()
464 },
465 None,
466 );
467 let line = {
468 wait(&handle, Duration::from_secs(600)).expect("the export finishes");
469 handle.encoders().unwrap_or_default()
470 };
471 println!("the card's line: {line}");
472 assert!(
473 line.starts_with("copy · "),
474 "the untouched picture was not copied: {line}"
475 );
476 assert!(
477 line.contains("Opus"),
478 "the copied picture's line does not name the sound it was written with: {line}"
479 );
480 // ...and the file agrees with the line, on both halves.
481 let bytes = std::fs::read(&*out).expect("read the export back");
482 assert!(find(&bytes, b"A_OPUS").is_some(), "the track says A_OPUS");
483 assert!(find(&bytes, b"A_AAC").is_none(), "and nothing says A_AAC");
484}