forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-opus-swap' (597e096): both Opus seats are ec-opus natives -- ruopus/opus-rs/spectrograms leave the tree, the 128 kbps cap (an opus-rs bug workaround) rises to 320 and mono is proven end to end; known-accepted: ~1.5x slower absolute encode/decode vs the FFT-built incumbents at >=88x realtime floor, lane-ecopus-perf queued to close it

Browse files at this commit

3d8112a58f757765a16f8b7137283c22df467042Ahmet Kaan GümüşParent: ba33df0597e096
Cargo.lockmodified+43 -167
@@ -1588,6 +1588,27 @@ version = "1.0.20"
1588 source = "registry+https://github.com/rust-lang/crates.io-index"1588 source = "registry+https://github.com/rust-lang/crates.io-index"
1589 checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"1589 checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
1590 1590
1591+[[package]]
1592+name = "ec-core"
1593+version = "0.1.0"
1594+
1595+[[package]]
1596+name = "ec-dsp"
1597+version = "0.1.0"
1598+dependencies = [
1599+ "ec-core",
1600+ "wide 1.7.0",
1601+]
1602+
1603+[[package]]
1604+name = "ec-opus"
1605+version = "0.1.0"
1606+dependencies = [
1607+ "ec-core",
1608+ "ec-dsp",
1609+ "wide 1.7.0",
1610+]
1611+
1591 [[package]]1612 [[package]]
1592 name = "edith"1613 name = "edith"
1593 version = "0.1.0"1614 version = "0.1.0"
@@ -1636,6 +1657,7 @@ checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
1636 name = "engine"1657 name = "engine"
1637 version = "0.1.0"1658 version = "0.1.0"
1638 dependencies = [1659 dependencies = [
1660+ "ec-opus",
1639 "flacenc",1661 "flacenc",
1640 "hound",1662 "hound",
1641 "image",1663 "image",
@@ -1643,7 +1665,6 @@ dependencies = [
1643 "libloading",1665 "libloading",
1644 "miniz_oxide",1666 "miniz_oxide",
1645 "mp4",1667 "mp4",
1646- "opus-rs",
1647 "oxideav-ac3",1668 "oxideav-ac3",
1648 "oxideav-ass",1669 "oxideav-ass",
1649 "oxideav-core",1670 "oxideav-core",
@@ -1652,7 +1673,6 @@ dependencies = [
1652 "oxideav-sub-image",1673 "oxideav-sub-image",
1653 "oxideav-subtitle",1674 "oxideav-subtitle",
1654 "rav1e",1675 "rav1e",
1655- "ruopus",
1656 "rusty_aac",1676 "rusty_aac",
1657 "rusty_h264",1677 "rusty_h264",
1658 "rusty_mp3",1678 "rusty_mp3",
@@ -3374,16 +3394,6 @@ dependencies = [
3374 "libc",3394 "libc",
3375 ]3395 ]
3376 3396
3377-[[package]]
3378-name = "matrixmultiply"
3379-version = "0.3.11"
3380-source = "registry+https://github.com/rust-lang/crates.io-index"
3381-checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
3382-dependencies = [
3383- "autocfg",
3384- "rawpointer",
3385-]
3386-
3387 [[package]]3397 [[package]]
3388 name = "maybe-rayon"3398 name = "maybe-rayon"
3389 version = "0.1.1"3399 version = "0.1.1"
@@ -3548,22 +3558,6 @@ dependencies = [
3548 "getrandom 0.2.17",3558 "getrandom 0.2.17",
3549 ]3559 ]
3550 3560
3551-[[package]]
3552-name = "ndarray"
3553-version = "0.17.2"
3554-source = "registry+https://github.com/rust-lang/crates.io-index"
3555-checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"
3556-dependencies = [
3557- "matrixmultiply",
3558- "num-complex",
3559- "num-integer",
3560- "num-traits",
3561- "portable-atomic",
3562- "portable-atomic-util",
3563- "rawpointer",
3564- "serde",
3565-]
3566-
3567 [[package]]3561 [[package]]
3568 name = "new_debug_unreachable"3562 name = "new_debug_unreachable"
3569 version = "1.0.6"3563 version = "1.0.6"
@@ -3634,34 +3628,6 @@ dependencies = [
3634 "memchr",3628 "memchr",
3635 ]3629 ]
3636 3630
3637-[[package]]
3638-name = "non-empty-iter"
3639-version = "0.3.1"
3640-source = "registry+https://github.com/rust-lang/crates.io-index"
3641-checksum = "ac123b8e4bd1fef3e8e972ba7a07f046ac6b608633ad761c61876b7197313f63"
3642-dependencies = [
3643- "non-zero-size",
3644-]
3645-
3646-[[package]]
3647-name = "non-empty-slice"
3648-version = "0.6.0"
3649-source = "registry+https://github.com/rust-lang/crates.io-index"
3650-checksum = "9935c822e11be79ef40f986558b00da0ff176b7c87ddf6d9fb8b9138a6112c20"
3651-dependencies = [
3652- "non-empty-iter",
3653- "non-zero-size",
3654- "ownership",
3655- "serde",
3656- "thiserror 2.0.20",
3657-]
3658-
3659-[[package]]
3660-name = "non-zero-size"
3661-version = "0.2.0"
3662-source = "registry+https://github.com/rust-lang/crates.io-index"
3663-checksum = "401b3a4027292c1c318fd2305783f791d5579d18e7143ef72d653bf0c29e6b36"
3664-
3665 [[package]]3631 [[package]]
3666 name = "noop_proc_macro"3632 name = "noop_proc_macro"
3667 version = "0.3.0"3633 version = "0.3.0"
@@ -3726,7 +3692,6 @@ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
3726 dependencies = [3692 dependencies = [
3727 "bytemuck",3693 "bytemuck",
3728 "num-traits",3694 "num-traits",
3729- "serde",
3730 ]3695 ]
3731 3696
3732 [[package]]3697 [[package]]
@@ -3990,12 +3955,6 @@ version = "0.2.0"
3990 source = "registry+https://github.com/rust-lang/crates.io-index"3955 source = "registry+https://github.com/rust-lang/crates.io-index"
3991 checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"3956 checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
3992 3957
3993-[[package]]
3994-name = "opus-rs"
3995-version = "0.1.26"
3996-source = "registry+https://github.com/rust-lang/crates.io-index"
3997-checksum = "b7f1ce2826529746cac003d7338e9c0f47cdd2979ba769c61cc26fdebc402f4c"
3998-
3999 [[package]]3958 [[package]]
4000 name = "ordered-stream"3959 name = "ordered-stream"
4001 version = "0.2.0"3960 version = "0.2.0"
@@ -4006,12 +3965,6 @@ dependencies = [
4006 "pin-project-lite",3965 "pin-project-lite",
4007 ]3966 ]
4008 3967
4009-[[package]]
4010-name = "ownership"
4011-version = "0.3.0"
4012-source = "registry+https://github.com/rust-lang/crates.io-index"
4013-checksum = "cfb1aeb68b9f2683ee3f83960c10668b37a8a640224ba1169697ee8fd1e906c1"
4014-
4015 [[package]]3968 [[package]]
4016 name = "oxideav-ac3"3969 name = "oxideav-ac3"
4017 version = "0.0.10"3970 version = "0.0.10"
@@ -4340,21 +4293,6 @@ version = "0.2.5"
4340 source = "registry+https://github.com/rust-lang/crates.io-index"4293 source = "registry+https://github.com/rust-lang/crates.io-index"
4341 checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"4294 checksum = "5da3b0203fd7ee5720aa0b5e790b591aa5d3f41c3ed2c34a3a393382198af2f7"
4342 4295
4343-[[package]]
4344-name = "portable-atomic"
4345-version = "1.15.0"
4346-source = "registry+https://github.com/rust-lang/crates.io-index"
4347-checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
4348-
4349-[[package]]
4350-name = "portable-atomic-util"
4351-version = "0.2.7"
4352-source = "registry+https://github.com/rust-lang/crates.io-index"
4353-checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
4354-dependencies = [
4355- "portable-atomic",
4356-]
4357-
4358 [[package]]4296 [[package]]
4359 name = "postage"4297 name = "postage"
4360 version = "0.5.0"4298 version = "0.5.0"
@@ -4400,15 +4338,6 @@ dependencies = [
4400 "syn 2.0.119",4338 "syn 2.0.119",
4401 ]4339 ]
4402 4340
4403-[[package]]
4404-name = "primal-check"
4405-version = "0.3.4"
4406-source = "registry+https://github.com/rust-lang/crates.io-index"
4407-checksum = "dc0d895b311e3af9902528fbb8f928688abbd95872819320517cc24ca6b2bd08"
4408-dependencies = [
4409- "num-integer",
4410-]
4411-
4412 [[package]]4341 [[package]]
4413 name = "proc-macro-crate"4342 name = "proc-macro-crate"
4414 version = "3.5.0"4343 version = "3.5.0"
@@ -4783,12 +4712,6 @@ dependencies = [
4783 "raw-window-handle",4712 "raw-window-handle",
4784 ]4713 ]
4785 4714
4786-[[package]]
4787-name = "rawpointer"
4788-version = "0.2.1"
4789-source = "registry+https://github.com/rust-lang/crates.io-index"
4790-checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
4791-
4792 [[package]]4715 [[package]]
4793 name = "rayon"4716 name = "rayon"
4794 version = "1.12.0"4717 version = "1.12.0"
@@ -4820,15 +4743,6 @@ dependencies = [
4820 "once_cell",4743 "once_cell",
4821 ]4744 ]
4822 4745
4823-[[package]]
4824-name = "realfft"
4825-version = "3.5.0"
4826-source = "registry+https://github.com/rust-lang/crates.io-index"
4827-checksum = "f821338fddb99d089116342c46e9f1fbf3828dba077674613e734e01d6ea8677"
4828-dependencies = [
4829- "rustfft",
4830-]
4831-
4832 [[package]]4746 [[package]]
4833 name = "reborrow"4747 name = "reborrow"
4834 version = "0.5.5"4748 version = "0.5.5"
@@ -4962,15 +4876,6 @@ version = "0.20.0"
4962 source = "registry+https://github.com/rust-lang/crates.io-index"4876 source = "registry+https://github.com/rust-lang/crates.io-index"
4963 checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"4877 checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97"
4964 4878
4965-[[package]]
4966-name = "ruopus"
4967-version = "0.1.2"
4968-source = "registry+https://github.com/rust-lang/crates.io-index"
4969-checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd"
4970-dependencies = [
4971- "spectrograms",
4972-]
4973-
4974 [[package]]4879 [[package]]
4975 name = "rust-embed"4880 name = "rust-embed"
4976 version = "8.12.0"4881 version = "8.12.0"
@@ -5028,20 +4933,6 @@ dependencies = [
5028 "semver",4933 "semver",
5029 ]4934 ]
5030 4935
5031-[[package]]
5032-name = "rustfft"
5033-version = "6.4.1"
5034-source = "registry+https://github.com/rust-lang/crates.io-index"
5035-checksum = "21db5f9893e91f41798c88680037dba611ca6674703c1a18601b01a72c8adb89"
5036-dependencies = [
5037- "num-complex",
5038- "num-integer",
5039- "num-traits",
5040- "primal-check",
5041- "strength_reduce",
5042- "transpose",
5043-]
5044-
5045 [[package]]4936 [[package]]
5046 name = "rustix"4937 name = "rustix"
5047 version = "0.38.44"4938 version = "0.38.44"
@@ -5150,7 +5041,7 @@ name = "rusty_h264-common"
5150 version = "0.9.1"5041 version = "0.9.1"
5151 dependencies = [5042 dependencies = [
5152 "bytemuck",5043 "bytemuck",
5153- "wide",5044+ "wide 0.7.33",
5154 ]5045 ]
5155 5046
5156 [[package]]5047 [[package]]
@@ -5233,6 +5124,15 @@ dependencies = [
5233 "bytemuck",5124 "bytemuck",
5234 ]5125 ]
5235 5126
5127+[[package]]
5128+name = "safe_arch"
5129+version = "1.2.0"
5130+source = "registry+https://github.com/rust-lang/crates.io-index"
5131+checksum = "42c6efa15875e6ecb39ca61fb0b0c1a40b84fac5a5ffe71eef7d1000c8eb3f5f"
5132+dependencies = [
5133+ "bytemuck",
5134+]
5135+
5236 [[package]]5136 [[package]]
5237 name = "same-file"5137 name = "same-file"
5238 version = "1.0.6"5138 version = "1.0.6"
@@ -5621,24 +5521,6 @@ dependencies = [
5621 "windows-sys 0.61.2",5521 "windows-sys 0.61.2",
5622 ]5522 ]
5623 5523
5624-[[package]]
5625-name = "spectrograms"
5626-version = "2.1.3"
5627-source = "registry+https://github.com/rust-lang/crates.io-index"
5628-checksum = "3ff1e83612f5a16e413dbfaf0381753b5eee714932fc95db19fe0974d5e6462b"
5629-dependencies = [
5630- "ndarray",
5631- "non-empty-slice",
5632- "num-complex",
5633- "num-traits",
5634- "once_cell",
5635- "pkg-config",
5636- "realfft",
5637- "regex",
5638- "rustfft",
5639- "thiserror 2.0.20",
5640-]
5641-
5642 [[package]]5524 [[package]]
5643 name = "spin"5525 name = "spin"
5644 version = "0.9.9"5526 version = "0.9.9"
@@ -5703,12 +5585,6 @@ version = "1.1.0"
5703 source = "registry+https://github.com/rust-lang/crates.io-index"5585 source = "registry+https://github.com/rust-lang/crates.io-index"
5704 checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"5586 checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
5705 5587
5706-[[package]]
5707-name = "strength_reduce"
5708-version = "0.2.4"
5709-source = "registry+https://github.com/rust-lang/crates.io-index"
5710-checksum = "fe895eb47f22e2ddd4dabc02bce419d2e643c8e3b585c78158b349195bc24d82"
5711-
5712 [[package]]5588 [[package]]
5713 name = "strict-num"5589 name = "strict-num"
5714 version = "0.1.1"5590 version = "0.1.1"
@@ -6540,16 +6416,6 @@ dependencies = [
6540 "once_cell",6416 "once_cell",
6541 ]6417 ]
6542 6418
6543-[[package]]
6544-name = "transpose"
6545-version = "0.2.3"
6546-source = "registry+https://github.com/rust-lang/crates.io-index"
6547-checksum = "1ad61aed86bc3faea4300c7aee358b4c6d0c8d6ccc36524c96e4c92ccf26e77e"
6548-dependencies = [
6549- "num-integer",
6550- "strength_reduce",
6551-]
6552-
6553 [[package]]6419 [[package]]
6554 name = "try-lock"6420 name = "try-lock"
6555 version = "0.2.5"6421 version = "0.2.5"
@@ -7078,7 +6944,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
7078 checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03"6944 checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03"
7079 dependencies = [6945 dependencies = [
7080 "bytemuck",6946 "bytemuck",
7081- "safe_arch",6947+ "safe_arch 0.7.4",
6948+]
6949+
6950+[[package]]
6951+name = "wide"
6952+version = "1.7.0"
6953+source = "registry+https://github.com/rust-lang/crates.io-index"
6954+checksum = "8cf05ca94c9fba0c51316899caa1d1e74a064fc310a5efa7375e614343d415be"
6955+dependencies = [
6956+ "bytemuck",
6957+ "safe_arch 1.2.0",
7082 ]6958 ]
7083 6959
7084 [[package]]6960 [[package]]
crates/engine/Cargo.tomlmodified+25 -46
@@ -35,7 +35,7 @@ mp4 = "0.14"
35 # rest of the ecosystem is built on.35 # rest of the ecosystem is built on.
36 miniz_oxide = "0.8"36 miniz_oxide = "0.8"
37 # The software H.264 pair, and the only software decoder this project has for37 # The software H.264 pair, and the only software decoder this project has for
38-# any format. Pinned exactly, like `ruopus` and `oxideav-ac3` below, because a38+# any format. Pinned exactly, like `oxideav-ac3` below, because a
39 # decoder is a bit-exactness dependency -- and 0.9.1 is where that stopped being39 # decoder is a bit-exactness dependency -- and 0.9.1 is where that stopped being
40 # a figure of speech. Measured 2026-08-12 against ffmpeg's own decode of a 1080p40 # a figure of speech. Measured 2026-08-12 against ffmpeg's own decode of a 1080p
41 # High and a 720p Main clip, 750 pictures between them: 0.8 matched it41 # High and a 720p Main clip, 750 pictures between them: 0.8 matched it
@@ -87,57 +87,36 @@ rusty_mp3 = "0.6"
87 # packet. This one does the whole pipeline. Its quirks are measured and worked87 # packet. This one does the whole pipeline. Its quirks are measured and worked
88 # around in [`crate::export::write_ogg`] -- read that before touching this line.88 # around in [`crate::export::write_ogg`] -- read that before touching this line.
89 rusty_vorbis = "0.1.1"89 rusty_vorbis = "0.1.1"
90-# The Opus decoder: pure Rust, MIT, no C and no FFI.
91-#
92-# `spectrograms` is not, as this line long claimed, "for its own analysis tools":
93-# it is the crate's *FFT backend*, and it is default-on because CELT synthesis is
94-# an N/4 complex FFT per block. Turned off -- which is what asking for `std`
95-# alone did -- `celt/mdct.rs` falls back to an O(n²) DFT evaluated in f64, and a
96-# 5.1 film soundtrack decodes at **0.95x realtime**: slower than playing it.
97-# With the backend on, the same file decodes at **104x** (7.1: 0.93x -> 112x,
98-# stereo: 10.4x -> 135x). The cost is fifteen pure-Rust crates (`spectrograms` ->
99-# `realfft`/`rustfft`, `ndarray`, `regex`), still no C and no `build.rs`.
100-# The output is *not* bit-identical to the DFT build -- FFT summation order
101-# differs -- but the two agree to 144 dB SNR (max |Δ| 3.7e-8, half an LSB at
102-# 24-bit) while *both* sit 93 dB from ffmpeg's own libopus decode of the same
103-# file. The change is 40 dB below the decoder's existing distance to the
104-# reference, i.e. inside float noise, and upstream says as much: Opus conformance
105-# is a quality threshold (`opus_compare`), not bit-exactness, and every
106-# bitstream-affecting computation stays exact either way.
107 # Symphonia has no Opus at any version -- its feature list stops at vorbis and90 # Symphonia has no Opus at any version -- its feature list stops at vorbis and
108 # there is no `symphonia-codec-opus` crate -- while both of its containers *read*91 # there is no `symphonia-codec-opus` crate -- while both of its containers *read*
109 # the format already: `A_OPUS` and `OpusHead` have always mapped to92 # the format already: `A_OPUS` and `OpusHead` have always mapped to
110 # `CODEC_ID_OPUS`. The decoder was the one missing half, and the reason a 5.193 # `CODEC_ID_OPUS`. The decoder was the one missing half, and the reason a 5.1
111 # Opus film played silent while its picture was fine.94 # Opus film played silent while its picture was fine.
112 #95 #
113-# Multistream is what decides which crate: a 5.1 track is four elementary Opus96+# Both Opus seats are `ec-opus`, the codec family built in the sibling
114-# streams in one packet, all but the last **self-delimited** (RFC 6716 App. B),97+# workspace this checkout expects beside it (`edith_codecs`): the multistream
115-# and this one strips that framing per stream (`multistream.rs:71`). The obvious98+# decoder a surround track needs -- a 5.1 packet is four elementary Opus
116-# sibling pick, `rusty-opus 0.9.1` -- same family as `rusty_aac`/`rusty_mp3`99+# streams, all but the last **self-delimited** (RFC 6716 App. B), and this one
117-# above -- hands each self-delimited slice to a decoder that parses it as an100+# strips that framing per stream -- and the CELT encoder the export seat codes
118-# ordinary packet, so every stream but the last decodes the length prefix as101+# with. The path is the first edge across that workspace boundary, and a path
119-# payload: measured on a real 5.1 Opus remux as full-scale noise at -13 dBFS102+# is the whole story: the family is not a registry crate, so there is no
120-# where the film is silent. This one matches ffmpeg's own decode of the same file to a103+# version to pin -- the working tree is exactly as pinned as a decoder that is
121-# correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3`104+# a bit-exactness dependency can be.
122-# below, because a decoder is a bit-exactness dependency.
123-ruopus = { version = "=0.1.2", default-features = false, features = ["std", "spectrograms"] }
124-# The Opus *encoder*, the other half of that pair: a pure-Rust port of libopus
125-# 1.6, BSD-3, `build.rs`-less and with **no dependencies at all** -- checked, not
126-# taken from the README (`cargo tree` is two lines; there is not one `.c`, `.h`
127-# or `.S` file in the crate). It is what lets an edited Opus source leave in a
128-# Matroska file as Opus instead of being downgraded to AAC on the way out.
129 #105 #
130-# Used inside a measured envelope, and that envelope is the whole reason this106+# What it replaced, and why the move is measured rather than hoped for:
131-# line is not simply "the encoder": 48 kHz **stereo** at **at most**107+# `ruopus 0.1.2` decoded (it matched ffmpeg's own decode of a real 5.1 Opus
132-# [`crate::export::OPUS_MAX_KBPS`]. Above roughly 165 kbps stereo this encoder108+# remux to correlation 1.0000 on all six channels) but ran the export
133-# writes packets that only its *own* decoder reads back -- `ruopus` decodes them109+# fidelity path's stereo decode at 0.2x real time (measured, 24.2 s for 121.5 s
134-# as noise (correlation 0.06 at 256 kbps against the source, 0.9999 at 160), and110+# of stereo), and `opus-rs 0.1.26` encoded -- into packets that only
135-# `ruopus` is not the suspect: it decodes ffmpeg's own libopus at 256 kbps to111+# its own decoder read back above roughly 165 kbps stereo, the edge moving with
136-# correlation 1.00000 on the same signal. Mono is worse and at every rate, which112+# the content (correlation 0.06 at 256 kbps against the source; its own round
137-# is why a mono mix keeps the AAC path. Both measured in113+# trip read 0.9999 at 160), and mono worse still at every rate. That is what
138-# `tests/opus_export.rs`, which fails the day the crate is unpinned onto a114+# held [`crate::export::OPUS_MAX_KBPS`] at 128 and a mono mix on the AAC path.
139-# version that has fixed it -- that is the upgrade signal.115+# Both replaced seats are measured where they used to fail: `export::tests`
140-opus-rs = "=0.1.26"116+# round-trips the top of the new band and the mono path, and
117+# `tests/opus_export.rs` exports and re-reads the files through this project's
118+# own decoder door.
119+ec-opus = { path = "../../../edith_codecs/crates/ec-opus" }
141 # The Ogg container, and the only new *name* here that is not a new crate tree:120 # The Ogg container, and the only new *name* here that is not a new crate tree:
142 # its one dependency is `oxideav-core`, which the AC-3 decoder above already121 # its one dependency is `oxideav-core`, which the AC-3 decoder above already
143 # pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the122 # pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the
@@ -154,7 +133,7 @@ symphonia-codec-aac = "0.6"
154 # `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of133 # `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of
155 # a Matroska video file is read, the picture having its own demuxer here.134 # a Matroska video file is read, the picture having its own demuxer here.
156 # There is no opus/ac3/dts feature at any symphonia version: AC-3 comes from135 # There is no opus/ac3/dts feature at any symphonia version: AC-3 comes from
157-# `oxideav-ac3` and Opus from `ruopus` above, both plugged into this crate's136+# `oxideav-ac3` and Opus from `ec-opus` above, both plugged into this crate's
158 # own readers, and DTS is the one that really is refused.137 # own readers, and DTS is the one that really is refused.
159 symphonia = { version = "0.6", default-features = false, features = [138 symphonia = { version = "0.6", default-features = false, features = [
160 "aac",139 "aac",
crates/engine/src/audio.rsmodified+4 -4
@@ -67,7 +67,7 @@ const EMPTY_EDIT: u64 = u32::MAX as u64;
67 /// symphonia's registry as this project enables it (see the feature list in67 /// symphonia's registry as this project enables it (see the feature list in
68 /// `Cargo.toml`) plus the two families no symphonia version carries and this68 /// `Cargo.toml`) plus the two families no symphonia version carries and this
69 /// project decodes anyway -- AC-3/E-AC-3 through `oxideav-ac3` ([`MkvAc3Track`])69 /// project decodes anyway -- AC-3/E-AC-3 through `oxideav-ac3` ([`MkvAc3Track`])
70-/// and Opus through `ruopus` ([`SymDecoder::Opus`]).70+/// and Opus through `ec-opus` ([`SymDecoder::Opus`]).
71 ///71 ///
72 /// Written down per container because capability is not one set: an mp4 video's72 /// Written down per container because capability is not one set: an mp4 video's
73 /// sound never reaches symphonia ([`Track::open`] answers before it), so it73 /// sound never reaches symphonia ([`Track::open`] answers before it), so it
@@ -1701,7 +1701,7 @@ impl SymTrack {
1701 /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 and1701 /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 and
1702 /// 7.1 tracks of a film, so those go to `rusty_aac` instead1702 /// 7.1 tracks of a film, so those go to `rusty_aac` instead
1703 /// ([`aac_decoder`]), and it has no Opus decoder at all, so that one goes to1703 /// ([`aac_decoder`]), and it has no Opus decoder at all, so that one goes to
1704- /// `ruopus`.1704+ /// `ec-opus` ([`SymDecoder::Opus`]).
1705 fn decoder(&self) -> crate::Result<SymDecoder> {1705 fn decoder(&self) -> crate::Result<SymDecoder> {
1706 let from = usize::from(self.source_channels);1706 let from = usize::from(self.source_channels);
1707 if self.params.codec == CODEC_ID_OPUS {1707 if self.params.codec == CODEC_ID_OPUS {
@@ -1709,7 +1709,7 @@ impl SymTrack {
1709 opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), from)?;1709 opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), from)?;
1710 // 48 kHz whatever the container says: that is the only rate Opus1710 // 48 kHz whatever the container says: that is the only rate Opus
1711 // decodes at, and the rate both readers declare for it.1711 // decodes at, and the rate both readers declare for it.
1712- let decoder = ruopus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping);1712+ let decoder = ec_opus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping);
1713 return Ok(SymDecoder::Opus(Box::new(decoder), from));1713 return Ok(SymDecoder::Opus(Box::new(decoder), from));
1714 }1714 }
1715 if self.params.codec == CODEC_ID_AAC {1715 if self.params.codec == CODEC_ID_AAC {
@@ -1840,7 +1840,7 @@ enum SymDecoder {
1840 /// Every Opus track, mono to 7.1: one multistream decoder -- the streams of1840 /// Every Opus track, mono to 7.1: one multistream decoder -- the streams of
1841 /// a packet, the channel mapping table and the routing between them are all1841 /// a packet, the channel mapping table and the routing between them are all
1842 /// its business -- and the same width.1842 /// its business -- and the same width.
1843- Opus(Box<ruopus::MultistreamDecoder>, usize),1843+ Opus(Box<ec_opus::MultistreamDecoder>, usize),
1844 }1844 }
1845 1845
1846 impl SymDecoder {1846 impl SymDecoder {
crates/engine/src/export.rsmodified+185 -111
@@ -859,7 +859,7 @@ fn audio_label(
859 // It is one line and 76 characters wide (`summary_head` in the app859 // It is one line and 76 characters wide (`summary_head` in the app
860 // has the test), which is why the condition is in this comment860 // has the test), which is why the condition is in this comment
861 // instead of in the string.861 // instead of in the string.
862- false if format.is_mkv() => "Opus · SW encode (opus-rs)",862+ false if format.is_mkv() => "Opus · SW encode (ec-opus)",
863 false => "AAC · SW encode (rusty_aac)",863 false => "AAC · SW encode (rusty_aac)",
864 },864 },
865 }865 }
@@ -881,10 +881,10 @@ fn measured_audio_label(
881 opus: bool,881 opus: bool,
882 ) -> &'static str {882 ) -> &'static str {
883 match (sound, opus) {883 match (sound, opus) {
884- (_, true) => "Opus · SW encode (opus-rs)",884+ (_, true) => "Opus · SW encode (ec-opus)",
885 // Encoded, into a container that would have carried Opus, and it is not885 // Encoded, into a container that would have carried Opus, and it is not
886- // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or the886+ // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or
887- // mix was not the 48 kHz stereo that seat is measured in.887+ // the mix was not 48 kHz at a width the seat is measured in.
888 (Some(false), false) if format.is_mkv() => "AAC · SW encode (rusty_aac)",888 (Some(false), false) if format.is_mkv() => "AAC · SW encode (rusty_aac)",
889 // `sound` is already what happened, not a prediction, so `copied` is889 // `sound` is already what happened, not a prediction, so `copied` is
890 // filled in and `ranged` never reaches the branch that reads it.890 // filled in and `ranged` never reaches the branch that reads it.
@@ -2020,29 +2020,30 @@ fn encode_audio(
2020 );2020 );
2021 2021
2022 // Opus where the container carries it and the mix is inside the envelope2022 // Opus where the container carries it and the mix is inside the envelope
2023- // this encoder was *measured* correct in ([`encode_opus`]): a Matroska file,2023+ // this encoder is *measured* correct in ([`encode_opus`]): a Matroska file,
2024- // 48 kHz, stereo. An Opus source edited into an mkv export therefore leaves2024+ // 48 kHz, mono or stereo. An Opus source edited into an mkv export
2025- // as Opus instead of being turned into AAC on the way out, which is the one2025+ // therefore leaves as Opus instead of being turned into AAC on the way
2026- // generation of loss an all-Opus timeline used to pay for being cut.2026+ // out, which is the one generation of loss an all-Opus timeline used to
2027+ // pay for being cut.
2027 //2028 //
2028 // Everything else falls through to the AAC below and is unchanged by this:2029 // Everything else falls through to the AAC below and is unchanged by this:
2029- // every mp4, a mono mix, a 44.1 kHz timeline. The rate is the mix's own --2030+ // every mp4, a 44.1 kHz timeline. The rate is the mix's own -- there is no
2030- // there is no resampler on this path, and inventing one to reach 48 kHz2031+ // resampler on this path, and inventing one to reach 48 kHz would resample
2031- // would resample a whole timeline to satisfy a codec, which is a bigger2032+ // a whole timeline to satisfy a codec, which is a bigger change to the
2032- // change to the sound than the codec is.2033+ // sound than the codec is.
2033 // ...and again before either encoder is entered: both of them run to the2034 // ...and again before either encoder is entered: both of them run to the
2034 // end of the mix without a checkpoint of their own, so this is the last2035 // end of the mix without a checkpoint of their own, so this is the last
2035 // moment a cancel costs seconds rather than the whole encode.2036 // moment a cancel costs seconds rather than the whole encode.
2036 cancelled(shared)?;2037 cancelled(shared)?;
2037 if mkv2038 if mkv
2038 && audio.sample_rate == OPUS_RATE2039 && audio.sample_rate == OPUS_RATE
2039- && channels == 22040+ && (1..=2).contains(&channels)
2040- && let Some((packets, pre_skip)) = encode_opus(&samples, kbps)?2041+ && let Some((packets, pre_skip)) = encode_opus(&samples, kbps, channels)?
2041 {2042 {
2042 return Ok(Some(ExportAudio {2043 return Ok(Some(ExportAudio {
2043 params: crate::AacTrackParams {2044 params: crate::AacTrackParams {
2044 freq_index,2045 freq_index,
2045- chan_conf: 2,2046+ chan_conf: channels as u8,
2046 sample_rate: OPUS_RATE,2047 sample_rate: OPUS_RATE,
2047 },2048 },
2048 packets,2049 packets,
@@ -2095,13 +2096,16 @@ pub(crate) const OPUS_RATE: u32 = 48_000;
2095 /// Matroska block timestamp in whole milliseconds is exact.2096 /// Matroska block timestamp in whole milliseconds is exact.
2096 const OPUS_FRAME: usize = 960;2097 const OPUS_FRAME: usize = 960;
2097 2098
2098-/// The most this project asks of `opus-rs`, in kbps, and why it is a cap rather2099+/// The most this project asks of the Opus encoder, in kbps, and why it is a cap
2099-/// than the four rates the Sound row offers: this encoder falls off a cliff at a2100+/// rather than the four rates the Sound row offers.
2100-/// rate that depends on the *content*, and above it a conformant decoder gets2101+///
2101-/// noise back. Measured on three one-second spans of a real 5.1 Opus film,2102+/// History, because the number moved once already and the reason it could is
2102-/// encoded here and decoded with `ruopus` -- which is not the suspect, since it2103+/// part of the record. Under `opus-rs 0.1.26` the ceiling was 128: that encoder
2103-/// decodes ffmpeg's own libopus at 256 kbps to correlation 1.00000 on the same2104+/// fell off a cliff at a rate that depended on the *content*, and above it a
2104-/// material:2105+/// conformant decoder got noise back. Measured on three one-second spans of a
2106+/// real 5.1 Opus film, encoded there and decoded with `ruopus` -- which was not
2107+/// the suspect, since it decoded ffmpeg's own libopus at 256 kbps to
2108+/// correlation 1.00000 on the same material:
2105 ///2109 ///
2106 /// ```text2110 /// ```text
2107 /// kbps 120 128 136 144 152 1602111 /// kbps 120 128 136 144 152 160
@@ -2111,18 +2115,21 @@ const OPUS_FRAME: usize = 960;
2111 /// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control)2115 /// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control)
2112 /// ```2116 /// ```
2113 ///2117 ///
2114-/// So: usable to 128, ruined by 136 on real film sound, and the pure-tone2118+/// So: usable to 128, ruined by 136 on real film sound -- and mono worse, at
2115-/// fixtures that first suggested a 165 kbps ceiling were simply easy material.2119+/// every rate, which is why a mono mix kept the AAC path entirely. `ec-opus`
2116-/// 128 kbps stereo Opus is around transparency anyway (libopus scores 0.9982120+/// has no such cliff: its own suite holds every rate of the format's table to
2117-/// there on the worst of those spans), so the cap costs nothing a listener has.2121+/// the reference decoders, mono, stereo and 5.1 alike, and this project
2118-/// It is still not *trusted*: every track is decoded again and measured before2122+/// re-measures the high band and the mono path where the old encoder failed
2119-/// it is written ([`opus_fidelity`]), because a cliff whose edge moves with the2123+/// (`the_opus_encoder_is_pinned_to_the_band_it_was_measured_in`).
2120-/// material is not something a constant can be safe against on its own.
2121 ///2124 ///
2122-/// corner-cut: the ceiling is this encoder's, not the format's. Upgrade path is a2125+/// It is still not *trusted*: every track is decoded again and measured before
2123-/// released `opus-rs` that survives its own high rates -- the unit test pins the2126+/// it is written ([`opus_fidelity`]), because a rate nobody measured on *your*
2124-/// failure, so it fails the day the bug is fixed and this can be raised.2127+/// sound is not something a constant can be safe against on its own.
2125-pub(crate) const OPUS_MAX_KBPS: u32 = 128;2128+/// The ceiling is the Sound row's ([`AUDIO_KBPS`]), not the format's 510 kbps:
2129+/// a rate nothing in the product can ask for is a rate nothing here measures.
2130+/// 320 covers the row honestly, including the 256 default
2131+/// ([`DEFAULT_AUDIO_KBPS`]) the old cap silently halved on a Matroska export.
2132+pub(crate) const OPUS_MAX_KBPS: u32 = 320;
2126 2133
2127 /// How well a track has to survive its own round trip to be written as Opus:2134 /// How well a track has to survive its own round trip to be written as Opus:
2128 /// the correlation between the mix and the decode of what was encoded from it.2135 /// 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;
2142 const OPUS_PRE_SKIP: u16 = 120;2149 const OPUS_PRE_SKIP: u16 = 120;
2143 2150
2144 /// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has2151 /// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has
2145-/// to be declared in front of them. Stereo and [`OPUS_RATE`] only -- the caller2152+/// to be declared in front of them. Mono or stereo, at [`OPUS_RATE`] -- the
2146-/// checks both, because outside that pair this encoder is not one this project2153+/// caller checks all of it, because outside that envelope this encoder is not
2147-/// is willing to write files with ([`OPUS_MAX_KBPS`]).2154+/// one this project is willing to write files with ([`OPUS_MAX_KBPS`]).
2148 ///2155 ///
2149 /// The tail frame is padded with silence rather than dropped: Opus codes whole2156 /// The tail frame is padded with silence rather than dropped: Opus codes whole
2150 /// frames and a track a few milliseconds short under a picture that is not is2157 /// frames and a track a few milliseconds short under a picture that is not is
2151 /// the drift every other path here is written to avoid. The pre-skip trims the2158 /// the drift every other path here is written to avoid. The pre-skip trims the
2152 /// front; the container's duration trims the back.2159 /// front; the container's duration trims the back.
2153-fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result<Option<(Vec<crate::AacPacket>, u16)>> {2160+fn encode_opus(
2154- let mut encoder = opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio)2161+ samples: &[f32],
2155- .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))?;2162+ kbps: u32,
2156- encoder.bitrate_bps = (kbps.min(OPUS_MAX_KBPS) * 1_000) as i32;2163+ channels: usize,
2157- encoder.complexity = 10;2164+) -> crate::Result<Option<(Vec<crate::AacPacket>, u16)>> {
2165+ let mut encoder = ec_opus::Encoder::new(OPUS_RATE, channels, ec_opus::Application::Audio)
2166+ .map_err(|e| format!("the Opus encoder refused 48 kHz {channels}-channel sound: {e}"))?;
2167+ // CBR, the crate's default: every packet exactly the rate's size. The old
2168+ // seat ran opus-rs's VBR; the gate below measures either, and a fixed
2169+ // packet size is the friendlier neighbour to a muxer's block budget.
2170+ encoder.set_bitrate(kbps.min(OPUS_MAX_KBPS) * 1_000);
2171+ // No complexity knob on this crate: the reference's default (9) is baked
2172+ // into its rate arithmetic, one percent of equiv rate away from the 10 the
2173+ // old encoder was asked for.
2158 let mut packets = Vec::new();2174 let mut packets = Vec::new();
2159- let mut frame = vec![0f32; OPUS_FRAME * 2];2175+ let mut frame = vec![0f32; OPUS_FRAME * channels];
2160 // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is2176 // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is
2161- // that with room for the TOC and a padded frame, so `encode` never has to2177+ // that with room for the TOC and a padded frame, so `encode_float` never
2162- // refuse for want of a buffer.2178+ // has to refuse for want of a buffer.
2163 let mut out = vec![0u8; 1500];2179 let mut out = vec![0u8; 1500];
2164 // The head, coded **twice**. An encoder's very first frame has no history2180 // The head, coded **twice**. An encoder's very first frame has no history
2165 // behind it and comes out ramped and out of phase -- measured on a 440 Hz2181 // 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<Option<(Vec<crate::A
2170 // once to warm the encoder, and thrown away again by the pre-skip: exactly2186 // once to warm the encoder, and thrown away again by the pre-skip: exactly
2171 // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.2187 // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.
2172 let coded = std::time::Instant::now();2188 let coded = std::time::Instant::now();
2173- let warm = samples.len().min(OPUS_FRAME * 2);2189+ let warm = samples.len().min(OPUS_FRAME * channels);
2174 // ...and one silent frame after the sound, for the same delay seen from the2190 // ...and one silent frame after the sound, for the same delay seen from the
2175 // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so2191 // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so
2176 // without a frame to push them out the last 2.5 ms of the timeline stay2192 // without a frame to push them out the last 2.5 ms of the timeline stay
2177 // inside it and the track ends short under a picture that does not.2193 // inside it and the track ends short under a picture that does not.
2178 let blocks = std::iter::once(&samples[..warm])2194 let blocks = std::iter::once(&samples[..warm])
2179- .chain(samples.chunks(OPUS_FRAME * 2))2195+ .chain(samples.chunks(OPUS_FRAME * channels))
2180 .chain(std::iter::once(&samples[..0]));2196 .chain(std::iter::once(&samples[..0]));
2181 for block in blocks {2197 for block in blocks {
2182 frame[..block.len()].copy_from_slice(block);2198 frame[..block.len()].copy_from_slice(block);
2183 frame[block.len()..].fill(0.0);2199 frame[block.len()..].fill(0.0);
2184 let len = encoder2200 let len = encoder
2185- .encode(&frame, OPUS_FRAME, &mut out)2201+ .encode_float(&frame, OPUS_FRAME, &mut out)
2186 .map_err(|e| format!("Opus encode failed: {e}"))?;2202 .map_err(|e| format!("Opus encode failed: {e}"))?;
2187 packets.push(crate::AacPacket {2203 packets.push(crate::AacPacket {
2188 bytes: out[..len].to_vec(),2204 bytes: out[..len].to_vec(),
@@ -2202,7 +2218,7 @@ fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result<Option<(Vec<crate::A
2202 let encoded = coded.elapsed().as_secs_f64();2218 let encoded = coded.elapsed().as_secs_f64();
2203 let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;2219 let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;
2204 let measured = std::time::Instant::now();2220 let measured = std::time::Instant::now();
2205- let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip));2221+ let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip), channels);
2206 eprintln!(2222 eprintln!(
2207 "export audio: Opus encode {encoded:.1} s, fidelity {fidelity:.4} measured in {:.1} s",2223 "export audio: Opus encode {encoded:.1} s, fidelity {fidelity:.4} measured in {:.1} s",
2208 measured.elapsed().as_secs_f64()2224 measured.elapsed().as_secs_f64()
@@ -2240,8 +2256,11 @@ const FIDELITY_FLOOR: f64 = 1e-9;
2240 /// cannot read is exactly what this is here to catch.2256 /// cannot read is exactly what this is here to catch.
2241 ///2257 ///
2242 /// **Sampled above a minute of sound, and the median window is the answer.**2258 /// **Sampled above a minute of sound, and the median window is the answer.**
2243-/// This decode is the whole cost of exporting a feature film: `ruopus` runs its2259+/// This decode was the whole cost of exporting a feature film under the
2244-/// inverse MDCT at 0.2x real time here (measured, 24.2 s for 121.5 s of stereo),2260+/// previous decoder: `ruopus` ran its inverse MDCT at 0.2x real time (measured,
2261+/// 24.2 s for 121.5 s of stereo; `ec-opus`, the decoder here now, is far
2262+/// quicker, and the sampling survives it because it costs almost nothing to
2263+/// keep),
2245 /// so judging every packet of a two-and-a-half-hour film costs half an hour2264 /// so judging every packet of a two-and-a-half-hour film costs half an hour
2246 /// before a byte of picture is written -- which is what it did, and what made a2265 /// before a byte of picture is written -- which is what it did, and what made a
2247 /// copy export that has no encoding to do at all sit at zero for twenty minutes.2266 /// copy export that has no encoding to do at all sit at zero for twenty minutes.
@@ -2269,12 +2288,18 @@ const FIDELITY_FLOOR: f64 = 1e-9;
2269 /// by a margin no single window can (0.998 against under 0.7) -- and a track2288 /// by a margin no single window can (0.998 against under 0.7) -- and a track
2270 /// under a minute is one window, where median and whole-track correlation are2289 /// under a minute is one window, where median and whole-track correlation are
2271 /// the same number the gate always used.2290 /// the same number the gate always used.
2272-fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize) -> f64 {2291+fn opus_fidelity(
2292+ packets: &[crate::AacPacket],
2293+ samples: &[f32],
2294+ pre_skip: usize,
2295+ channels: usize,
2296+) -> f64 {
2273 // Short enough to hear all of: every fixture, every unit test, and any2297 // Short enough to hear all of: every fixture, every unit test, and any
2274 // track under a minute. There is nothing to sample from.2298 // track under a minute. There is nothing to sample from.
2275 let all = FIDELITY_WINDOW * FIDELITY_WINDOWS;2299 let all = FIDELITY_WINDOW * FIDELITY_WINDOWS;
2276 if packets.len() <= all {2300 if packets.len() <= all {
2277- return window_fidelity(packets, samples, pre_skip, 0, 0, packets.len()).unwrap_or(1.0);2301+ return window_fidelity(packets, samples, pre_skip, channels, 0, 0, packets.len())
2302+ .unwrap_or(1.0);
2278 }2303 }
2279 // Evenly spread, first window at the head: the head is where an encoder's2304 // Evenly spread, first window at the head: the head is where an encoder's
2280 // own warm-up would show, and the last starts a window short of the end so2305 // 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)
2285 let at = w * step;2310 let at = w * step;
2286 let from = at.saturating_sub(FIDELITY_WARMUP);2311 let from = at.saturating_sub(FIDELITY_WARMUP);
2287 let Some(fidelity) =2312 let Some(fidelity) =
2288- window_fidelity(packets, samples, pre_skip, from, at, at + FIDELITY_WINDOW)2313+ window_fidelity(packets, samples, pre_skip, channels, from, at, at + FIDELITY_WINDOW)
2289 else {2314 else {
2290 continue; // silence: nothing to correlate, and not a failure2315 continue; // silence: nothing to correlate, and not a failure
2291 };2316 };
@@ -2306,24 +2331,31 @@ fn window_fidelity(
2306 packets: &[crate::AacPacket],2331 packets: &[crate::AacPacket],
2307 samples: &[f32],2332 samples: &[f32],
2308 pre_skip: usize,2333 pre_skip: usize,
2334+ channels: usize,
2309 from: usize,2335 from: usize,
2310 measure: usize,2336 measure: usize,
2311 to: usize,2337 to: usize,
2312 ) -> Option<f64> {2338 ) -> Option<f64> {
2313- let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);2339+ let (streams, coupled, mapping) = match channels {
2340+ 1 => (1, 0, vec![0u8]),
2341+ // One coupled stream: the stereo shape every fixture and every mix
2342+ // here decodes back through.
2343+ _ => (1, 1, vec![0, 1]),
2344+ };
2345+ let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, streams, coupled, &mapping);
2314 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);2346 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
2315 // Where in the mix this window's first decoded sample lands: every packet2347 // Where in the mix this window's first decoded sample lands: every packet
2316 // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream2348 // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream
2317 // owes before the first of them is the timeline's frame 0.2349 // owes before the first of them is the timeline's frame 0.
2318- let mut at = (from * OPUS_FRAME * 2).saturating_sub(pre_skip * 2);2350+ let mut at = (from * OPUS_FRAME * channels).saturating_sub(pre_skip * channels);
2319- let mut drop = (pre_skip * 2).saturating_sub(from * OPUS_FRAME * 2);2351+ let mut drop = (pre_skip * channels).saturating_sub(from * OPUS_FRAME * channels);
2320 let mut counted = 0usize;2352 let mut counted = 0usize;
2321 for (index, packet) in packets.iter().enumerate().take(to).skip(from) {2353 for (index, packet) in packets.iter().enumerate().take(to).skip(from) {
2322 let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {2354 let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {
2323 return Some(0.0);2355 return Some(0.0);
2324 };2356 };
2325 let pcm = &pcm[drop.min(pcm.len())..];2357 let pcm = &pcm[drop.min(pcm.len())..];
2326- drop = drop.saturating_sub(packet.samples as usize * 2);2358+ drop = drop.saturating_sub(packet.samples as usize * channels);
2327 // The warm-up is decoded for its state and not for its numbers.2359 // The warm-up is decoded for its state and not for its numbers.
2328 if index < measure {2360 if index < measure {
2329 at += pcm.len();2361 at += pcm.len();
@@ -4733,17 +4765,31 @@ mod tests {
4733 .collect()4765 .collect()
4734 }4766 }
4735 4767
4768+ /// Three seconds of the same two tones summed onto one channel: the mono
4769+ /// mix `opus-rs 0.1.26` mis-encoded at every rate, which is why a mono
4770+ /// export kept the AAC path until `ec-opus` took the seat.
4771+ fn mono_tones(secs: usize) -> Vec<f32> {
4772+ (0..OPUS_RATE as usize * secs)
4773+ .map(|i| {
4774+ let t = i as f32 / OPUS_RATE as f32;
4775+ let tau = std::f32::consts::TAU;
4776+ 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin()
4777+ })
4778+ .collect()
4779+ }
4780+
4736 /// The best correlation of one channel of `got` against `want`, and the4781 /// The best correlation of one channel of `got` against `want`, and the
4737- /// offset it sat at.4782+ /// offset it sat at. `stride` is the interleave width: 2 for the stereo
4738- fn align(want: &[f32], got: &[f32]) -> (f64, usize) {4783+ /// fixtures, 1 for mono.
4784+ fn align(want: &[f32], got: &[f32], stride: usize) -> (f64, usize) {
4739 let (mut best, mut at) = (-2.0, 0);4785 let (mut best, mut at) = (-2.0, 0);
4740 let window = OPUS_RATE as usize;4786 let window = OPUS_RATE as usize;
4741 for lag in 0..1400 {4787 for lag in 0..1400 {
4742 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);4788 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
4743 for (x, y) in want[..window]4789 for (x, y) in want[..window]
4744 .iter()4790 .iter()
4745- .step_by(2)4791+ .step_by(stride)
4746- .zip(got[lag * 2..].iter().step_by(2))4792+ .zip(got[lag * stride..].iter().step_by(stride))
4747 {4793 {
4748 num += f64::from(*x) * f64::from(*y);4794 num += f64::from(*x) * f64::from(*y);
4749 da += f64::from(*x) * f64::from(*x);4795 da += f64::from(*x) * f64::from(*x);
@@ -4757,8 +4803,22 @@ mod tests {
4757 (best, at)4803 (best, at)
4758 }4804 }
4759 4805
4760- fn ruopus_decode(packets: &[crate::AacPacket]) -> Vec<f32> {4806+ fn ec_decode(packets: &[crate::AacPacket]) -> Vec<f32> {
4761- let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);4807+ let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
4808+ let mut pcm = Vec::new();
4809+ for packet in packets {
4810+ pcm.extend(
4811+ decoder
4812+ .decode_packet(&packet.bytes)
4813+ .expect("a valid packet"),
4814+ );
4815+ }
4816+ pcm
4817+ }
4818+
4819+ /// [`ec_decode`] for a mono packet stream: one stream, no coupling.
4820+ fn ec_decode_mono(packets: &[crate::AacPacket]) -> Vec<f32> {
4821+ let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 0, &[0]);
4762 let mut pcm = Vec::new();4822 let mut pcm = Vec::new();
4763 for packet in packets {4823 for packet in packets {
4764 pcm.extend(4824 pcm.extend(
@@ -4771,20 +4831,22 @@ mod tests {
4771 }4831 }
4772 4832
4773 /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and4833 /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and
4774- /// why [`opus_fidelity`] exists at all -- all three measured here against4834+ /// why [`opus_fidelity`] exists at all -- all three measured here through
4775- /// `ruopus`, the decoder this project reads every Opus file back with, and4835+ /// the same decoder door the product reads every Opus file back with, the
4776- /// which matches ffmpeg's libopus decode of a libopus file to correlation4836+ /// decoder being the witness and the *encoder* the one under test.
4777- /// 1.00000 on this very signal.
4778 ///4837 ///
4779- /// The last third **asserts the bug**: at 256 kbps stereo `opus-rs 0.1.26`4838+ /// The second half pins the two failures the seat's move here fixed: under
4780- /// writes packets that only its own decoder reads back, and pinning that4839+ /// `opus-rs 0.1.26` the encoder wrote stereo packets that only its own
4781- /// here is what makes a version bump that fixes it *fail* -- which is the4840+ /// decoder read back above roughly 165 kbps (fidelity 0.06 at 256), and it
4782- /// signal to raise the cap rather than a reason to widen it quietly.4841+ /// mis-encoded mono at every rate -- which is what the old 128 cap and the
4842+ /// mono-mix-keeps-AAC rule stood on. Both asserts are survival now, and a
4843+ /// regression fails here, loudly: that is the signal to lower
4844+ /// [`OPUS_MAX_KBPS`] again, not a reason to widen it quietly.
4783 #[test]4845 #[test]
4784 fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() {4846 fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() {
4785 let pcm = two_tones(3);4847 let pcm = two_tones(3);
4786 for kbps in [96, OPUS_MAX_KBPS] {4848 for kbps in [96, OPUS_MAX_KBPS] {
4787- let (packets, pre_skip) = encode_opus(&pcm, kbps)4849+ let (packets, pre_skip) = encode_opus(&pcm, kbps, 2)
4788 .expect("the encoder opens")4850 .expect("the encoder opens")
4789 .expect("and inside the band it passes its own round trip");4851 .expect("and inside the band it passes its own round trip");
4790 assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);4852 assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);
@@ -4793,16 +4855,16 @@ mod tests {
4793 pcm.len().div_ceil(OPUS_FRAME * 2) + 2,4855 pcm.len().div_ceil(OPUS_FRAME * 2) + 2,
4794 "one packet per 20 ms frame, plus the warm-up and the flush"4856 "one packet per 20 ms frame, plus the warm-up and the flush"
4795 );4857 );
4796- let decoded = ruopus_decode(&packets);4858+ let decoded = ec_decode(&packets);
4797- let (c, lag) = align(&pcm, &decoded);4859+ let (c, lag) = align(&pcm, &decoded, 2);
4798 // From the first audible sample, head included -- and the head is4860 // From the first audible sample, head included -- and the head is
4799 // why this is 0.98 and not the 0.999 below: the encoder's first4861 // why this is 0.98 and not the 0.999 below: the encoder's first
4800- // audible 20 ms still comes out about 6 dB down whatever is fed in4862+ // audible 20 ms comes out a few dB down (one frame of cold start;
4801- // ahead of it (a second warm-up frame changes the numbers here in4863+ // a second warm-up frame changes the numbers in no decimal place),
4802- // no decimal place), so that ramp is a property of `opus-rs 0.1.26`4864+ // so that ramp is stated rather than hidden behind a loose
4803- // and is stated rather than hidden behind a loose threshold.4865+ // threshold.
4804 assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}");4866 assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}");
4805- let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..]);4867+ let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..], 2);
4806 assert!(4868 assert!(
4807 settled >= 0.999,4869 settled >= 0.999,
4808 "{kbps} kbps past the first frame: correlation {settled:.4}"4870 "{kbps} kbps past the first frame: correlation {settled:.4}"
@@ -4824,38 +4886,50 @@ mod tests {
4824 );4886 );
4825 // The gate the export runs before it writes anything, on a track4887 // The gate the export runs before it writes anything, on a track
4826 // that deserves to pass it.4888 // that deserves to pass it.
4827- let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip));4889+ let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip), 2);
4828 assert!(4890 assert!(
4829 fidelity >= OPUS_MIN_FIDELITY,4891 fidelity >= OPUS_MIN_FIDELITY,
4830 "{kbps} kbps scored {fidelity:.4} on its own round trip"4892 "{kbps} kbps scored {fidelity:.4} on its own round trip"
4831 );4893 );
4832 }4894 }
4833 4895
4834- // Above the band, straight at the crate, since `encode_opus` clamps: the4896+ // Mono, the shape `opus-rs 0.1.26` mis-encoded at every rate and the
4835- // packets come back as noise, and the gate says so. This is the check4897+ // reason a mono mix kept the AAC path: straight through the same seat,
4836- // that the guard actually catches the failure it is built for -- and the4898+ // including at the rate where the old encoder was already writing
4837- // one that fails, loudly, the day `opus-rs` fixes it.4899+ // stereo noise, let alone mono.
4838- let mut encoder =4900+ let mono = mono_tones(3);
4839- opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio).unwrap();4901+ for kbps in [96, 256] {
4840- encoder.bitrate_bps = 256_000;4902+ let (packets, pre_skip) = encode_opus(&mono, kbps, 1)
4841- encoder.complexity = 10;4903+ .expect("the encoder opens")
4842- let mut out = vec![0u8; 1500];4904+ .expect("and mono passes its own round trip");
4843- let packets: Vec<crate::AacPacket> = pcm4905+ assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);
4844- .chunks_exact(OPUS_FRAME * 2)4906+ let decoded = ec_decode_mono(&packets);
4845- .map(|block| {4907+ let (c, lag) = align(&mono, &decoded, 1);
4846- let len = encoder.encode(block, OPUS_FRAME, &mut out).unwrap();4908+ assert!(
4847- crate::AacPacket {4909+ c >= 0.98,
4848- bytes: out[..len].to_vec(),4910+ "mono at {kbps} kbps came back at correlation {c:.4}"
4849- samples: OPUS_FRAME as u32,4911+ );
4850- }4912+ let (settled, _) = align(&mono[OPUS_FRAME..], &decoded[OPUS_FRAME..], 1);
4851- })4913+ assert!(
4852- .collect();4914+ settled >= 0.999,
4853- let fidelity = opus_fidelity(&packets, &pcm, usize::from(OPUS_PRE_SKIP));4915+ "mono at {kbps} kbps past the first frame: correlation {settled:.4}"
4854- assert!(4916+ );
4855- fidelity < OPUS_MIN_FIDELITY,4917+ assert_eq!(
4856- "opus-rs now encodes 256 kbps stereo that a conformant decoder reads \4918+ lag,
4857- back (fidelity {fidelity:.4}): raise OPUS_MAX_KBPS and delete this half"4919+ usize::from(pre_skip),
4858- );4920+ "mono at {kbps} kbps: the declared pre-skip is not where the sound starts"
4921+ );
4922+ assert!(
4923+ decoded.len() - usize::from(pre_skip) >= mono.len(),
4924+ "mono at {kbps} kbps: the track ends {} samples short of the timeline",
4925+ mono.len() + usize::from(pre_skip) - decoded.len()
4926+ );
4927+ let fidelity = opus_fidelity(&packets, &mono, usize::from(pre_skip), 1);
4928+ assert!(
4929+ fidelity >= OPUS_MIN_FIDELITY,
4930+ "mono at {kbps} kbps scored {fidelity:.4} on its own round trip"
4931+ );
4932+ }
4859 }4933 }
4860 4934
4861 /// The gate on a track too long to listen to whole: it samples, and the4935 /// The gate on a track too long to listen to whole: it samples, and the
@@ -4872,7 +4946,7 @@ mod tests {
4872 #[test]4946 #[test]
4873 fn a_long_track_is_judged_by_the_middle_of_what_it_samples() {4947 fn a_long_track_is_judged_by_the_middle_of_what_it_samples() {
4874 let pcm = two_tones(61);4948 let pcm = two_tones(61);
4875- let (packets, pre_skip) = encode_opus(&pcm, 96)4949+ let (packets, pre_skip) = encode_opus(&pcm, 96, 2)
4876 .expect("the encoder opens")4950 .expect("the encoder opens")
4877 .expect("and passes its own round trip");4951 .expect("and passes its own round trip");
4878 assert!(4952 assert!(
@@ -4881,7 +4955,7 @@ mod tests {
4881 packets.len()4955 packets.len()
4882 );4956 );
4883 let pre_skip = usize::from(pre_skip);4957 let pre_skip = usize::from(pre_skip);
4884- let whole = opus_fidelity(&packets, &pcm, pre_skip);4958+ let whole = opus_fidelity(&packets, &pcm, pre_skip, 2);
4885 assert!(whole >= OPUS_MIN_FIDELITY, "a good track scored {whole:.4}");4959 assert!(whole >= OPUS_MIN_FIDELITY, "a good track scored {whole:.4}");
4886 4960
4887 // One window's worth of the *mix* replaced by its own phase inverse:4961 // One window's worth of the *mix* replaced by its own phase inverse:
@@ -4896,7 +4970,7 @@ mod tests {
4896 for sample in &mut one_bad[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] {4970 for sample in &mut one_bad[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] {
4897 *sample = -*sample;4971 *sample = -*sample;
4898 }4972 }
4899- let dip = opus_fidelity(&packets, &one_bad, pre_skip);4973+ let dip = opus_fidelity(&packets, &one_bad, pre_skip, 2);
4900 assert!(4974 assert!(
4901 dip >= OPUS_MIN_FIDELITY,4975 dip >= OPUS_MIN_FIDELITY,
4902 "one ruined window sank the whole track ({dip:.4})"4976 "one ruined window sank the whole track ({dip:.4})"
@@ -4909,7 +4983,7 @@ mod tests {
4909 for sample in &mut ruined[pcm.len() / 4..] {4983 for sample in &mut ruined[pcm.len() / 4..] {
4910 *sample = -*sample;4984 *sample = -*sample;
4911 }4985 }
4912- let ruined = opus_fidelity(&packets, &ruined, pre_skip);4986+ let ruined = opus_fidelity(&packets, &ruined, pre_skip, 2);
4913 assert!(4987 assert!(
4914 ruined < OPUS_MIN_FIDELITY,4988 ruined < OPUS_MIN_FIDELITY,
4915 "a track that is no longer the mix scored {ruined:.4}"4989 "a track that is no longer the mix scored {ruined:.4}"
@@ -4918,10 +4992,10 @@ mod tests {
4918 // ...and silence is silence: nothing to correlate is not a round trip4992 // ...and silence is silence: nothing to correlate is not a round trip
4919 // that failed. Short, because the floor is the same on either path.4993 // that failed. Short, because the floor is the same on either path.
4920 let quiet = vec![0f32; OPUS_RATE as usize * 2 * 2];4994 let quiet = vec![0f32; OPUS_RATE as usize * 2 * 2];
4921- let (packets, pre_skip) = encode_opus(&quiet, 96)4995+ let (packets, pre_skip) = encode_opus(&quiet, 96, 2)
4922 .expect("the encoder opens")4996 .expect("the encoder opens")
4923 .expect("silence is written as Opus, not sent to AAC");4997 .expect("silence is written as Opus, not sent to AAC");
4924- let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip));4998+ let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip), 2);
4925 assert!(4999 assert!(
4926 fidelity >= OPUS_MIN_FIDELITY,5000 fidelity >= OPUS_MIN_FIDELITY,
4927 "a silent track scored {fidelity:.4} and would fall back to AAC"5001 "a silent track scored {fidelity:.4} and would fall back to AAC"
crates/engine/src/lib.rsmodified+1 -1
@@ -51,7 +51,7 @@ pub use project::{Clip, Project, Rate, Speed};
51 ///51 ///
52 /// Exactly the containers the engine's audio path reads (`audio::AudioSession`),52 /// Exactly the containers the engine's audio path reads (`audio::AudioSession`),
53 /// Opus included: `.opus` is an Ogg file symphonia's probe already reads and53 /// Opus included: `.opus` is an Ogg file symphonia's probe already reads and
54-/// `ruopus` now decodes, and `.mka` is the Matroska whose sound is all it54+/// `ec-opus` decodes, and `.mka` is the Matroska whose sound is all it
55 /// has. A `.dts` or a bare `.ac3` is refused by the same door that refuses a55 /// has. A `.dts` or a bare `.ac3` is refused by the same door that refuses a
56 /// `.txt` -- there is no reader here that opens an elementary stream -- which is56 /// `.txt` -- there is no reader here that opens an elementary stream -- which is
57 /// the honest answer.57 /// the honest answer.
crates/engine/tests/audio_decode.rsmodified+1 -1
@@ -202,7 +202,7 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() {
202 /// Opus, which used to be the codec the refusal string was *for*: a standalone202 /// Opus, which used to be the codec the refusal string was *for*: a standalone
203 /// `.opus`, the `.webm` sound off the web, and the 5.1 in an `.mka` that a film203 /// `.opus`, the `.webm` sound off the web, and the 5.1 in an `.mka` that a film
204 /// soundtrack is -- four Opus streams with a channel mapping table, decoded by204 /// soundtrack is -- four Opus streams with a channel mapping table, decoded by
205-/// `ruopus` and folded to stereo by the same fold the AC-3 and AAC paths use.205+/// `ec-opus` and folded to stereo by the same fold the AC-3 and AAC paths use.
206 ///206 ///
207 /// The 5.1 fixture is the channel-order check as well: its tone is in FL and BR207 /// The 5.1 fixture is the channel-order check as well: its tone is in FL and BR
208 /// and silent in between, so both output channels carry sound only if the208 /// and silent in between, so both output channels carry sound only if the
crates/engine/tests/capability_matrix.rsmodified+1 -1
@@ -99,7 +99,7 @@ fn every_audio_codec_the_refusal_names_really_decodes() {
99 // 5.1 film soundtrack is remuxed into, and the standalone `.opus`. It was99 // 5.1 film soundtrack is remuxed into, and the standalone `.opus`. It was
100 // the last codec the notice named as absent while both readers here already100 // the last codec the notice named as absent while both readers here already
101 // *parsed* it -- `A_OPUS` and `OpusHead` have always mapped to symphonia's101 // *parsed* it -- `A_OPUS` and `OpusHead` have always mapped to symphonia's
102- // `CODEC_ID_OPUS`; only the decoder was missing, and it is `ruopus` now.102+ // `CODEC_ID_OPUS`; only the decoder was missing, and it is `ec-opus` now.
103 for (file, what, channels) in [103 for (file, what, channels) in [
104 ("test_vp9.webm", "opus in a webm", 1),104 ("test_vp9.webm", "opus in a webm", 1),
105 // 5.1 arrives as the stereo fold, exactly as a 5.1 AC-3 track does.105 // 5.1 arrives as the stereo fold, exactly as a 5.1 AC-3 track does.
crates/engine/tests/opus_export.rsmodified+64 -24
@@ -1,6 +1,6 @@
1 //! Opus on the way *out*: an edited Opus source leaves a Matroska export as1 //! 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 this2 //! 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` for3+//! 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.4 //! the packets, which is the pair a film already plays through.
5 //!5 //!
6 //! Three claims, and each is measured rather than asserted from the code:6 //! Three claims, and each is measured rather than asserted from the code:
@@ -12,9 +12,10 @@
12 //! * a timeline nobody has touched still *copies* its AAC packets rather than12 //! * 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 passthrough13 //! taking the new encoder: Opus is what an edit costs, never what a passthrough
14 //! costs;14 //! costs;
15-//! * and the envelope itself -- 48 kHz, stereo, at most15+//! * and the envelope itself -- 48 kHz, mono or stereo, at most
16-//! `OPUS_MAX_KBPS` -- is a measurement of `opus-rs 0.1.26` and is pinned here,16+//! `OPUS_MAX_KBPS` -- is measured here: the high band and the mono path are
17-//! so the day the crate is bumped past its high-rate bug this suite says so.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.
18 //!19 //!
19 //! Nothing here needs a GPU: the picture is 320x180 and HEVC's intra encoder is20 //! 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. Add21 //! software by construction, so the whole file runs anywhere. Add
@@ -33,8 +34,9 @@ use engine::scratch::Scratch;
33 use engine::{AudioSession, Clip, ExportHandle, Project};34 use engine::{AudioSession, Clip, ExportHandle, Project};
34 35
35 /// The picture: 320x180 at 24 fps, 30 s (`scripts/gen_fixtures.sh`). Its own36 /// 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 -- see37+/// sound is mono Opus and is deliberately left off the audio lane -- except by
37-/// [`a_mono_mix_keeps_the_aac_path`].38+/// the mono test, which puts it there on purpose
39+/// ([`a_mono_mix_leaves_as_opus_too`]).
38 const VIDEO: &str = "test_seek_chirp.mkv";40 const 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 the41 /// 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,42 /// 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 {
135 137
136 /// Interleaved samples of a written file through the engine's own reader: the138 /// 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's139 /// door an import comes in through, and for an Opus track that is symphonia's
138-/// mkv reader handing `CodecPrivate` and blocks to `ruopus`.140+/// mkv reader handing `CodecPrivate` and blocks to `ec-opus`.
139 fn decode(path: &Path) -> (engine::AudioMeta, Vec<f32>) {141 fn decode(path: &Path) -> (engine::AudioMeta, Vec<f32>) {
140 let (meta, chunks) = AudioSession::open(path)142 let (meta, chunks) = AudioSession::open(path)
141 .expect("reopen the export")143 .expect("reopen the export")
@@ -255,7 +257,8 @@ fn an_edited_opus_source_leaves_a_matroska_export_as_opus() {
255 the export is either not this sound or not in this place"257 the export is either not this sound or not in this place"
256 );258 );
257 // Past the first frame, where the encoder's cold start is behind it:259 // 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 the260+ // 0.997 left and 0.993 right, measured at 128 kbps under the seat's
261+ // previous encoder (opus-rs 0.1.26), against 0.9948/0.9825 with the
259 // head in. That gap *is* the ramp the pre-skip cannot cover, and it is262 // 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.263 // asserted from both sides so neither can drift unnoticed.
261 let settled = corr(&w[OPUS_FRAME_SAMPLES..span], &g[OPUS_FRAME_SAMPLES..span]);264 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() {
264 "{name}: correlation {settled:.4} past the first frame"267 "{name}: correlation {settled:.4} past the first frame"
265 );268 );
266 // ...and the head specifically, which is what the pre-skip and the269 // ...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,270+ // warm-up frame are for. Measured at 128 kbps under that same
268- // where the same export with no warm-up frame scored 0.9788 left and a271+ // previous encoder: 0.990 left, 0.953 right, where the same export
269- // mis-declared pre-skip would score far less than either. The gap to the272+ // with no warm-up frame scored 0.9788 left and a mis-declared
270- // 0.99 above is one frame of cold start -- `opus-rs 0.1.26` opens about273+ // pre-skip would score far less than either. The gap to the 0.99
271- // 6 dB down whatever is fed in ahead of it (two warm-up frames change274+ // above is one frame of cold start -- an encoder's first frame opens
272- // this in no decimal place) -- so this threshold is that ramp stated275+ // a few dB down whatever is fed in ahead of it, opus-rs 0.1.26 by
273- // rather than a shrug.276+ // about 6 dB, and two warm-up frames change this in no decimal
277+ // place -- so this threshold is that ramp stated rather than a shrug.
274 let head = corr(&w[..12_000], &g[..12_000]);278 let head = corr(&w[..12_000], &g[..12_000]);
275 assert!(head >= 0.94, "{name}: the first 250 ms correlate {head:.4}");279 assert!(head >= 0.94, "{name}: the first 250 ms correlate {head:.4}");
276 }280 }
@@ -311,21 +315,57 @@ fn an_untouched_timeline_still_copies_its_aac_into_an_mkv() {
311 );315 );
312 }316 }
313 317
314-/// A mono mix keeps AAC, and that is a *measurement* and not a preference:318+/// A mono mix leaves as Opus too, and that is a *measurement*: `opus-rs 0.1.26`
315-/// `opus-rs 0.1.26` mis-encodes mono at rates it is asked for here (see the319+/// mis-encoded mono at every rate (see the envelope test in `export.rs`), which
316-/// envelope test in `export.rs`), so the file that would play back wrong is320+/// is why this file used to assert the AAC path instead. `test_seek_chirp.mkv`
317-/// never written. `test_seek_chirp.mkv` carries mono Opus, which is exactly the321+/// carries mono Opus, which is exactly the source that used to tempt this path
318-/// source that would tempt this path.322+/// onto the rocks.
319 #[test]323 #[test]
320-fn a_mono_mix_keeps_the_aac_path() {324+fn a_mono_mix_leaves_as_opus_too() {
321 let source = asset(VIDEO);325 let source = asset(VIDEO);
322 let out = export("mono", project(&source, &source, 1), &source);326 let out = export("mono", project(&source, &source, 1), &source);
323 let bytes = std::fs::read(&*out).expect("read the export back");327 let bytes = std::fs::read(&*out).expect("read the export back");
328+ let head = find(&bytes, b"OpusHead").expect("an OpusHead in the CodecPrivate");
329+ assert!(
330+ find(&bytes, b"A_OPUS").is_some(),
331+ "a mono mix is written as Opus"
332+ );
333+ assert!(find(&bytes, b"A_AAC").is_none());
334+ assert_eq!(bytes[head + 9], 1, "OpusHead: mono");
335+ assert_eq!(bytes[head + 18], 0, "OpusHead: mapping family 0");
336+
337+ // ...and it is the sound that went in, in the right place: the same second
338+ // of the same source, at lag zero, as the 5.1 test asks of its fixture.
339+ let (meta, got) = decode(&out);
340+ assert_eq!((meta.sample_rate, meta.channels), (48_000, 1));
341+ let want: Vec<f32> = {
342+ let (_, chunks) = AudioSession::open_segments(asset(VIDEO), &[(1.0, 2.0)])
343+ .expect("open the source")
344+ .expect("the source has sound");
345+ let mut s = Vec::new();
346+ for chunk in chunks {
347+ s.extend(chunk.samples);
348+ }
349+ s
350+ };
351+ assert!(
352+ got.len() >= want.len() - 2 && got.len() <= want.len() + OPUS_FRAME_SAMPLES * 2,
353+ "the track is {} samples where the timeline is {}",
354+ got.len(),
355+ want.len()
356+ );
357+ let span = want.len().min(got.len());
358+ let aligned = corr(&want[..span], &got[..span]);
359+ assert!(
360+ aligned >= 0.98,
361+ "correlation {aligned:.4} against the source at lag zero -- \
362+ the export is either not this sound or not in this place"
363+ );
364+ let settled = corr(&want[OPUS_FRAME_SAMPLES..span], &got[OPUS_FRAME_SAMPLES..span]);
324 assert!(365 assert!(
325- find(&bytes, b"A_AAC").is_some(),366+ settled >= 0.99,
326- "a mono mix is written as AAC"367+ "correlation {settled:.4} past the first frame"
327 );368 );
328- assert!(find(&bytes, b"A_OPUS").is_none());
329 }369 }
330 370
331 /// A real library, not a fixture: a real Opus film, cut, exported, read back.371 /// A real library, not a fixture: a real Opus film, cut, exported, read back.
scripts/gen_fixtures.shmodified+1 -1
@@ -85,7 +85,7 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
85 # other VP9 file in the wild actually arrives: `V_VP9` used to fall through the85 # other VP9 file in the wild actually arrives: `V_VP9` used to fall through the
86 # mkv track dispatch and be refused by name while the mp4 twin above decoded.86 # mkv track dispatch and be refused by name while the mp4 twin above decoded.
87 # Opus audio because that is what a .webm carries -- the sound decodes here now87 # Opus audio because that is what a .webm carries -- the sound decodes here now
88-# (`ruopus`), and this is the webm cell of the Opus row in `capability_matrix`.88+# (`ec-opus`), and this is the webm cell of the Opus row in `capability_matrix`.
89 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \89 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
90 -f lavfi -i "sine=frequency=440:duration=2" \90 -f lavfi -i "sine=frequency=440:duration=2" \
91 -c:v libvpx-vp9 -b:v 2M -g 30 -pix_fmt yuv420p \91 -c:v libvpx-vp9 -b:v 2M -g 30 -pix_fmt yuv420p \