forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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