diff --git a/Cargo.lock b/Cargo.lock index 8e32099..f626bf6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1588,6 +1588,27 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "ec-core" +version = "0.1.0" + +[[package]] +name = "ec-dsp" +version = "0.1.0" +dependencies = [ + "ec-core", + "wide 1.7.0", +] + +[[package]] +name = "ec-opus" +version = "0.1.0" +dependencies = [ + "ec-core", + "ec-dsp", + "wide 1.7.0", +] + [[package]] name = "edith" version = "0.1.0" @@ -1636,6 +1657,7 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" name = "engine" version = "0.1.0" dependencies = [ + "ec-opus", "flacenc", "hound", "image", @@ -1643,7 +1665,6 @@ dependencies = [ "libloading", "miniz_oxide", "mp4", - "opus-rs", "oxideav-ac3", "oxideav-ass", "oxideav-core", @@ -1652,7 +1673,6 @@ dependencies = [ "oxideav-sub-image", "oxideav-subtitle", "rav1e", - "ruopus", "rusty_aac", "rusty_h264", "rusty_mp3", @@ -3373,16 +3393,6 @@ 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" @@ -3547,22 +3557,6 @@ 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" @@ -3633,34 +3627,6 @@ 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" @@ -3725,7 +3691,6 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ "bytemuck", "num-traits", - "serde", ] [[package]] @@ -3989,12 +3954,6 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" -[[package]] -name = "opus-rs" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f1ce2826529746cac003d7338e9c0f47cdd2979ba769c61cc26fdebc402f4c" - [[package]] name = "ordered-stream" version = "0.2.0" @@ -4005,12 +3964,6 @@ 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" @@ -4339,21 +4292,6 @@ 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" @@ -4399,15 +4337,6 @@ 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" @@ -4782,12 +4711,6 @@ 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" @@ -4819,15 +4742,6 @@ 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" @@ -4961,15 +4875,6 @@ version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" -[[package]] -name = "ruopus" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd" -dependencies = [ - "spectrograms", -] - [[package]] name = "rust-embed" version = "8.12.0" @@ -5027,20 +4932,6 @@ 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" @@ -5149,7 +5040,7 @@ name = "rusty_h264-common" version = "0.9.1" dependencies = [ "bytemuck", - "wide", + "wide 0.7.33", ] [[package]] @@ -5232,6 +5123,15 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "safe_arch" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f" +dependencies = [ + "bytemuck", +] + [[package]] name = "same-file" version = "1.0.6" @@ -5620,24 +5520,6 @@ 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" @@ -5702,12 +5584,6 @@ 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" @@ -6539,16 +6415,6 @@ 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" @@ -7077,7 +6943,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03" dependencies = [ "bytemuck", - "safe_arch", + "safe_arch 0.7.4", +] + +[[package]] +name = "wide" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf05ca94c9fba0c51316899caa1d1e74a064fc310a5efa7375e614343d415be" +dependencies = [ + "bytemuck", + "safe_arch 1.2.0", ] [[package]] diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a80cb5e..13b8ed2 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -35,7 +35,7 @@ mp4 = "0.14" # rest of the ecosystem is built on. miniz_oxide = "0.8" # The software H.264 pair, and the only software decoder this project has for -# any format. Pinned exactly, like `ruopus` and `oxideav-ac3` below, because a +# any format. Pinned exactly, like `oxideav-ac3` below, because a # decoder is a bit-exactness dependency -- and 0.9.1 is where that stopped being # a figure of speech. Measured 2026-08-12 against ffmpeg's own decode of a 1080p # High and a 720p Main clip, 750 pictures between them: 0.8 matched it @@ -87,57 +87,36 @@ 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. -# -# `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 # `CODEC_ID_OPUS`. The decoder was the one missing half, and the reason a 5.1 # Opus film played silent while its picture was fine. # -# Multistream is what decides which crate: a 5.1 track is four elementary Opus -# streams in one packet, all but the last **self-delimited** (RFC 6716 App. B), -# and this one strips that framing per stream (`multistream.rs:71`). The obvious -# sibling pick, `rusty-opus 0.9.1` -- same family as `rusty_aac`/`rusty_mp3` -# above -- hands each self-delimited slice to a decoder that parses it as an -# ordinary packet, so every stream but the last decodes the length prefix as -# payload: measured on a real 5.1 Opus remux as full-scale noise at -13 dBFS -# 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", "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` -# or `.S` file in the crate). It is what lets an edited Opus source leave in a -# Matroska file as Opus instead of being downgraded to AAC on the way out. +# Both Opus seats are `ec-opus`, the codec family built in the sibling +# workspace this checkout expects beside it (`edith_codecs`): the multistream +# decoder a surround track needs -- a 5.1 packet is four elementary Opus +# streams, all but the last **self-delimited** (RFC 6716 App. B), and this one +# strips that framing per stream -- and the CELT encoder the export seat codes +# with. The path is the first edge across that workspace boundary, and a path +# is the whole story: the family is not a registry crate, so there is no +# version to pin -- the working tree is exactly as pinned as a decoder that is +# a bit-exactness dependency can be. # -# Used inside a measured envelope, and that envelope is the whole reason this -# line is not simply "the encoder": 48 kHz **stereo** at **at most** -# [`crate::export::OPUS_MAX_KBPS`]. Above roughly 165 kbps stereo this encoder -# writes packets that only its *own* decoder reads back -- `ruopus` decodes them -# as noise (correlation 0.06 at 256 kbps against the source, 0.9999 at 160), and -# `ruopus` is not the suspect: it decodes ffmpeg's own libopus at 256 kbps to -# correlation 1.00000 on the same signal. Mono is worse and at every rate, which -# is why a mono mix keeps the AAC path. Both measured in -# `tests/opus_export.rs`, which fails the day the crate is unpinned onto a -# version that has fixed it -- that is the upgrade signal. -opus-rs = "=0.1.26" +# What it replaced, and why the move is measured rather than hoped for: +# `ruopus 0.1.2` decoded (it matched ffmpeg's own decode of a real 5.1 Opus +# remux to correlation 1.0000 on all six channels) but ran the export +# fidelity path's stereo decode at 0.2x real time (measured, 24.2 s for 121.5 s +# of stereo), and `opus-rs 0.1.26` encoded -- into packets that only +# its own decoder read back above roughly 165 kbps stereo, the edge moving with +# the content (correlation 0.06 at 256 kbps against the source; its own round +# trip read 0.9999 at 160), and mono worse still at every rate. That is what +# held [`crate::export::OPUS_MAX_KBPS`] at 128 and a mono mix on the AAC path. +# Both replaced seats are measured where they used to fail: `export::tests` +# round-trips the top of the new band and the mono path, and +# `tests/opus_export.rs` exports and re-reads the files through this project's +# own decoder door. +ec-opus = { path = "../../../edith_codecs/crates/ec-opus" } # The Ogg container, and the only new *name* here that is not a new crate tree: # its one dependency is `oxideav-core`, which the AC-3 decoder above already # pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the @@ -154,7 +133,7 @@ symphonia-codec-aac = "0.6" # `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of # a Matroska video file is read, the picture having its own demuxer here. # There is no opus/ac3/dts feature at any symphonia version: AC-3 comes from -# `oxideav-ac3` and Opus from `ruopus` above, both plugged into this crate's +# `oxideav-ac3` and Opus from `ec-opus` above, both plugged into this crate's # own readers, and DTS is the one that really is refused. symphonia = { version = "0.6", default-features = false, features = [ "aac", diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 0cc0499..42e0be7 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -67,7 +67,7 @@ const EMPTY_EDIT: u64 = u32::MAX as u64; /// symphonia's registry as this project enables it (see the feature list in /// `Cargo.toml`) plus the two families no symphonia version carries and this /// project decodes anyway -- AC-3/E-AC-3 through `oxideav-ac3` ([`MkvAc3Track`]) -/// and Opus through `ruopus` ([`SymDecoder::Opus`]). +/// and Opus through `ec-opus` ([`SymDecoder::Opus`]). /// /// Written down per container because capability is not one set: an mp4 video's /// sound never reaches symphonia ([`Track::open`] answers before it), so it @@ -1701,7 +1701,7 @@ impl SymTrack { /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 and /// 7.1 tracks of a film, so those go to `rusty_aac` instead /// ([`aac_decoder`]), and it has no Opus decoder at all, so that one goes to - /// `ruopus`. + /// `ec-opus` ([`SymDecoder::Opus`]). fn decoder(&self) -> crate::Result { let from = usize::from(self.source_channels); if self.params.codec == CODEC_ID_OPUS { @@ -1709,7 +1709,7 @@ impl SymTrack { opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), from)?; // 48 kHz whatever the container says: that is the only rate Opus // decodes at, and the rate both readers declare for it. - let decoder = ruopus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping); + let decoder = ec_opus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping); return Ok(SymDecoder::Opus(Box::new(decoder), from)); } if self.params.codec == CODEC_ID_AAC { @@ -1840,7 +1840,7 @@ enum SymDecoder { /// Every Opus track, mono to 7.1: one multistream decoder -- the streams of /// a packet, the channel mapping table and the routing between them are all /// its business -- and the same width. - Opus(Box, usize), + Opus(Box, usize), } impl SymDecoder { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index f0816ee..3f984e6 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -859,7 +859,7 @@ fn audio_label( // It is one line and 76 characters wide (`summary_head` in the app // has the test), which is why the condition is in this comment // instead of in the string. - false if format.is_mkv() => "Opus · SW encode (opus-rs)", + false if format.is_mkv() => "Opus · SW encode (ec-opus)", false => "AAC · SW encode (rusty_aac)", }, } @@ -881,10 +881,10 @@ fn measured_audio_label( opus: bool, ) -> &'static str { match (sound, opus) { - (_, true) => "Opus · SW encode (opus-rs)", + (_, true) => "Opus · SW encode (ec-opus)", // Encoded, into a container that would have carried Opus, and it is not - // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or the - // mix was not the 48 kHz stereo that seat is measured in. + // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or + // the mix was not 48 kHz at a width the seat is measured in. (Some(false), false) if format.is_mkv() => "AAC · SW encode (rusty_aac)", // `sound` is already what happened, not a prediction, so `copied` is // filled in and `ranged` never reaches the branch that reads it. @@ -2020,29 +2020,30 @@ fn encode_audio( ); // Opus where the container carries it and the mix is inside the envelope - // this encoder was *measured* correct in ([`encode_opus`]): a Matroska file, - // 48 kHz, stereo. An Opus source edited into an mkv export therefore leaves - // as Opus instead of being turned into AAC on the way out, which is the one - // generation of loss an all-Opus timeline used to pay for being cut. + // this encoder is *measured* correct in ([`encode_opus`]): a Matroska file, + // 48 kHz, mono or stereo. An Opus source edited into an mkv export + // therefore leaves as Opus instead of being turned into AAC on the way + // out, which is the one generation of loss an all-Opus timeline used to + // pay for being cut. // // Everything else falls through to the AAC below and is unchanged by this: - // every mp4, a mono mix, a 44.1 kHz timeline. The rate is the mix's own -- - // there is no resampler on this path, and inventing one to reach 48 kHz - // would resample a whole timeline to satisfy a codec, which is a bigger - // change to the sound than the codec is. + // every mp4, a 44.1 kHz timeline. The rate is the mix's own -- there is no + // resampler on this path, and inventing one to reach 48 kHz would resample + // a whole timeline to satisfy a codec, which is a bigger change to the + // sound than the codec is. // ...and again before either encoder is entered: both of them run to the // end of the mix without a checkpoint of their own, so this is the last // moment a cancel costs seconds rather than the whole encode. cancelled(shared)?; if mkv && audio.sample_rate == OPUS_RATE - && channels == 2 - && let Some((packets, pre_skip)) = encode_opus(&samples, kbps)? + && (1..=2).contains(&channels) + && let Some((packets, pre_skip)) = encode_opus(&samples, kbps, channels)? { return Ok(Some(ExportAudio { params: crate::AacTrackParams { freq_index, - chan_conf: 2, + chan_conf: channels as u8, sample_rate: OPUS_RATE, }, packets, @@ -2095,13 +2096,16 @@ pub(crate) const OPUS_RATE: u32 = 48_000; /// Matroska block timestamp in whole milliseconds is exact. const OPUS_FRAME: usize = 960; -/// The most this project asks of `opus-rs`, in kbps, and why it is a cap rather -/// than the four rates the Sound row offers: this encoder falls off a cliff at a -/// rate that depends on the *content*, and above it a conformant decoder gets -/// noise back. Measured on three one-second spans of a real 5.1 Opus film, -/// encoded here and decoded with `ruopus` -- which is not the suspect, since it -/// decodes ffmpeg's own libopus at 256 kbps to correlation 1.00000 on the same -/// material: +/// The most this project asks of the Opus encoder, in kbps, and why it is a cap +/// rather than the four rates the Sound row offers. +/// +/// History, because the number moved once already and the reason it could is +/// part of the record. Under `opus-rs 0.1.26` the ceiling was 128: that encoder +/// fell off a cliff at a rate that depended on the *content*, and above it a +/// conformant decoder got noise back. Measured on three one-second spans of a +/// real 5.1 Opus film, encoded there and decoded with `ruopus` -- which was not +/// the suspect, since it decoded ffmpeg's own libopus at 256 kbps to +/// correlation 1.00000 on the same material: /// /// ```text /// kbps 120 128 136 144 152 160 @@ -2111,18 +2115,21 @@ const OPUS_FRAME: usize = 960; /// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control) /// ``` /// -/// So: usable to 128, ruined by 136 on real film sound, and the pure-tone -/// fixtures that first suggested a 165 kbps ceiling were simply easy material. -/// 128 kbps stereo Opus is around transparency anyway (libopus scores 0.998 -/// there on the worst of those spans), so the cap costs nothing a listener has. -/// It is still not *trusted*: every track is decoded again and measured before -/// it is written ([`opus_fidelity`]), because a cliff whose edge moves with the -/// material is not something a constant can be safe against on its own. +/// So: usable to 128, ruined by 136 on real film sound -- and mono worse, at +/// every rate, which is why a mono mix kept the AAC path entirely. `ec-opus` +/// has no such cliff: its own suite holds every rate of the format's table to +/// the reference decoders, mono, stereo and 5.1 alike, and this project +/// re-measures the high band and the mono path where the old encoder failed +/// (`the_opus_encoder_is_pinned_to_the_band_it_was_measured_in`). /// -/// corner-cut: the ceiling is this encoder's, not the format's. Upgrade path is a -/// released `opus-rs` that survives its own high rates -- the unit test pins the -/// failure, so it fails the day the bug is fixed and this can be raised. -pub(crate) const OPUS_MAX_KBPS: u32 = 128; +/// It is still not *trusted*: every track is decoded again and measured before +/// it is written ([`opus_fidelity`]), because a rate nobody measured on *your* +/// sound is not something a constant can be safe against on its own. +/// The ceiling is the Sound row's ([`AUDIO_KBPS`]), not the format's 510 kbps: +/// a rate nothing in the product can ask for is a rate nothing here measures. +/// 320 covers the row honestly, including the 256 default +/// ([`DEFAULT_AUDIO_KBPS`]) the old cap silently halved on a Matroska export. +pub(crate) const OPUS_MAX_KBPS: u32 = 320; /// How well a track has to survive its own round trip to be written as Opus: /// the correlation between the mix and the decode of what was encoded from it. @@ -2142,24 +2149,33 @@ const OPUS_MIN_FIDELITY: f64 = 0.95; const OPUS_PRE_SKIP: u16 = 120; /// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has -/// to be declared in front of them. Stereo and [`OPUS_RATE`] only -- the caller -/// checks both, because outside that pair this encoder is not one this project -/// is willing to write files with ([`OPUS_MAX_KBPS`]). +/// to be declared in front of them. Mono or stereo, at [`OPUS_RATE`] -- the +/// caller checks all of it, because outside that envelope this encoder is not +/// one this project is willing to write files with ([`OPUS_MAX_KBPS`]). /// /// The tail frame is padded with silence rather than dropped: Opus codes whole /// frames and a track a few milliseconds short under a picture that is not is /// the drift every other path here is written to avoid. The pre-skip trims the /// front; the container's duration trims the back. -fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result, u16)>> { - let mut encoder = opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio) - .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))?; - encoder.bitrate_bps = (kbps.min(OPUS_MAX_KBPS) * 1_000) as i32; - encoder.complexity = 10; +fn encode_opus( + samples: &[f32], + kbps: u32, + channels: usize, +) -> crate::Result, u16)>> { + let mut encoder = ec_opus::Encoder::new(OPUS_RATE, channels, ec_opus::Application::Audio) + .map_err(|e| format!("the Opus encoder refused 48 kHz {channels}-channel sound: {e}"))?; + // CBR, the crate's default: every packet exactly the rate's size. The old + // seat ran opus-rs's VBR; the gate below measures either, and a fixed + // packet size is the friendlier neighbour to a muxer's block budget. + encoder.set_bitrate(kbps.min(OPUS_MAX_KBPS) * 1_000); + // No complexity knob on this crate: the reference's default (9) is baked + // into its rate arithmetic, one percent of equiv rate away from the 10 the + // old encoder was asked for. let mut packets = Vec::new(); - let mut frame = vec![0f32; OPUS_FRAME * 2]; + let mut frame = vec![0f32; OPUS_FRAME * channels]; // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is - // that with room for the TOC and a padded frame, so `encode` never has to - // refuse for want of a buffer. + // that with room for the TOC and a padded frame, so `encode_float` never + // has to refuse for want of a buffer. let mut out = vec![0u8; 1500]; // The head, coded **twice**. An encoder's very first frame has no history // behind it and comes out ramped and out of phase -- measured on a 440 Hz @@ -2170,19 +2186,19 @@ fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result crate::Result f64 { +fn opus_fidelity( + packets: &[crate::AacPacket], + samples: &[f32], + pre_skip: usize, + channels: usize, +) -> f64 { // Short enough to hear all of: every fixture, every unit test, and any // track under a minute. There is nothing to sample from. let all = FIDELITY_WINDOW * FIDELITY_WINDOWS; if packets.len() <= all { - return window_fidelity(packets, samples, pre_skip, 0, 0, packets.len()).unwrap_or(1.0); + return window_fidelity(packets, samples, pre_skip, channels, 0, 0, packets.len()) + .unwrap_or(1.0); } // Evenly spread, first window at the head: the head is where an encoder's // own warm-up would show, and the last starts a window short of the end so @@ -2285,7 +2310,7 @@ fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize) let at = w * step; let from = at.saturating_sub(FIDELITY_WARMUP); let Some(fidelity) = - window_fidelity(packets, samples, pre_skip, from, at, at + FIDELITY_WINDOW) + window_fidelity(packets, samples, pre_skip, channels, from, at, at + FIDELITY_WINDOW) else { continue; // silence: nothing to correlate, and not a failure }; @@ -2306,24 +2331,31 @@ fn window_fidelity( packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize, + channels: usize, from: usize, measure: usize, to: usize, ) -> Option { - let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]); + let (streams, coupled, mapping) = match channels { + 1 => (1, 0, vec![0u8]), + // One coupled stream: the stereo shape every fixture and every mix + // here decodes back through. + _ => (1, 1, vec![0, 1]), + }; + let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, streams, coupled, &mapping); let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); // Where in the mix this window's first decoded sample lands: every packet // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream // owes before the first of them is the timeline's frame 0. - let mut at = (from * OPUS_FRAME * 2).saturating_sub(pre_skip * 2); - let mut drop = (pre_skip * 2).saturating_sub(from * OPUS_FRAME * 2); + let mut at = (from * OPUS_FRAME * channels).saturating_sub(pre_skip * channels); + let mut drop = (pre_skip * channels).saturating_sub(from * OPUS_FRAME * channels); let mut counted = 0usize; for (index, packet) in packets.iter().enumerate().take(to).skip(from) { let Ok(pcm) = decoder.decode_packet(&packet.bytes) else { return Some(0.0); }; let pcm = &pcm[drop.min(pcm.len())..]; - drop = drop.saturating_sub(packet.samples as usize * 2); + drop = drop.saturating_sub(packet.samples as usize * channels); // The warm-up is decoded for its state and not for its numbers. if index < measure { at += pcm.len(); @@ -4733,17 +4765,31 @@ mod tests { .collect() } + /// Three seconds of the same two tones summed onto one channel: the mono + /// mix `opus-rs 0.1.26` mis-encoded at every rate, which is why a mono + /// export kept the AAC path until `ec-opus` took the seat. + fn mono_tones(secs: usize) -> Vec { + (0..OPUS_RATE as usize * secs) + .map(|i| { + let t = i as f32 / OPUS_RATE as f32; + let tau = std::f32::consts::TAU; + 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin() + }) + .collect() + } + /// The best correlation of one channel of `got` against `want`, and the - /// offset it sat at. - fn align(want: &[f32], got: &[f32]) -> (f64, usize) { + /// offset it sat at. `stride` is the interleave width: 2 for the stereo + /// fixtures, 1 for mono. + fn align(want: &[f32], got: &[f32], stride: usize) -> (f64, usize) { let (mut best, mut at) = (-2.0, 0); let window = OPUS_RATE as usize; for lag in 0..1400 { let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); for (x, y) in want[..window] .iter() - .step_by(2) - .zip(got[lag * 2..].iter().step_by(2)) + .step_by(stride) + .zip(got[lag * stride..].iter().step_by(stride)) { num += f64::from(*x) * f64::from(*y); da += f64::from(*x) * f64::from(*x); @@ -4757,8 +4803,22 @@ mod tests { (best, at) } - fn ruopus_decode(packets: &[crate::AacPacket]) -> Vec { - let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]); + fn ec_decode(packets: &[crate::AacPacket]) -> Vec { + let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]); + let mut pcm = Vec::new(); + for packet in packets { + pcm.extend( + decoder + .decode_packet(&packet.bytes) + .expect("a valid packet"), + ); + } + pcm + } + + /// [`ec_decode`] for a mono packet stream: one stream, no coupling. + fn ec_decode_mono(packets: &[crate::AacPacket]) -> Vec { + let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 0, &[0]); let mut pcm = Vec::new(); for packet in packets { pcm.extend( @@ -4771,20 +4831,22 @@ mod tests { } /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and - /// why [`opus_fidelity`] exists at all -- all three measured here against - /// `ruopus`, the decoder this project reads every Opus file back with, and - /// which matches ffmpeg's libopus decode of a libopus file to correlation - /// 1.00000 on this very signal. + /// why [`opus_fidelity`] exists at all -- all three measured here through + /// the same decoder door the product reads every Opus file back with, the + /// decoder being the witness and the *encoder* the one under test. /// - /// The last third **asserts the bug**: at 256 kbps stereo `opus-rs 0.1.26` - /// writes packets that only its own decoder reads back, and pinning that - /// here is what makes a version bump that fixes it *fail* -- which is the - /// signal to raise the cap rather than a reason to widen it quietly. + /// The second half pins the two failures the seat's move here fixed: under + /// `opus-rs 0.1.26` the encoder wrote stereo packets that only its own + /// decoder read back above roughly 165 kbps (fidelity 0.06 at 256), and it + /// mis-encoded mono at every rate -- which is what the old 128 cap and the + /// mono-mix-keeps-AAC rule stood on. Both asserts are survival now, and a + /// regression fails here, loudly: that is the signal to lower + /// [`OPUS_MAX_KBPS`] again, not a reason to widen it quietly. #[test] fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() { let pcm = two_tones(3); for kbps in [96, OPUS_MAX_KBPS] { - let (packets, pre_skip) = encode_opus(&pcm, kbps) + let (packets, pre_skip) = encode_opus(&pcm, kbps, 2) .expect("the encoder opens") .expect("and inside the band it passes its own round trip"); assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16); @@ -4793,16 +4855,16 @@ mod tests { pcm.len().div_ceil(OPUS_FRAME * 2) + 2, "one packet per 20 ms frame, plus the warm-up and the flush" ); - let decoded = ruopus_decode(&packets); - let (c, lag) = align(&pcm, &decoded); + let decoded = ec_decode(&packets); + let (c, lag) = align(&pcm, &decoded, 2); // From the first audible sample, head included -- and the head is // why this is 0.98 and not the 0.999 below: the encoder's first - // audible 20 ms still comes out about 6 dB down whatever is fed in - // ahead of it (a second warm-up frame changes the numbers here in - // no decimal place), so that ramp is a property of `opus-rs 0.1.26` - // and is stated rather than hidden behind a loose threshold. + // audible 20 ms comes out a few dB down (one frame of cold start; + // a second warm-up frame changes the numbers in no decimal place), + // so that ramp is stated rather than hidden behind a loose + // threshold. assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}"); - let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..]); + let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..], 2); assert!( settled >= 0.999, "{kbps} kbps past the first frame: correlation {settled:.4}" @@ -4824,38 +4886,50 @@ mod tests { ); // The gate the export runs before it writes anything, on a track // that deserves to pass it. - let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip)); + let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip), 2); assert!( fidelity >= OPUS_MIN_FIDELITY, "{kbps} kbps scored {fidelity:.4} on its own round trip" ); } - // Above the band, straight at the crate, since `encode_opus` clamps: the - // packets come back as noise, and the gate says so. This is the check - // that the guard actually catches the failure it is built for -- and the - // one that fails, loudly, the day `opus-rs` fixes it. - let mut encoder = - opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio).unwrap(); - encoder.bitrate_bps = 256_000; - encoder.complexity = 10; - let mut out = vec![0u8; 1500]; - let packets: Vec = pcm - .chunks_exact(OPUS_FRAME * 2) - .map(|block| { - let len = encoder.encode(block, OPUS_FRAME, &mut out).unwrap(); - crate::AacPacket { - bytes: out[..len].to_vec(), - samples: OPUS_FRAME as u32, - } - }) - .collect(); - let fidelity = opus_fidelity(&packets, &pcm, usize::from(OPUS_PRE_SKIP)); - assert!( - fidelity < OPUS_MIN_FIDELITY, - "opus-rs now encodes 256 kbps stereo that a conformant decoder reads \ - back (fidelity {fidelity:.4}): raise OPUS_MAX_KBPS and delete this half" - ); + // Mono, the shape `opus-rs 0.1.26` mis-encoded at every rate and the + // reason a mono mix kept the AAC path: straight through the same seat, + // including at the rate where the old encoder was already writing + // stereo noise, let alone mono. + let mono = mono_tones(3); + for kbps in [96, 256] { + let (packets, pre_skip) = encode_opus(&mono, kbps, 1) + .expect("the encoder opens") + .expect("and mono passes its own round trip"); + assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16); + let decoded = ec_decode_mono(&packets); + let (c, lag) = align(&mono, &decoded, 1); + assert!( + c >= 0.98, + "mono at {kbps} kbps came back at correlation {c:.4}" + ); + let (settled, _) = align(&mono[OPUS_FRAME..], &decoded[OPUS_FRAME..], 1); + assert!( + settled >= 0.999, + "mono at {kbps} kbps past the first frame: correlation {settled:.4}" + ); + assert_eq!( + lag, + usize::from(pre_skip), + "mono at {kbps} kbps: the declared pre-skip is not where the sound starts" + ); + assert!( + decoded.len() - usize::from(pre_skip) >= mono.len(), + "mono at {kbps} kbps: the track ends {} samples short of the timeline", + mono.len() + usize::from(pre_skip) - decoded.len() + ); + let fidelity = opus_fidelity(&packets, &mono, usize::from(pre_skip), 1); + assert!( + fidelity >= OPUS_MIN_FIDELITY, + "mono at {kbps} kbps scored {fidelity:.4} on its own round trip" + ); + } } /// The gate on a track too long to listen to whole: it samples, and the @@ -4872,7 +4946,7 @@ mod tests { #[test] fn a_long_track_is_judged_by_the_middle_of_what_it_samples() { let pcm = two_tones(61); - let (packets, pre_skip) = encode_opus(&pcm, 96) + let (packets, pre_skip) = encode_opus(&pcm, 96, 2) .expect("the encoder opens") .expect("and passes its own round trip"); assert!( @@ -4881,7 +4955,7 @@ mod tests { packets.len() ); let pre_skip = usize::from(pre_skip); - let whole = opus_fidelity(&packets, &pcm, pre_skip); + let whole = opus_fidelity(&packets, &pcm, pre_skip, 2); assert!(whole >= OPUS_MIN_FIDELITY, "a good track scored {whole:.4}"); // One window's worth of the *mix* replaced by its own phase inverse: @@ -4896,7 +4970,7 @@ mod tests { for sample in &mut one_bad[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] { *sample = -*sample; } - let dip = opus_fidelity(&packets, &one_bad, pre_skip); + let dip = opus_fidelity(&packets, &one_bad, pre_skip, 2); assert!( dip >= OPUS_MIN_FIDELITY, "one ruined window sank the whole track ({dip:.4})" @@ -4909,7 +4983,7 @@ mod tests { for sample in &mut ruined[pcm.len() / 4..] { *sample = -*sample; } - let ruined = opus_fidelity(&packets, &ruined, pre_skip); + let ruined = opus_fidelity(&packets, &ruined, pre_skip, 2); assert!( ruined < OPUS_MIN_FIDELITY, "a track that is no longer the mix scored {ruined:.4}" @@ -4918,10 +4992,10 @@ mod tests { // ...and silence is silence: nothing to correlate is not a round trip // that failed. Short, because the floor is the same on either path. let quiet = vec![0f32; OPUS_RATE as usize * 2 * 2]; - let (packets, pre_skip) = encode_opus(&quiet, 96) + let (packets, pre_skip) = encode_opus(&quiet, 96, 2) .expect("the encoder opens") .expect("silence is written as Opus, not sent to AAC"); - let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip)); + let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip), 2); assert!( fidelity >= OPUS_MIN_FIDELITY, "a silent track scored {fidelity:.4} and would fall back to AAC" diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed75a72..ca7b2b3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -51,7 +51,7 @@ pub use project::{Clip, Project, Rate, Speed}; /// /// Exactly the containers the engine's audio path reads (`audio::AudioSession`), /// Opus included: `.opus` is an Ogg file symphonia's probe already reads and -/// `ruopus` now decodes, and `.mka` is the Matroska whose sound is all it +/// `ec-opus` decodes, and `.mka` is the Matroska whose sound is all it /// has. A `.dts` or a bare `.ac3` is refused by the same door that refuses a /// `.txt` -- there is no reader here that opens an elementary stream -- which is /// the honest answer. diff --git a/crates/engine/tests/audio_decode.rs b/crates/engine/tests/audio_decode.rs index bc1ac9f..ffdc631 100644 --- a/crates/engine/tests/audio_decode.rs +++ b/crates/engine/tests/audio_decode.rs @@ -202,7 +202,7 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() { /// Opus, which used to be the codec the refusal string was *for*: a standalone /// `.opus`, the `.webm` sound off the web, and the 5.1 in an `.mka` that a film /// soundtrack is -- four Opus streams with a channel mapping table, decoded by -/// `ruopus` and folded to stereo by the same fold the AC-3 and AAC paths use. +/// `ec-opus` and folded to stereo by the same fold the AC-3 and AAC paths use. /// /// The 5.1 fixture is the channel-order check as well: its tone is in FL and BR /// and silent in between, so both output channels carry sound only if the diff --git a/crates/engine/tests/capability_matrix.rs b/crates/engine/tests/capability_matrix.rs index a1f71c5..843951e 100644 --- a/crates/engine/tests/capability_matrix.rs +++ b/crates/engine/tests/capability_matrix.rs @@ -98,7 +98,7 @@ fn every_audio_codec_the_refusal_names_really_decodes() { // 5.1 film soundtrack is remuxed into, and the standalone `.opus`. It was // the last codec the notice named as absent while both readers here already // *parsed* it -- `A_OPUS` and `OpusHead` have always mapped to symphonia's - // `CODEC_ID_OPUS`; only the decoder was missing, and it is `ruopus` now. + // `CODEC_ID_OPUS`; only the decoder was missing, and it is `ec-opus` now. for (file, what, channels) in [ ("test_vp9.webm", "opus in a webm", 1), // 5.1 arrives as the stereo fold, exactly as a 5.1 AC-3 track does. diff --git a/crates/engine/tests/opus_export.rs b/crates/engine/tests/opus_export.rs index 23147b0..994f3ec 100644 --- a/crates/engine/tests/opus_export.rs +++ b/crates/engine/tests/opus_export.rs @@ -1,6 +1,6 @@ //! Opus on the way *out*: an edited Opus source leaves a Matroska export as //! Opus instead of being turned into AAC, and comes back in through this -//! project's own door -- symphonia's mkv reader for the container, `ruopus` for +//! project's own door -- symphonia's mkv reader for the container, `ec-opus` for //! the packets, which is the pair a film already plays through. //! //! Three claims, and each is measured rather than asserted from the code: @@ -12,9 +12,10 @@ //! * a timeline nobody has touched still *copies* its AAC packets rather than //! taking the new encoder: Opus is what an edit costs, never what a passthrough //! costs; -//! * and the envelope itself -- 48 kHz, stereo, at most -//! `OPUS_MAX_KBPS` -- is a measurement of `opus-rs 0.1.26` and is pinned here, -//! so the day the crate is bumped past its high-rate bug this suite says so. +//! * and the envelope itself -- 48 kHz, mono or stereo, at most +//! `OPUS_MAX_KBPS` -- is measured here: the high band and the mono path are +//! exactly where `opus-rs 0.1.26`, the encoder this seat replaced, wrote +//! files only it could read back, and a regression fails here, loudly. //! //! Nothing here needs a GPU: the picture is 320x180 and HEVC's intra encoder is //! software by construction, so the whole file runs anywhere. Add @@ -33,8 +34,9 @@ use engine::scratch::Scratch; use engine::{AudioSession, Clip, ExportHandle, Project}; /// The picture: 320x180 at 24 fps, 30 s (`scripts/gen_fixtures.sh`). Its own -/// sound is mono Opus and is deliberately left off the audio lane -- see -/// [`a_mono_mix_keeps_the_aac_path`]. +/// sound is mono Opus and is deliberately left off the audio lane -- except by +/// the mono test, which puts it there on purpose +/// ([`a_mono_mix_leaves_as_opus_too`]). const VIDEO: &str = "test_seek_chirp.mkv"; /// The sound: 5.1 Opus, 440 Hz in FL and 880 Hz in BR, folded to stereo on the /// way to the timeline -- so the mix this export encodes *is* an Opus source's, @@ -135,7 +137,7 @@ fn export(name: &str, project: Project, video: &Path) -> Scratch { /// Interleaved samples of a written file through the engine's own reader: the /// door an import comes in through, and for an Opus track that is symphonia's -/// mkv reader handing `CodecPrivate` and blocks to `ruopus`. +/// mkv reader handing `CodecPrivate` and blocks to `ec-opus`. fn decode(path: &Path) -> (engine::AudioMeta, Vec) { let (meta, chunks) = AudioSession::open(path) .expect("reopen the export") @@ -255,7 +257,8 @@ fn an_edited_opus_source_leaves_a_matroska_export_as_opus() { the export is either not this sound or not in this place" ); // Past the first frame, where the encoder's cold start is behind it: - // 0.997 left and 0.993 right, measured, against 0.9948/0.9825 with the + // 0.997 left and 0.993 right, measured at 128 kbps under the seat's + // previous encoder (opus-rs 0.1.26), against 0.9948/0.9825 with the // head in. That gap *is* the ramp the pre-skip cannot cover, and it is // asserted from both sides so neither can drift unnoticed. let settled = corr(&w[OPUS_FRAME_SAMPLES..span], &g[OPUS_FRAME_SAMPLES..span]); @@ -264,13 +267,14 @@ fn an_edited_opus_source_leaves_a_matroska_export_as_opus() { "{name}: correlation {settled:.4} past the first frame" ); // ...and the head specifically, which is what the pre-skip and the - // warm-up frame are for. Measured at 128 kbps: 0.990 left, 0.953 right, - // where the same export with no warm-up frame scored 0.9788 left and a - // mis-declared pre-skip would score far less than either. The gap to the - // 0.99 above is one frame of cold start -- `opus-rs 0.1.26` opens about - // 6 dB down whatever is fed in ahead of it (two warm-up frames change - // this in no decimal place) -- so this threshold is that ramp stated - // rather than a shrug. + // warm-up frame are for. Measured at 128 kbps under that same + // previous encoder: 0.990 left, 0.953 right, where the same export + // with no warm-up frame scored 0.9788 left and a mis-declared + // pre-skip would score far less than either. The gap to the 0.99 + // above is one frame of cold start -- an encoder's first frame opens + // a few dB down whatever is fed in ahead of it, opus-rs 0.1.26 by + // about 6 dB, and two warm-up frames change this in no decimal + // place -- so this threshold is that ramp stated rather than a shrug. let head = corr(&w[..12_000], &g[..12_000]); assert!(head >= 0.94, "{name}: the first 250 ms correlate {head:.4}"); } @@ -311,21 +315,57 @@ fn an_untouched_timeline_still_copies_its_aac_into_an_mkv() { ); } -/// A mono mix keeps AAC, and that is a *measurement* and not a preference: -/// `opus-rs 0.1.26` mis-encodes mono at rates it is asked for here (see the -/// envelope test in `export.rs`), so the file that would play back wrong is -/// never written. `test_seek_chirp.mkv` carries mono Opus, which is exactly the -/// source that would tempt this path. +/// A mono mix leaves as Opus too, and that is a *measurement*: `opus-rs 0.1.26` +/// mis-encoded mono at every rate (see the envelope test in `export.rs`), which +/// is why this file used to assert the AAC path instead. `test_seek_chirp.mkv` +/// carries mono Opus, which is exactly the source that used to tempt this path +/// onto the rocks. #[test] -fn a_mono_mix_keeps_the_aac_path() { +fn a_mono_mix_leaves_as_opus_too() { let source = asset(VIDEO); let out = export("mono", project(&source, &source, 1), &source); let bytes = std::fs::read(&*out).expect("read the export back"); + let head = find(&bytes, b"OpusHead").expect("an OpusHead in the CodecPrivate"); + assert!( + find(&bytes, b"A_OPUS").is_some(), + "a mono mix is written as Opus" + ); + assert!(find(&bytes, b"A_AAC").is_none()); + assert_eq!(bytes[head + 9], 1, "OpusHead: mono"); + assert_eq!(bytes[head + 18], 0, "OpusHead: mapping family 0"); + + // ...and it is the sound that went in, in the right place: the same second + // of the same source, at lag zero, as the 5.1 test asks of its fixture. + let (meta, got) = decode(&out); + assert_eq!((meta.sample_rate, meta.channels), (48_000, 1)); + let want: Vec = { + let (_, chunks) = AudioSession::open_segments(asset(VIDEO), &[(1.0, 2.0)]) + .expect("open the source") + .expect("the source has sound"); + let mut s = Vec::new(); + for chunk in chunks { + s.extend(chunk.samples); + } + s + }; + assert!( + got.len() >= want.len() - 2 && got.len() <= want.len() + OPUS_FRAME_SAMPLES * 2, + "the track is {} samples where the timeline is {}", + got.len(), + want.len() + ); + let span = want.len().min(got.len()); + let aligned = corr(&want[..span], &got[..span]); + assert!( + aligned >= 0.98, + "correlation {aligned:.4} against the source at lag zero -- \ + the export is either not this sound or not in this place" + ); + let settled = corr(&want[OPUS_FRAME_SAMPLES..span], &got[OPUS_FRAME_SAMPLES..span]); assert!( - find(&bytes, b"A_AAC").is_some(), - "a mono mix is written as AAC" + settled >= 0.99, + "correlation {settled:.4} past the first frame" ); - assert!(find(&bytes, b"A_OPUS").is_none()); } /// A real library, not a fixture: a real Opus film, cut, exported, read back. diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 6f0b1b7..a8f641e 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -85,7 +85,7 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ # other VP9 file in the wild actually arrives: `V_VP9` used to fall through the # mkv track dispatch and be refused by name while the mp4 twin above decoded. # Opus audio because that is what a .webm carries -- the sound decodes here now -# (`ruopus`), and this is the webm cell of the Opus row in `capability_matrix`. +# (`ec-opus`), and this is the webm cell of the Opus row in `capability_matrix`. ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -f lavfi -i "sine=frequency=440:duration=2" \ -c:v libvpx-vp9 -b:v 2M -g 30 -pix_fmt yuv420p \