diff --git a/Cargo.lock b/Cargo.lock index 7185421..990056d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3372,6 +3372,16 @@ dependencies = [ "libc", ] +[[package]] +name = "matrixmultiply" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" +dependencies = [ + "autocfg", + "rawpointer", +] + [[package]] name = "maybe-rayon" version = "0.1.1" @@ -3538,6 +3548,22 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "ndarray" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" +dependencies = [ + "matrixmultiply", + "num-complex", + "num-integer", + "num-traits", + "portable-atomic", + "portable-atomic-util", + "rawpointer", + "serde", +] + [[package]] name = "new_debug_unreachable" version = "1.0.6" @@ -3608,6 +3634,34 @@ dependencies = [ "memchr", ] +[[package]] +name = "non-empty-iter" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac123b8e4bd1fef3e8e972ba7a07f046ac6b608633ad761c61876b7197313f63" +dependencies = [ + "non-zero-size", +] + +[[package]] +name = "non-empty-slice" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9935c822e11be79ef40f986558b00da0ff176b7c87ddf6d9fb8b9138a6112c20" +dependencies = [ + "non-empty-iter", + "non-zero-size", + "ownership", + "serde", + "thiserror 2.0.20", +] + +[[package]] +name = "non-zero-size" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "401b3a4027292c1c318fd2305783f791d5579d18e7143ef72d653bf0c29e6b36" + [[package]] name = "noop_proc_macro" version = "0.3.0" @@ -3672,6 +3726,7 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ "bytemuck", "num-traits", + "serde", ] [[package]] @@ -3951,6 +4006,12 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "ownership" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfb1aeb68b9f2683ee3f83960c10668b37a8a640224ba1169697ee8fd1e906c1" + [[package]] name = "oxideav-ac3" version = "0.0.10" @@ -4279,6 +4340,21 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + [[package]] name = "postage" version = "0.5.0" @@ -4324,6 +4400,15 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "primal-check" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08" +dependencies = [ + "num-integer", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -4700,6 +4785,12 @@ dependencies = [ "raw-window-handle", ] +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + [[package]] name = "rayon" version = "1.12.0" @@ -4731,6 +4822,15 @@ dependencies = [ "once_cell", ] +[[package]] +name = "realfft" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f821338fddb99d089116342c46e9f1fbf3828dba077674613e734e01d6ea8677" +dependencies = [ + "rustfft", +] + [[package]] name = "reborrow" version = "0.5.5" @@ -4869,6 +4969,9 @@ name = "ruopus" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd" +dependencies = [ + "spectrograms", +] [[package]] name = "rust-embed" @@ -4927,6 +5030,20 @@ dependencies = [ "semver", ] +[[package]] +name = "rustfft" +version = "6.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89" +dependencies = [ + "num-complex", + "num-integer", + "num-traits", + "primal-check", + "strength_reduce", + "transpose", +] + [[package]] name = "rustix" version = "0.38.44" @@ -5506,6 +5623,24 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spectrograms" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff1e83612f5a16e413dbfaf0381753b5eee714932fc95db19fe0974d5e6462b" +dependencies = [ + "ndarray", + "non-empty-slice", + "num-complex", + "num-traits", + "once_cell", + "pkg-config", + "realfft", + "regex", + "rustfft", + "thiserror 2.0.20", +] + [[package]] name = "spin" version = "0.9.9" @@ -5570,6 +5705,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strength_reduce" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82" + [[package]] name = "strict-num" version = "0.1.1" @@ -6401,6 +6542,16 @@ dependencies = [ "once_cell", ] +[[package]] +name = "transpose" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e" +dependencies = [ + "num-integer", + "strength_reduce", +] + [[package]] name = "try-lock" version = "0.2.5" diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 4419a58..23b6059 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -81,8 +81,23 @@ rusty_mp3 = "0.6" # packet. This one does the whole pipeline. Its quirks are measured and worked # around in [`crate::export::write_ogg`] -- read that before touching this line. rusty_vorbis = "0.1.1" -# The Opus decoder: pure Rust, MIT, no C and no FFI, and no dependencies at all -# without its default features (`spectrograms` is for its own analysis tools). +# The Opus decoder: pure Rust, MIT, no C and no FFI. +# +# `spectrograms` is not, as this line long claimed, "for its own analysis tools": +# it is the crate's *FFT backend*, and it is default-on because CELT synthesis is +# an N/4 complex FFT per block. Turned off -- which is what asking for `std` +# alone did -- `celt/mdct.rs` falls back to an O(n²) DFT evaluated in f64, and a +# 5.1 film soundtrack decodes at **0.95x realtime**: slower than playing it. +# With the backend on, the same file decodes at **104x** (7.1: 0.93x -> 112x, +# stereo: 10.4x -> 135x). The cost is fifteen pure-Rust crates (`spectrograms` -> +# `realfft`/`rustfft`, `ndarray`, `regex`), still no C and no `build.rs`. +# The output is *not* bit-identical to the DFT build -- FFT summation order +# differs -- but the two agree to 144 dB SNR (max |Δ| 3.7e-8, half an LSB at +# 24-bit) while *both* sit 93 dB from ffmpeg's own libopus decode of the same +# file. The change is 40 dB below the decoder's existing distance to the +# reference, i.e. inside float noise, and upstream says as much: Opus conformance +# is a quality threshold (`opus_compare`), not bit-exactness, and every +# bitstream-affecting computation stays exact either way. # Symphonia has no Opus at any version -- its feature list stops at vorbis and # there is no `symphonia-codec-opus` crate -- while both of its containers *read* # the format already: `A_OPUS` and `OpusHead` have always mapped to @@ -99,7 +114,7 @@ rusty_vorbis = "0.1.1" # where the film is silent. This one matches ffmpeg's own decode of the same file to a # correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3` # below, because a decoder is a bit-exactness dependency. -ruopus = { version = "=0.1.2", default-features = false, features = ["std"] } +ruopus = { version = "=0.1.2", default-features = false, features = ["std", "spectrograms"] } # The Opus *encoder*, the other half of that pair: a pure-Rust port of libopus # 1.6, BSD-3, `build.rs`-less and with **no dependencies at all** -- checked, not # taken from the README (`cargo tree` is two lines; there is not one `.c`, `.h` diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 75ac7a9..99b7ed3 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -276,6 +276,17 @@ pub struct PlaybackSession { /// not -- with the single exception `sources` itself has, /// [`Self::remove_source`], which takes the same entry out of both. counts: Vec, + /// Audio headers already read, by the `(path, stream)` they were read for. + /// Every door that checks a file against the timeline asks the same two + /// questions -- what this file's sound is, and what the timeline's first + /// source's is ([`audio_matches`], [`first_audio_of`]) -- and each answer is + /// a container open. Warm that is 5-10 ms; on a film whose pages have been + /// evicted it is **1.7 s** (measured, 3.1 GB HEVC mkv), and both of those + /// are spent on the thread that draws, because placing and importing are + /// what a drag lands on. A header does not change while a session holds the + /// file, so it is read once and remembered. Errors are not kept: a file that + /// failed to open is asked again next time. + probes: std::collections::HashMap<(std::path::PathBuf, usize), Option>, /// What each source's own frame rate is against this timeline's, indexed /// and grown exactly as [`Self::counts`] is (and shortened with it by /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the @@ -423,6 +434,7 @@ impl PlaybackSession { audio_disabled, project, counts: vec![meta.frame_count], + probes: std::collections::HashMap::new(), // Source 0 *is* the timeline's rate: it defined it. rates: vec![Rate::REAL_TIME], span_rate: Rate::REAL_TIME, @@ -534,6 +546,7 @@ impl PlaybackSession { audio_disabled, project, counts: vec![meta.frame_count], + probes: std::collections::HashMap::new(), // Source 0 *is* the timeline's rate: it defined it. rates: vec![Rate::REAL_TIME], span_rate: Rate::REAL_TIME, @@ -609,6 +622,7 @@ impl PlaybackSession { audio_disabled: None, project, counts: vec![meta.frame_count], + probes: std::collections::HashMap::new(), // Source 0 *is* the timeline's rate: it defined it. rates: vec![Rate::REAL_TIME], span_rate: Rate::REAL_TIME, @@ -902,6 +916,7 @@ impl PlaybackSession { audio_disabled, project, counts, + probes: std::collections::HashMap::new(), rates, span_rate: Rate::REAL_TIME, span, @@ -2055,7 +2070,7 @@ impl PlaybackSession { let image = crate::is_image(path); if !image { let first = self.first_audio()?; - audio_matches(&wanted, &first)?; + self.audio_matches_cached(&wanted, &first)?; } let rate = self.file_rate(&wanted.path); let source = self.project.import(path, stream); @@ -2167,8 +2182,44 @@ impl PlaybackSession { /// What the timeline's audio *is*: the chosen stream of the first source /// that could have any ([`audio_source_of`]), probed. Every other source is /// held to it. - fn first_audio(&self) -> crate::Result> { - first_audio_of(self.project.sources()) + /// + /// Through the session's own memo ([`probes`](Self::probes)), because this + /// is asked on the render thread: the free [`first_audio_of`] is the one a + /// worker with no session to reach for calls. + fn first_audio(&mut self) -> crate::Result> { + match audio_source_of(self.project.sources()) { + Some(first) => { + let (path, stream) = (first.path.clone(), first.audio_stream); + self.probe_cached(&path, stream) + } + None => Ok(None), + } + } + + /// One audio header, read at most once per session per `(path, stream)`. + fn probe_cached( + &mut self, + path: &Path, + stream: usize, + ) -> crate::Result> { + let key = (path.to_path_buf(), stream); + if let Some(probe) = self.probes.get(&key) { + return Ok(*probe); + } + let probe = AudioSession::probe(path, stream)?; + self.probes.insert(key, probe); + Ok(probe) + } + + /// [`audio_matches`] with this session's memo behind the new file's own + /// header too -- the second of the two opens a place or an import pays. + fn audio_matches_cached( + &mut self, + source: &Source, + first: &Option, + ) -> crate::Result<()> { + let probe = self.probe_cached(&source.path, source.audio_stream)?; + audio_matches_probed(probe, first) } /// Places `clip` on `lane` alone at the playhead, overwriting what it lands @@ -2320,7 +2371,7 @@ impl PlaybackSession { // Stream 0, and there is no other: a standalone audio file carries one // track (`AudioSession::probe_streams`), so nothing here has a stream // to pick the way `place_stream_at` does for an mp4. - audio_matches(&Source::new(path, 0), &first)?; + self.audio_matches_cached(&Source::new(path, 0), &first)?; let frames = audio_frames(path, self.meta.frame_rate)?; let source = self.project.import(path, 0); self.note_frames(source, frames, Rate::REAL_TIME); @@ -2912,12 +2963,22 @@ fn audio_source_of(sources: &[Source]) -> Option<&Source> { } fn audio_matches(source: &Source, first: &Option) -> crate::Result<()> { + let probe = AudioSession::probe(&source.path, source.audio_stream)?; + audio_matches_probed(probe, first) +} + +/// The verdict alone, once the file's own header is in hand: the half a session +/// with a memo behind it ([`PlaybackSession::audio_matches_cached`]) does not +/// have to open the file for. +fn audio_matches_probed( + probe: Option, + first: &Option, +) -> crate::Result<()> { // The layout, which the audio worker holds every source to anyway -- and not // the rate any more: a file written at another one is resampled to the // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as // a file shot at another frame rate is read through [`Rate`]. Both silent is // a match. - let probe = AudioSession::probe(&source.path, source.audio_stream)?; if probe.map(|p| p.channels) == first.map(|p| p.channels) { return Ok(()); } @@ -3187,6 +3248,53 @@ mod tests { assert_eq!(session.sources().len(), session.counts.len()); } + /// The two headers a place reads are read *once*: an mp4 dropped on a lane + /// used to open its own container and the timeline's first source every + /// time, both on the thread that draws, and a film whose pages have gone + /// cold is 1.7 s of that. + /// + /// Proved by answering, not by timing: the memo is filled with a layout the + /// file does not have, and the place is refused. Only a door that read the + /// remembered header rather than the disk can refuse it. + #[test] + fn a_place_reads_each_audio_header_once() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &asset("test_av2.mp4"), 0, None) + .expect("a file just imported is on this timeline") + ); + assert_eq!( + session.probes.len(), + 2, + "the timeline's first source and the file placed, once each" + ); + + // Now say av2 is 5.1. Nothing on disk changed, so a door that opens the + // file still matches; one that trusts the memo refuses by layout. + // Keyed exactly as a [`Source`] names a file -- canonical, symlinks + // resolved -- which is the key the doors look up. + let av2 = Source::new(asset("test_av2.mp4"), 0).path; + session.probes.insert( + (av2, 0), + Some(crate::AudioProbe { + sample_rate: 48_000, + channels: 6, + }), + ); + let refused = session + .place_stream_at(end, &asset("test_av2.mp4"), 0, None) + .expect_err("the remembered layout disagrees with the timeline's"); + assert!( + refused.to_string().contains("6 ch"), + "refused in the layout's own words: {refused}" + ); + assert_eq!(session.probes.len(), 2, "and nothing was opened to say so"); + } + #[test] fn boundary_seconds_round_trip_to_their_own_frame() { for f in 0u32..300 { diff --git a/crates/engine/tests/pgs_bitmaps.rs b/crates/engine/tests/pgs_bitmaps.rs index 6fb20bc..5de2956 100644 --- a/crates/engine/tests/pgs_bitmaps.rs +++ b/crates/engine/tests/pgs_bitmaps.rs @@ -62,12 +62,17 @@ fn the_session_maps_a_pgs_track_onto_the_timeline_and_draws_it() { let drawn = Instant::now(); let image = cues[0].image.as_ref().expect("a picture cue"); let rgba = image.rgba().expect("the first display set decodes"); + let took = drawn.elapsed(); eprintln!( - "cue 0 decoded to {}x{} in {:?}", - image.width, - image.height, - drawn.elapsed() + "cue 0 decoded to {}x{} in {took:?}", + image.width, image.height, ); + // The run-length walk is paid once per cue *change* -- the window keeps the + // picture while it is up ([`Player::sub_picture`]) -- so what this holds is + // the cost of the one frame a new line appears on: 247 µs measured on this + // remux, a sixty-eighth of that frame's budget. A whole repaint's worth + // would mean the cache above it had stopped mattering. + assert!(took.as_millis() < 16, "a frame's worth of decode: {took:?}"); assert_eq!(rgba.len(), (image.width * image.height * 4) as usize); let opaque = rgba.chunks_exact(4).filter(|px| px[3] > 0).count(); assert!(opaque > 0, "the block decoded to an empty canvas");