From cbad1feeb018b08ee99a5d071b894c8c6b67f920 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 13 Sep 2026 01:34:43 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A5=20chore(engine):=20rusty=5Faac=20l?= =?UTF-8?q?eaves=20the=20tree=20--=20the=20encode=20seat=20was=20its=20las?= =?UTF-8?q?t=20job=20and=20ec-aac=20took=20it=20in=20the=20previous=20comm?= =?UTF-8?q?it;=20vendor/rusty=5Faac=20git-rm'd,=20the=20[patch.crates-io]?= =?UTF-8?q?=20line=20and=20the=20workspace=20exclude=20row=20go=20with=20i?= =?UTF-8?q?t,=20Cargo.lock=20carries=20zero=20rusty=5Faac=20entries=20(its?= =?UTF-8?q?=20lock=20stanza=20was=20dependency-free,=20so=20nothing=20else?= =?UTF-8?q?=20moves),=20and=20the=20manifest=20keeps=20the=20record=20in?= =?UTF-8?q?=20the=20rusty=5Fh264-common=20style:=20a=20seventh=20vendor=20?= =?UTF-8?q?whose=20whole=20entry=20left=20with=20its=20last=20seat,=20its?= =?UTF-8?q?=20decoder=20IMDCT=20patch=20(N/4-point=20FFT=20through=20dsp::?= =?UTF-8?q?dct4,=2040x=20the=20matrix=20version)=20having=20served=20the?= =?UTF-8?q?=20decode=20seat=20ec-aac=20replaced=20first.=20Seat=20comments?= =?UTF-8?q?=20read=20past=20tense.=20Post-removal:=20-p=20engine=20--all-t?= =?UTF-8?q?argets=200=20warnings,=20lib=20suite=20375/375,=20export=208/8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 5 - Cargo.toml | 22 +- crates/engine/Cargo.toml | 15 +- crates/engine/tests/audio_seek.rs | 2 +- vendor/rusty_aac/Cargo.toml | 54 - vendor/rusty_aac/LICENSE | 201 -- vendor/rusty_aac/README.md | 280 -- vendor/rusty_aac/src/bits.rs | 99 - vendor/rusty_aac/src/codebook.rs | 258 -- vendor/rusty_aac/src/decode.rs | 871 ----- vendor/rusty_aac/src/dsp.rs | 461 --- vendor/rusty_aac/src/encode.rs | 4940 ----------------------------- vendor/rusty_aac/src/error.rs | 58 - vendor/rusty_aac/src/huffman.rs | 116 - vendor/rusty_aac/src/ics.rs | 175 - vendor/rusty_aac/src/latm.rs | 463 --- vendor/rusty_aac/src/lib.rs | 413 --- vendor/rusty_aac/src/sbr.rs | 405 --- vendor/rusty_aac/src/swb.rs | 129 - vendor/rusty_aac/src/tables.rs | 296 -- 20 files changed, 15 insertions(+), 9248 deletions(-) delete mode 100644 vendor/rusty_aac/Cargo.toml delete mode 100644 vendor/rusty_aac/LICENSE delete mode 100644 vendor/rusty_aac/README.md delete mode 100644 vendor/rusty_aac/src/bits.rs delete mode 100644 vendor/rusty_aac/src/codebook.rs delete mode 100644 vendor/rusty_aac/src/decode.rs delete mode 100644 vendor/rusty_aac/src/dsp.rs delete mode 100644 vendor/rusty_aac/src/encode.rs delete mode 100644 vendor/rusty_aac/src/error.rs delete mode 100644 vendor/rusty_aac/src/huffman.rs delete mode 100644 vendor/rusty_aac/src/ics.rs delete mode 100644 vendor/rusty_aac/src/latm.rs delete mode 100644 vendor/rusty_aac/src/lib.rs delete mode 100644 vendor/rusty_aac/src/sbr.rs delete mode 100644 vendor/rusty_aac/src/swb.rs delete mode 100644 vendor/rusty_aac/src/tables.rs diff --git a/Cargo.lock b/Cargo.lock index 181c0b6..323bc3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1724,7 +1724,6 @@ dependencies = [ "oxideav-sub-image", "oxideav-subtitle", "rav1e", - "rusty_aac", "rusty_mp3", "rusty_vorbis", "symphonia", @@ -5094,10 +5093,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" -[[package]] -name = "rusty_aac" -version = "0.5.0" - [[package]] name = "rusty_mp3" version = "0.6.1" diff --git a/Cargo.toml b/Cargo.toml index 1892e10..3b8179f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,6 @@ members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/a exclude = [ "vendor/cros-libva", "vendor/cros-codecs", - "vendor/rusty_aac", "vendor/oxideav-h265", "vendor/mp4", ] @@ -14,9 +13,9 @@ exclude = [ version = "0.1.0" edition = "2024" -# Five upstream crates vendored verbatim except for one clearly marked fix each, +# Four upstream crates vendored verbatim except for one clearly marked fix each, # all blockers on this machine and all still unfixed upstream as of -# 0.0.6/0.0.13/0.5.0/0.0.9/0.14: +# 0.0.6/0.0.13/0.0.9/0.14: # cros-libva - fails to build against libva >= 1.23 headers # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses; # and creates every decode context as 8-bit 4:2:0, which no HEVC @@ -47,13 +46,6 @@ edition = "2024" # (2.2 GB over a 719-frame export). Both are fixed in place # and marked LOCAL PATCH -# rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per -# term (the fast path in the same file serves the encoder only), -# which is 4x slower than real time for 5.1 and therefore not -# playable at all; the patch routes the IMDCT through the same -# N/4-point FFT the encoder's MDCT already uses (`dsp::dct4`), -# 40x the matrix version it started as -- 2 hours of 5.1 for a -# waveform in 2.4 minutes rather than an hour # oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and # refuses any dimension that is not a multiple of the 16-sample # CTB, so 1920x1080 could not be written at all; the patch adds @@ -78,11 +70,17 @@ edition = "2024" # authors' allocator installed itself as the process `#[global_allocator]` and # segfaulted the editor on a new thread's first allocation -- and once # `ec-h264` carried both H.264 seats there was nothing left to patch. -# Drop `vendor/` entirely once released versions handle all five. +# rusty_aac - a seventh vendor whose whole entry left with its last seat: +# `ec-aac`, the family's own, took the *encode* seat on +# 2026-09-13 after already carrying the decode one, and the +# vendored crate went with them. Its patch had routed the +# decoder's O(N^2) IMDCT through the encoder's N/4-point FFT +# (`dsp::dct4`, 40x the matrix version) so 5.1 was playable at +# all -- a fix for a crate the tree no longer carries. +# Drop `vendor/` entirely once released versions handle all four. [patch.crates-io] cros-libva = { path = "vendor/cros-libva" } cros-codecs = { path = "vendor/cros-codecs" } -rusty_aac = { path = "vendor/rusty_aac" } # Drops the `pub use proc_macro;` re-export (E0365 future-incompat, rustc # warns on every workspace build); nothing in the crate or its users names it. proc-macro-error2 = { path = "vendor/proc-macro-error2" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b0be18d..843eb74 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -61,9 +61,11 @@ ec-core = { path = "../../../edith_codecs/crates/ec-core" } # The multichannel AAC decode seat: symphonia's own refuses anything wider than # stereo outright (`aac/mod.rs:93`, "aac: aac too complex"), and a 5.1 or 7.1 # film soundtrack is exactly that. `ec-aac`, the family's own decoder, took the -# seat the vendored `rusty_aac` held -- it hands 5.1 back already reordered +# multichannel seat from `rusty_aac` -- it hands 5.1 back already reordered # into FL, FR, FC, LFE, BL, BR, the order the downmix in `audio` folds, the -# same one the seat always delivered. +# same one the seat always delivered. It took the *encode* seat too (the swap +# that removed `rusty_aac` from the tree): every re-encoded track's sound now +# leaves through `export.rs`'s `encode_audio` on this encoder. ec-aac = { path = "../../../edith_codecs/crates/ec-aac" } # The software AV1 decode seat, the project's own: a whole AV1 decoder # (entropy, prediction, transforms, loop filters, film grain) with no @@ -72,15 +74,6 @@ ec-aac = { path = "../../../edith_codecs/crates/ec-aac" } # stream (`decode::run_av1`), so peak memory is one output picture plus the # reference bank, and seeks stay the demuxer's job. ec-av1 = { path = "../../../edith_codecs/crates/ec-av1" } -# The AAC *encoder*, and its last seat in the tree: so an mp4's sound can be a -# mix rather than a copy, an equalized (or otherwise processed) lane has to be -# decoded, and what is decoded has to be encoded again. Pure Rust with no C or -# FFI, Apache-2.0, the same Mata Network family the retired `rusty_h264` came -# from. Nothing else in the ecosystem encodes AAC without linking Fraunhofer's -# C library, which this project's no-install rule forbids. Built from -# `vendor/rusty_aac` -- see the patch table in the workspace manifest. Its -# *decoder* left the tree when `ec-aac` above took the multichannel seat. -rusty_aac = "0.5" # The MP3 encoder, so that format is a row a user can pick rather than a licence # note: pure Rust, Apache-2.0, CBR and VBR. The decoder side of mp3 is # symphonia's below -- an mp3 has always been importable here, and until this it diff --git a/crates/engine/tests/audio_seek.rs b/crates/engine/tests/audio_seek.rs index 4786332..e44d7b0 100644 --- a/crates/engine/tests/audio_seek.rs +++ b/crates/engine/tests/audio_seek.rs @@ -256,7 +256,7 @@ fn a_seek_into_real_film_lands_on_the_second_it_asked_for() { } } -/// The 5.1 **AAC** film: the multichannel seat `ec-aac` took from the vendored +/// The 5.1 **AAC** film: the multichannel seat `ec-aac` took over from /// `rusty_aac`, exercised on the kind of track it exists for -- a BluRay /// remux's 48 kHz AAC-LC 5.1, decoded, folded to the pair the timeline /// carries, seeked across the film, and correlated against ffmpeg's own decode diff --git a/vendor/rusty_aac/Cargo.toml b/vendor/rusty_aac/Cargo.toml deleted file mode 100644 index b3c4012..0000000 --- a/vendor/rusty_aac/Cargo.toml +++ /dev/null @@ -1,54 +0,0 @@ -# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO -# -# When uploading crates to the registry Cargo will automatically -# "normalize" Cargo.toml files for maximal compatibility -# with all versions of Cargo and also rewrite `path` dependencies -# to registry (e.g., crates.io) dependencies. -# -# If you are reading this file be aware that the original Cargo.toml -# will likely look very different (and much more reasonable). -# See Cargo.toml.orig for the original contents. - -[package] -edition = "2021" -rust-version = "1.85" -name = "rusty_aac" -version = "0.5.0" -authors = ["Mata Network "] -build = false -autolib = false -autobins = false -autoexamples = false -autotests = false -autobenches = false -description = "Pure-Rust AAC-LC decoder + encoder, no C/FFI. ~5x faster than FFmpeg's native AAC encoder and beats it on mono music at 128k+ (PEAQ-measured). Level-invariant transient detection, joint stereo rate loop, ADTS/MP4/LATM-LOAS, 5.1 layouts, HE-AAC signalling." -homepage = "https://github.com/Remade-With-Rust/remade_ffmpeg_rs" -readme = "README.md" -keywords = [ - "aac", - "audio", - "codec", - "decoder", - "encoder", -] -categories = [ - "multimedia::audio", - "multimedia::encoding", -] -license = "Apache-2.0" -repository = "https://github.com/Remade-With-Rust/remade_ffmpeg_rs" - -[features] -default = ["simd"] -lab = [] -simd = [] -simd-avx512 = ["simd"] - -[lib] -name = "rusty_aac" -path = "src/lib.rs" - -[dependencies] - -# LOCAL: the crate's own `lab` examples and their allocator dev-dependency are -# not vendored -- only the library is, and only for its decoder. diff --git a/vendor/rusty_aac/LICENSE b/vendor/rusty_aac/LICENSE deleted file mode 100644 index 10e8866..0000000 --- a/vendor/rusty_aac/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or Derivative - Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and do - not modify the License. You may add Your own attribution notices - within Derivative Works that You distribute, alongside or as an - addendum to the NOTICE text from the Work, provided that such - additional attribution notices cannot be construed as modifying - the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2026 Mata Network - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/rusty_aac/README.md b/vendor/rusty_aac/README.md deleted file mode 100644 index 4a1ea4c..0000000 --- a/vendor/rusty_aac/README.md +++ /dev/null @@ -1,280 +0,0 @@ -# rusty_aac - -[![Remade With Rust](https://img.shields.io/badge/Remade%20With-Rust-000?logo=rust&logoColor=fff)](https://github.com/remade-with-rust) -[![By Mata Network](https://img.shields.io/badge/by-Mata%20Network-5b2be0)](https://www.mata.network) -[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/Remade-With-Rust/remade_ffmpeg_rs/blob/main/LICENSE) - -A pure-Rust **AAC-LC decoder and encoder**. Zero dependencies, no C, no FFI, -Apache-2.0. - -- **Decoder** — complete AAC-LC: long/short/transition windows with grouped - scalefactors, all spectral Huffman codebooks, M/S and intensity stereo, PNS, - TNS. Verified against FFmpeg: bit-exact on deterministic features. -- **Encoder** — to our knowledge the **first pure-Rust AAC encoder on - crates.io** (the alternatives, `fdk-aac` and libxaac bindings, are C FFI). - Psychoacoustic Bark-scale masking model, **level-invariant transient - detection**, block switching, per-band M/S stereo with a **joint pair rate - loop** routed by inter-channel correlation, frame-parallel encoding, an - N/4-FFT MDCT and AVX2 (opt-in AVX-512) quantize kernels. -- **Transport** — ADTS, MP4 `esds`, and **LATM/LOAS** (the MPEG-TS / broadcast - carriage format). -- **HE-AAC signalling** — SBR/PS configurations are recognised and the core is - decoded at the correct **output** rate (see [HE-AAC](#he-aac-sbr--ps)). -- `--no-default-features` turns off the runtime-detected SIMD kernels and gives - a **100%-safe scalar build** (every `unsafe` block in the crate is - feature-gated SIMD). - ---- - -## Measured against FFmpeg's AAC encoder - -Everything below is measured, reproducible, and generated by the harness in this -repo. **0.5.0 is a large quality step over 0.4.0 — a mean +0.33 ODG across the -whole corpus, with gains up to +2.6 ODG on the weakest content — while staying -~5x faster than FFmpeg.** - -
-How this was measured (click to expand) - -- **Encoders**: this crate via its CLI vs `ffmpeg -c:a aac` (FFmpeg's *native* - AAC encoder), FFmpeg 8.1.2. -- **Quality metric**: **PEAQ ODG** (ITU-R BS.1387), an external oracle, range - `[-4, 0]` where 0 is imperceptible. Our own NMR metric is *not* used for - ranking — a self-metric provably flatters the encoder it came from. -- **Fairness**: both candidates are decoded with the **same neutral decoder** - (system FFmpeg) before scoring, so the comparison isolates the encoders. -- **Null arm**: reference-vs-itself through the same path scores **+0.14 ODG**. - That is the harness ceiling — any score at or above it means *transparent*. -- **Speed**: both encoders run as subprocesses with identical invocation shape, - best-of-5, ABBA-interleaved, on 24 s clips. -- **Corpus**: real CC0/Public-Domain music (piano, guitar, vocal; mono and - stereo) plus a synthetic suite covering content classes the real corpus lacks. - Real and synthetic are reported separately and never averaged together. - -Reproduce: `python tools/quality/aac_vs_ffmpeg.py` in the -[main repo](https://github.com/Remade-With-Rust/remade_ffmpeg_rs). - -
- -### What changed in 0.5.0 - -Two measured wins shipped, four candidate tools **measured and rejected**. Δ is -`ours − ffmpeg`; positive = we sound better. - -| content | 0.4.0 (64/96/128/192k) | **0.5.0** | gain | -| --- | --- | --- | --- | -| **percussive** | -1.18 | -1.73 | -1.96 | -2.22 | **+0.49 | -0.01 | -0.17 | -0.31** | **up to +1.91** | -| **clean speech** | -2.03 | -2.90 | -3.05 | -2.79 | **-0.94 | -1.58 | -1.28 | -0.19** | **up to +2.61** | -| **guitar stereo** | -0.55 | -1.34 | -1.32 | -0.28 | **-0.31 | -0.46 | -0.15 | +0.35** | **up to +1.17** | -| piano stereo | -1.12 | -2.11 | -1.73 | -0.16 | -1.11 | -1.98 | -1.50 | -0.01 | up to +0.22 | - -**1. A level-invariant transient detector.** The previous detector guarded its -attack ratio with an *absolute* energy threshold, so it went blind on quiet -content — and because its running average decays between attacks, it flagged -percussive material **zero times at any level**. Every such frame coded as a long -block and took the full pre-echo hit. The replacement floors the average relative -to the clip's own energy. Measured mean **+0.267 ODG, worst class +0.000** — it -improves the two weakest classes and changes nothing anywhere else. - -**2. A joint stereo rate loop.** A channel pair's two channels each received a -fixed half of the frame budget and ran independent rate loops — so when M/S made -the side channel nearly empty, its bits were simply wasted while the mid channel -starved. On perfectly-correlated stereo (`L == R`) at 128 kbps that cost -**28 dB** of reconstruction SNR versus FFmpeg. 0.5.0 runs **one** rate loop over -the pair at a common base, so bits follow demand. It is **routed by inter-channel -correlation**, because the change is a large win on correlated stereo and a loss -on genuinely wide stereo. - -**Rejected after measurement** (all built, all measured, all off): TNS -(−0.148 mean, and it destroyed the percussive class), PNS (−0.056, damages real -tonal music), tonality-adaptive SMR (−0.049), intensity stereo (−0.004, neutral). -Shipping a tool that measures worse is not a feature. - -### Speed — 3.2–7.9× faster (mean 5.0×) - -| clip (24 s) | rusty_aac | FFmpeg native AAC | speed-up | -| --- | --- | --- | --- | -| piano | **214× realtime** | 57× realtime | **3.8×** | -| guitar | **306× realtime** | 39× realtime | **7.9×** | -| vocal | **299× realtime** | 93× realtime | **3.2×** | - -The 0.5.0 quality work cost no measurable speed. - -### Current standing, honestly - -| content | 64k | 96k | 128k | 192k | -| --- | --- | --- | --- | --- | -| piano (real, CC0) | -1.29 | -0.25 | **+0.28** | **+0.44** | -| guitar (real, PD) | -1.02 | -0.03 | **+0.65** | **+0.47** | -| vocal (real, PD) | -1.92 | -0.38 | **+0.39** | **+0.60** | -| guitar stereo | -0.31 | -0.46 | -0.15 | +0.35 | -| percussive | +0.49 | -0.01 | -0.17 | -0.31 | -| tonal music | +0.30 | -0.00 | -0.13 | -0.29 | - -- **We beat FFmpeg's native AAC on real mono music at ≥128 kbps**, reaching the - harness transparency ceiling while FFmpeg sits around −0.3 to −0.6. -- **Percussive and clean speech are no longer the disasters they were** — 0.4.0 - lost by up to 2.2 and 3.0 ODG; 0.5.0 wins percussive at 64 kbps. -- **We are still behind overall**, principally at ≤96 kbps, on piano stereo, and - on noise-like content. The encoder still has no bit reservoir, no VBR mode and - no absolute-threshold-of-hearing term; those are the next levers, tracked with - per-class evidence in - [`docs/codec-aac-quality-plan.md`](https://github.com/Remade-With-Rust/remade_ffmpeg_rs/blob/main/docs/codec-aac-quality-plan.md). -- **Rate caveat**: at the 64 k target we emit ~89% of FFmpeg's actual bitrate and - at 192 k ~107%, so neither extreme is a perfectly clean like-for-like. -- FFmpeg's native AAC encoder is not the strongest AAC encoder in existence - (libfdk-aac generally beats it); it is the one available in a permissive - default build. - -## Patents - -AAC-LC is the oldest, largely-expired, lowest-risk corner of the AAC family — -this crate implements **only AAC-LC coding tools**. It does not implement SBR, -Parametric Stereo or xHE-AAC, which carry much younger patents; the HE-AAC -support here is limited to *reading the configuration* and decoding the AAC-LC -core, with no SBR reconstruction. The code is independently written and -Apache-2.0-licensed, but **no patent license is granted or implied** by the -copyright license. If you distribute products commercially, consult IP counsel -about your own position; see the main repo's -[patent notes](https://github.com/Remade-With-Rust/remade_ffmpeg_rs/blob/main/docs/compatibility.md#patents). -This is engineering context, not legal advice. - -## Decode - -```rust -use rusty_aac::{AacDecoder, Error}; - -fn main() -> Result<(), Error> { - let adts = std::fs::read("input.aac").map_err(|e| Error::invalid(e.to_string()))?; - - // The decoder reads its configuration from the ADTS headers. For bare MP4 - // access units, build it from the esds config instead — prefer the raw-bytes - // form, which also recovers HE-AAC signalling: - // AacDecoder::with_config_bytes(&esds_payload)? - let mut dec = AacDecoder::new(); - - let mut pcm: Vec = Vec::new(); // interleaved, [-1, 1] - let mut pos = 0; - while pos + 7 <= adts.len() { - let hdr = rusty_aac::parse_adts(&adts[pos..])?; - let frame = dec.decode(&adts[pos..pos + hdr.frame_length], None)?; - println!("{} Hz, {} ch, {} samples", frame.sample_rate, frame.channels, frame.frames()); - pcm.extend_from_slice(&frame.samples); - pos += hdr.frame_length; - } - Ok(()) -} -``` - -## Encode - -```rust -use rusty_aac::{AacEncoder, AacEncoderConfig, AdtsHeader, Error}; - -fn main() -> Result<(), Error> { - // 1 s of a 440 Hz sine, mono 44.1 kHz, interleaved f32 in [-1, 1]. - let sr = 44_100u32; - let pcm: Vec = (0..sr) - .map(|i| (i as f32 / sr as f32 * 440.0 * std::f32::consts::TAU).sin() * 0.5) - .collect(); - - let mut enc = AacEncoder::new(AacEncoderConfig { - bitrate_bps: 128_000, - ..Default::default() - }); - enc.push_pcm(&pcm, 1, sr)?; - enc.finish(); // encodes everything, frame-parallel - - // Packets are raw access units; wrap each in ADTS for a playable .aac file - // (or hand `rusty_aac::audio_specific_config_bytes(sr, 1)` to an MP4 muxer - // as the esds DecoderSpecificInfo and store the packets raw). - let mut out = Vec::new(); - while let Ok(p) = enc.next_packet() { - out.extend_from_slice(&rusty_aac::write_adts_header(&AdtsHeader { - object_type: 2, // AAC-LC - sample_rate: sr, - channels: 1, - frame_length: 7 + p.data.len(), - header_len: 7, - })); - out.extend_from_slice(&p.data); - } - std::fs::write("tone.aac", &out).map_err(|e| Error::invalid(e.to_string()))?; - Ok(()) -} -``` - -## Channel layouts - -Mono through 5.1 (`channel_configuration` 1–6) are supported and emitted with the -**ISO-correct element sequence** — a 5.1 stream is `SCE, CPE, CPE, LFE` with the -channel reordering AAC requires, not six single-channel elements. Interleaved PCM -is taken in the standard order (`FL, FR, FC, LFE, BL, BR`) and returned in it. -Seven or more channels need a `program_config_element`, which is not implemented, -and are **rejected** rather than mis-encoded. - -## LATM / LOAS - -```rust -use rusty_aac::latm::{LatmReader, write_loas_frame}; - -// Parsing an MPEG-TS / broadcast stream. Use `LatmReader`, not the stateless -// helper: real streams send the StreamMuxConfig once and then set -// `useSameStreamMux` for long runs of frames. -let mut reader = LatmReader::new(); -// let frame = reader.parse(&loas_bytes)?; // -> config + raw access unit -``` - -## HE-AAC (SBR / PS) - -HE-AAC signalling is parsed in all three forms real streams use — explicit -hierarchical (`audioObjectType` 5/29), explicit backward-compatible (the `0x2B7` -sync extension), and implicit (SBR payload in the fill element). - -**The SBR high band is not reconstructed.** What this buys you is that an HE-AAC -stream decodes its AAC-LC core correctly and reports the true **output** sample -rate (twice the core rate) — without that, an HE-AAC stream plays at half speed. -`AacDecoder::sbr_support()` returns `SbrSupport::CoreOnly` so this is visible at -the API rather than discovered later. - -```rust -let dec = rusty_aac::AacDecoder::with_config_bytes(&esds_payload)?; -println!("{:?} at {:?} Hz", dec.sbr_support(), dec.output_sample_rate()); -``` - -## Features - -| feature | default | effect | -| --- | --- | --- | -| `simd` | yes | runtime-detected AVX2 quantize/`x^0.75` kernels (bit-exact vs scalar) | -| `simd-avx512` | no | adds an 8-lane AVX-512 tier (needs Rust ≥ 1.89; falls back at runtime) | -| `lab` | no | the quality lab: deterministic corpus, NMR metric, bitrate-ladder runner, WAV I/O. Dev/analysis only | - -## Part of Remade With Rust - -`rusty_aac` is the standalone AAC engine of -**[remade_ffmpeg_rs](https://github.com/Remade-With-Rust/remade_ffmpeg_rs)** — a -ground-up, permissively-licensed Rust rebuild of FFmpeg. Sister project: -**[FFAI](https://github.com/Remade-With-Rust/FFAI)** — media for an AI-first -world. More at **[github.com/remade-with-rust](https://github.com/remade-with-rust)**. - -Sibling codec crates: [`rusty_h264`](https://crates.io/crates/rusty_h264), -[`rusty_vp9`](https://crates.io/crates/rusty_vp9), -[`rusty_mp3`](https://crates.io/crates/rusty_mp3), -[`rusty-opus`](https://crates.io/crates/rusty-opus), [`rusty_vorbis`](https://crates.io/crates/rusty_vorbis), and the -[rusty-av1-toolkit](https://github.com/Remade-With-Rust/rusty-av1-toolkit) forks. - -## About Mata Network - - - -[Mata Network](https://www.mata.network) builds sovereign, self-hostable -infrastructure. **Remade With Rust** is our open-source home for the -permissively-licensed building blocks that work depends on. - - - -## License - -Apache-2.0. See -[LICENSE](https://github.com/Remade-With-Rust/remade_ffmpeg_rs/blob/main/LICENSE). diff --git a/vendor/rusty_aac/src/bits.rs b/vendor/rusty_aac/src/bits.rs deleted file mode 100644 index e9578e1..0000000 --- a/vendor/rusty_aac/src/bits.rs +++ /dev/null @@ -1,99 +0,0 @@ -//! MSB-first bit reader for AAC bitstreams. - -use crate::{Error, Result}; - -/// Reads bits most-significant-first from a byte slice (the order AAC uses). -pub struct BitReader<'a> { - data: &'a [u8], - /// Absolute bit position from the start of `data`. - pos: usize, -} - -impl<'a> BitReader<'a> { - pub fn new(data: &'a [u8]) -> BitReader<'a> { - BitReader { data, pos: 0 } - } - - /// Total bits remaining. - pub fn bits_left(&self) -> usize { - (self.data.len() * 8).saturating_sub(self.pos) - } - - /// Read a single bit. - pub fn read_bit(&mut self) -> Result { - let byte = self.pos / 8; - if byte >= self.data.len() { - return Err(Error::invalid("aac: bit reader past end of data")); - } - let shift = 7 - (self.pos % 8); - let bit = (self.data[byte] >> shift) & 1; - self.pos += 1; - Ok(bit as u32) - } - - /// Read `n` bits (0..=32) into a `u32`, MSB-first. - pub fn read_bits(&mut self, n: u32) -> Result { - if n > 32 { - return Err(Error::invalid("aac: read_bits > 32")); - } - let mut v = 0u32; - for _ in 0..n { - v = (v << 1) | self.read_bit()?; - } - Ok(v) - } - - /// Read one bit as a bool. - pub fn read_bool(&mut self) -> Result { - Ok(self.read_bit()? != 0) - } - - /// Skip `n` bits. - pub fn skip(&mut self, n: usize) -> Result<()> { - if self.pos + n > self.data.len() * 8 { - return Err(Error::invalid("aac: skip past end of data")); - } - self.pos += n; - Ok(()) - } - - /// Advance to the next byte boundary. - pub fn byte_align(&mut self) { - if self.pos % 8 != 0 { - self.pos += 8 - (self.pos % 8); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reads_bits_msb_first() { - // 0b1011_0010, 0b1100_0001 - let mut r = BitReader::new(&[0xB2, 0xC1]); - assert_eq!(r.read_bits(4).unwrap(), 0b1011); - assert_eq!(r.read_bits(4).unwrap(), 0b0010); - assert_eq!(r.read_bits(3).unwrap(), 0b110); - assert_eq!(r.read_bit().unwrap(), 0); - assert_eq!(r.read_bits(4).unwrap(), 0b0001); - assert_eq!(r.bits_left(), 0); - } - - #[test] - fn skip_and_align() { - let mut r = BitReader::new(&[0xFF, 0x0F]); - r.skip(4).unwrap(); - r.byte_align(); // jump to bit 8 - assert_eq!(r.read_bits(4).unwrap(), 0x0); - assert_eq!(r.read_bits(4).unwrap(), 0xF); - } - - #[test] - fn errors_past_end() { - let mut r = BitReader::new(&[0x00]); - assert!(r.read_bits(8).is_ok()); - assert!(r.read_bit().is_err()); - } -} diff --git a/vendor/rusty_aac/src/codebook.rs b/vendor/rusty_aac/src/codebook.rs deleted file mode 100644 index 545a320..0000000 --- a/vendor/rusty_aac/src/codebook.rs +++ /dev/null @@ -1,258 +0,0 @@ -//! AAC spectral Huffman codebooks: metadata + the index→coefficient decode -//! (ISO 14496-3 §4.6.3, Tables 4.A.2–4.A.13). -//! -//! Each codebook decodes a Huffman index into a 2- or 4-tuple of quantized -//! spectral coefficients. This module owns the *logic* — unpacking the index -//! into base-`modulo` digits, applying sign bits for the unsigned books, and -//! the codebook-11 escape sequence — all independent of the raw codeword -//! tables. The tables themselves (`HuffBook` per codebook) are fixed ISO data -//! transcribed separately; the decode here is what turns a correct lookup into -//! correct coefficients, and is verified with synthetic codebooks. - -#![allow(dead_code)] - -use crate::{Error, Result}; - -use crate::bits::BitReader; -use crate::huffman::HuffBook; - -/// Properties of one spectral Huffman codebook. -#[derive(Debug, Clone, Copy)] -pub struct Codebook { - /// Tuple size decoded per codeword: 4 (books 1–4) or 2 (books 5–11). - pub dim: u8, - /// `true` → magnitudes only; a sign bit follows each non-zero value. - pub unsigned: bool, - /// Largest absolute value the book codes directly (excludes escapes). - pub lav: u8, - /// `true` for book 11, which escape-codes values ≥ `lav`. - pub esc: bool, -} - -/// Codebook properties indexed by codebook number 0..=11 (0 = ZERO_HCB). -pub const CODEBOOKS: [Codebook; 12] = [ - Codebook { - dim: 0, - unsigned: false, - lav: 0, - esc: false, - }, // 0 ZERO - Codebook { - dim: 4, - unsigned: false, - lav: 1, - esc: false, - }, // 1 - Codebook { - dim: 4, - unsigned: false, - lav: 1, - esc: false, - }, // 2 - Codebook { - dim: 4, - unsigned: true, - lav: 2, - esc: false, - }, // 3 - Codebook { - dim: 4, - unsigned: true, - lav: 2, - esc: false, - }, // 4 - Codebook { - dim: 2, - unsigned: false, - lav: 4, - esc: false, - }, // 5 - Codebook { - dim: 2, - unsigned: false, - lav: 4, - esc: false, - }, // 6 - Codebook { - dim: 2, - unsigned: true, - lav: 7, - esc: false, - }, // 7 - Codebook { - dim: 2, - unsigned: true, - lav: 7, - esc: false, - }, // 8 - Codebook { - dim: 2, - unsigned: true, - lav: 12, - esc: false, - }, // 9 - Codebook { - dim: 2, - unsigned: true, - lav: 12, - esc: false, - }, // 10 - Codebook { - dim: 2, - unsigned: true, - lav: 16, - esc: true, - }, // 11 -]; - -/// First codebook number for intensity stereo (14, 15) and the special markers. -pub const ZERO_HCB: u8 = 0; -pub const ESC_HCB: u8 = 11; -pub const NOISE_HCB: u8 = 13; -pub const INTENSITY_HCB2: u8 = 14; -pub const INTENSITY_HCB: u8 = 15; - -/// Decode one codeword from `book` for codebook `cb` into `out[..cb.dim]`, -/// returning quantized (signed) coefficients. -pub fn decode_tuple( - cb: &Codebook, - book: &HuffBook, - r: &mut BitReader, - out: &mut [i32], -) -> Result<()> { - let idx = book.decode(r)?; - apply_index(cb, idx, r, out) -} - -/// Turn a decoded codebook `idx` into quantized coefficients, reading any sign -/// and escape bits that follow the codeword. Split out so it can be tested -/// directly with explicit indices. -pub fn apply_index(cb: &Codebook, idx: u16, r: &mut BitReader, out: &mut [i32]) -> Result<()> { - let dim = cb.dim as usize; - let modulo = if cb.unsigned { - cb.lav as u32 + 1 - } else { - 2 * cb.lav as u32 + 1 - }; - - // Unpack the Huffman index into `dim` base-`modulo` digits (MSB first). - let mut v = idx as u32; - let mut digits = [0u32; 4]; - for d in (0..dim).rev() { - digits[d] = v % modulo; - v /= modulo; - } - - // Map digits to coefficients (signed books offset by -lav). - for i in 0..dim { - out[i] = if cb.unsigned { - digits[i] as i32 - } else { - digits[i] as i32 - cb.lav as i32 - }; - } - - // Unsigned books: one sign bit per non-zero magnitude, in order. - if cb.unsigned { - for o in out.iter_mut().take(dim) { - if *o != 0 && r.read_bool()? { - *o = -*o; - } - } - } - - // Book 11: any magnitude equal to lav (16) is replaced by an escape value. - if cb.esc { - for o in out.iter_mut().take(dim) { - if o.unsigned_abs() == cb.lav as u32 { - let mag = read_escape(r)?; - *o = if *o < 0 { -mag } else { mag }; - } - } - } - Ok(()) -} - -/// Escape sequence (ISO 14496-3 §4.6.3.3): N leading 1-bits, a 0, then `N+4` -/// bits give `value = 2^(N+4) + word`. -fn read_escape(r: &mut BitReader) -> Result { - let mut n = 0u32; - while r.read_bool()? { - n += 1; - if n > 24 { - return Err(Error::invalid("aac: runaway escape sequence")); - } - } - let bits = n + 4; - let word = r.read_bits(bits)?; - Ok(((1u32 << bits) + word) as i32) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::tables::spectral_book; - - #[test] - fn signed_pair_offsets_by_lav() { - // cb5: dim2, signed, lav4 → modulo 9. index 56 → digits (6,2) → (2,-2). - let mut r = BitReader::new(&[]); // signed → no extra bits - let mut out = [0i32; 4]; - apply_index(&CODEBOOKS[5], 56, &mut r, &mut out).unwrap(); - assert_eq!(&out[..2], &[2, -2]); - } - - #[test] - fn unsigned_pair_reads_sign_bits() { - // cb7: dim2, unsigned, lav7 → modulo 8. index 24 → mags (3,0). - // The non-zero value reads one sign bit (1 → negative). - let mut r = BitReader::new(&[0x80]); - let mut out = [0i32; 4]; - apply_index(&CODEBOOKS[7], 24, &mut r, &mut out).unwrap(); - assert_eq!(&out[..2], &[-3, 0]); - } - - #[test] - fn book11_applies_escape_to_max_magnitude() { - // cb11: index 277 → mags (16,5). signs +,+; escape for 16: N=0, word - // 0011 → 16+3 = 19. bits: 0 0 0 0011 → 0000_0110 = 0x06. - let mut r = BitReader::new(&[0x06]); - let mut out = [0i32; 4]; - apply_index(&CODEBOOKS[11], 277, &mut r, &mut out).unwrap(); - assert_eq!(&out[..2], &[19, 5]); - } - - #[test] - fn escape_with_leading_ones() { - // cb11: index 272 → mags (16,0). sign(16)=+; escape: N=2 (110), word - // 000101 (=5) → 64+5 = 69. bits: 0 110 000101 → 0110_0001 0100_0000. - let mut r = BitReader::new(&[0x61, 0x40]); - let mut out = [0i32; 4]; - apply_index(&CODEBOOKS[11], 272, &mut r, &mut out).unwrap(); - assert_eq!(&out[..2], &[69, 0]); - } - - #[test] - fn metadata_matches_spec() { - assert!(CODEBOOKS[1].dim == 4 && !CODEBOOKS[1].unsigned && CODEBOOKS[1].lav == 1); - assert!(CODEBOOKS[3].unsigned && CODEBOOKS[3].lav == 2); - assert!(CODEBOOKS[5].dim == 2 && !CODEBOOKS[5].unsigned && CODEBOOKS[5].lav == 4); - assert!(CODEBOOKS[11].esc && CODEBOOKS[11].lav == 16); - } - - // End-to-end through the *real* codebook tables: Huffman lookup + unpack. - #[test] - fn real_codebook1_decodes_codewords() { - // cb1 (dim4, signed, lav1). codeword 0 (1 bit) → index 40 → (0,0,0,0). - let mut r = BitReader::new(&[0x00]); - let mut out = [9i32; 4]; - decode_tuple(&CODEBOOKS[1], spectral_book(1), &mut r, &mut out).unwrap(); - assert_eq!(out, [0, 0, 0, 0]); - - // codeword 0x011 (5 bits, 10001) → index 13 → digits (0,1,1,1) → (-1,0,0,0). - let mut r = BitReader::new(&[0x88]); // 1000_1000 - let mut out = [9i32; 4]; - decode_tuple(&CODEBOOKS[1], spectral_book(1), &mut r, &mut out).unwrap(); - assert_eq!(out, [-1, 0, 0, 0]); - } -} diff --git a/vendor/rusty_aac/src/decode.rs b/vendor/rusty_aac/src/decode.rs deleted file mode 100644 index 484b6e9..0000000 --- a/vendor/rusty_aac/src/decode.rs +++ /dev/null @@ -1,871 +0,0 @@ -//! AAC-LC decode assembly: `raw_data_block` → individual channels → spectral -//! reconstruction → filterbank → PCM (ISO 14496-3 §4.4 / §4.6). -//! -//! Supports long (`ONLY_LONG`), transition (`LONG_START`/`LONG_STOP`) and short -//! (`EIGHT_SHORT`) windows with grouped scalefactors/sections, regular Huffman -//! codebooks, pulse data and M/S stereo, synthesised via the verified IMDCT + -//! windowed overlap-add (2048 for long, 8×256 for short). Output is normalised -//! to float [-1, 1] and is bit-exact against FFmpeg on real AAC-LC files. -//! -//! **Tool coverage.** TNS is parsed *and applied* (`parse_tns` → `apply_tns`, on -//! both the SCE and CPE paths); PNS (`NOISE_HCB`) bands are filled with -//! energy-scaled noise; intensity stereo is applied via `apply_is`, including -//! the M/S sign flip. Only `gain_control_data` is rejected as unsupported. This -//! matters to the encoder campaign: the encoder-side arms for TNS, PNS and -//! intensity stereo (see `docs/codec-aac-great-gate.md`) can all be gated on -//! round-trip through this decoder, with no decode work needed first. - -use crate::bits::BitReader; -use crate::codebook::{decode_tuple, CODEBOOKS, INTENSITY_HCB2, NOISE_HCB, ZERO_HCB}; -use crate::dsp; -use crate::ics::{parse_ics_info, IcsInfo, WindowSequence}; -use crate::swb::swb_offsets; -use crate::tables::{spectral_book, SCALEFACTOR_BOOK}; -use crate::{DecodedAudio, Error, Result, SAMPLE_RATES}; - -const FRAME_LEN: usize = 1024; -const LONG_N: usize = 2048; -const SHORT_N: usize = 256; -const SHORT_HALF: usize = 128; -/// The ISO reconstruction is on a ~16-bit scale; normalise to float [-1, 1] -/// (verified bit-exact vs FFmpeg). -const OUTPUT_NORM: f32 = 1.0 / 32768.0; - -// raw_data_block element identifiers (id_syn_ele). -const ID_SCE: u32 = 0; -const ID_CPE: u32 = 1; -const ID_CCE: u32 = 2; -const ID_LFE: u32 = 3; -const ID_DSE: u32 = 4; -const ID_PCE: u32 = 5; -const ID_FIL: u32 = 6; -const ID_END: u32 = 7; - -/// Stateful AAC-LC decoder: holds per-channel overlap memory and the windows. -pub struct Decoder { - sample_rate: u32, - fs_index: u8, - /// Per-channel overlap-add memory (second half of the previous frame). - overlap: Vec<[f32; FRAME_LEN]>, - /// Per-channel previous window shape (false = sine, true = KBD). - prev_kbd: Vec, - /// Set when a fill_element carried SBR payload (implicit HE-AAC signalling). - saw_sbr: bool, - /// Per-channel previous window sequence. - prev_seq: Vec, - sine: Vec, - kbd: Vec, - sine_s: Vec, - kbd_s: Vec, - /// Deterministic PRNG state for PNS noise fill. - rng: u32, -} - -impl Decoder { - pub fn new(sample_rate: u32) -> Decoder { - Decoder { - sample_rate, - fs_index: fs_index_for(sample_rate), - overlap: Vec::new(), - prev_kbd: Vec::new(), - saw_sbr: false, - prev_seq: Vec::new(), - sine: dsp::sine_window(LONG_N), - kbd: dsp::kbd_window(LONG_N, 4.0), - sine_s: dsp::sine_window(SHORT_N), - kbd_s: dsp::kbd_window(SHORT_N, 6.0), - rng: 0x1234_5678, - } - } - - /// True once a `fill_element` carrying SBR payload has been seen — implicit - /// HE-AAC signalling. The core still decodes; the high band does not exist. - pub fn saw_sbr(&self) -> bool { - self.saw_sbr - } - - /// Decode one raw access unit into interleaved-`f32` PCM. - pub fn decode(&mut self, au: &[u8], pts: Option) -> Result { - let mut r = BitReader::new(au); - let mut outputs: Vec> = Vec::new(); - let mut ch = 0usize; - - loop { - if r.bits_left() < 3 { - break; - } - match r.read_bits(3)? { - ID_SCE | ID_LFE => { - let _tag = r.read_bits(4)?; - let mut c = decode_channel(&mut r, self.fs_index, None, &mut self.rng)?; - apply_tns(&mut c.spec, &c.tns, &c.info, self.fs_index); - outputs.push(self.synthesize(ch, &c.info, &c.spec)); - ch += 1; - } - ID_CPE => { - let _tag = r.read_bits(4)?; - let common = r.read_bool()?; - let (info, ms_used) = if common { - let info = parse_ics_info(&mut r, self.fs_index)?; - let ms = read_ms_used(&mut r, &info)?; - (Some(info), ms) - } else { - (None, Vec::new()) - }; - let info_ref = info.as_ref(); - let mut c0 = decode_channel(&mut r, self.fs_index, info_ref, &mut self.rng)?; - let mut c1 = decode_channel(&mut r, self.fs_index, info_ref, &mut self.rng)?; - let fs = self.fs_index; - // M/S and intensity stereo require a shared window/grouping. - if common { - apply_ms(&c0.info, &ms_used, fs, &c1.cb, &mut c0.spec, &mut c1.spec); - apply_is( - &c0.info, - &ms_used, - fs, - &c1.cb, - &c1.sf, - &c0.spec, - &mut c1.spec, - ); - } - apply_tns(&mut c0.spec, &c0.tns, &c0.info, fs); - apply_tns(&mut c1.spec, &c1.tns, &c1.info, fs); - outputs.push(self.synthesize(ch, &c0.info, &c0.spec)); - outputs.push(self.synthesize(ch + 1, &c1.info, &c1.spec)); - ch += 2; - } - ID_FIL => { - let mut count = r.read_bits(4)? as usize; - if count == 15 { - // count = 15 + next8 - 1; group as (count + next8) - 1 so a - // zero escape byte can't underflow usize (`0usize - 1` panics). - count = count + r.read_bits(8)? as usize - 1; - } - // Peek the 4-bit extension_type before skipping: SBR payload - // here is how *implicit* HE-AAC signalling works, where the - // config says nothing but the fill elements carry SBR anyway - // (a shape MPEG-TS broadcast really produces). Recording it - // lets the caller learn the output rate is doubled instead of - // being handed half-speed audio. - if count > 0 { - let ext = r.read_bits(4)?; - if ext == 13 || ext == 14 { - self.saw_sbr = true; - } - r.skip(count * 8 - 4)?; - } - } - ID_DSE => { - let _tag = r.read_bits(4)?; - let align = r.read_bool()?; - let mut count = r.read_bits(8)? as usize; - if count == 255 { - count += r.read_bits(8)? as usize; - } - if align { - r.byte_align(); - } - r.skip(count * 8)?; - } - ID_END => break, - ID_CCE | ID_PCE => { - return Err(Error::unsupported( - "aac: coupling / program-config elements not supported", - )); - } - _ => unreachable!(), - } - } - - if outputs.is_empty() { - return Err(Error::invalid("aac: no channel elements in frame")); - } - Ok(interleave(outputs, self.sample_rate, pts)) - } - - /// Build the 2048-sample analysis window for a long/transition block: left - /// half follows the previous block's shape, right half the current's. - fn long_window(&self, seq: WindowSequence, prev_kbd: bool, cur_kbd: bool) -> Vec { - let long_prev = if prev_kbd { &self.kbd } else { &self.sine }; - let long_cur = if cur_kbd { &self.kbd } else { &self.sine }; - let short_prev = if prev_kbd { &self.kbd_s } else { &self.sine_s }; - let short_cur = if cur_kbd { &self.kbd_s } else { &self.sine_s }; - let mut w = vec![0f32; LONG_N]; - - if seq == WindowSequence::LongStop { - for n in 0..128 { - w[448 + n] = short_prev[n]; - } - for s in w.iter_mut().take(FRAME_LEN).skip(576) { - *s = 1.0; - } - } else { - w[..FRAME_LEN].copy_from_slice(&long_prev[..FRAME_LEN]); - } - - if seq == WindowSequence::LongStart { - for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) { - *s = 1.0; - } - for n in 0..128 { - w[FRAME_LEN + 448 + n] = short_cur[128 + n]; - } - } else { - w[FRAME_LEN..].copy_from_slice(&long_cur[FRAME_LEN..]); - } - w - } - - /// Synthesise eight 256-IMDCT short windows into a normalised 2048 frame. - fn short_frame(&self, spec: &[f32; FRAME_LEN], cur_kbd: bool) -> Vec { - let sw = if cur_kbd { &self.kbd_s } else { &self.sine_s }; - let mut frame = vec![0f32; LONG_N]; - for w in 0..8 { - let time = dsp::imdct(&spec[w * SHORT_HALF..(w + 1) * SHORT_HALF]); // 256 - let off = 448 + w * SHORT_HALF; - for n in 0..SHORT_N { - frame[off + n] += time[n] * sw[n] * OUTPUT_NORM; - } - } - frame - } - - /// IMDCT + window + overlap-add for one channel's spectrum → 1024 samples. - fn synthesize(&mut self, ch: usize, info: &IcsInfo, spec: &[f32; FRAME_LEN]) -> Vec { - while self.overlap.len() <= ch { - self.overlap.push([0.0; FRAME_LEN]); - self.prev_kbd.push(false); - self.prev_seq.push(WindowSequence::OnlyLong); - } - - let frame = if info.window_sequence == WindowSequence::EightShort { - self.short_frame(spec, info.window_shape_kbd) - } else { - let time = dsp::imdct(spec); // 2048 - let win = self.long_window( - info.window_sequence, - self.prev_kbd[ch], - info.window_shape_kbd, - ); - (0..LONG_N) - .map(|n| time[n] * win[n] * OUTPUT_NORM) - .collect() - }; - - let mut out = vec![0.0f32; FRAME_LEN]; - for n in 0..FRAME_LEN { - out[n] = frame[n] + self.overlap[ch][n]; - } - for n in 0..FRAME_LEN { - self.overlap[ch][n] = frame[FRAME_LEN + n]; - } - self.prev_kbd[ch] = info.window_shape_kbd; - self.prev_seq[ch] = info.window_sequence; - out - } -} - -/// Decode one `individual_channel_stream` to a dequantized spectrum. For short -/// blocks the layout is window-major (eight 128-bin windows). -struct Channel { - info: IcsInfo, - spec: [f32; FRAME_LEN], - cb: Vec>, - sf: Vec>, - tns: Tns, -} - -fn decode_channel( - r: &mut BitReader, - fs_index: u8, - common_info: Option<&IcsInfo>, - rng: &mut u32, -) -> Result { - let global_gain = r.read_bits(8)? as i32; - let info = match common_info { - Some(i) => i.clone(), - None => parse_ics_info(r, fs_index)?, - }; - - let is_short = info.window_sequence == WindowSequence::EightShort; - let swb = swb_offsets(!is_short, fs_index); - let max_sfb = info.max_sfb as usize; - if max_sfb + 1 > swb.len() { - return Err(Error::invalid("aac: max_sfb out of range")); - } - let window_len = if is_short { SHORT_HALF } else { FRAME_LEN }; - - let sfb_cb = read_sections(r, info.num_window_groups, max_sfb, is_short)?; - let sf = read_scalefactors(r, &sfb_cb, global_gain)?; - - let pulse = if r.read_bool()? { - Some(read_pulse(r)?) - } else { - None - }; - let tns = if r.read_bool()? { - parse_tns(r, &info)? - } else { - Tns::default() - }; - if r.read_bool()? { - return Err(Error::unsupported("aac: gain control not supported")); - } - - let mut quant = [0i32; FRAME_LEN]; - read_spectrum(r, &sfb_cb, &info, swb, window_len, &mut quant)?; - if let (Some(p), false) = (&pulse, is_short) { - apply_pulse(&mut quant, p, swb); - } - - // Inverse quantization, per group/window with the group's band scalefactor. - // PNS (NOISE_HCB) bands are filled with energy-scaled random noise instead. - let mut spec = [0f32; FRAME_LEN]; - let mut wbase = 0usize; - for (g, group) in sfb_cb.iter().enumerate() { - for (sfb, &cb) in group.iter().enumerate() { - if cb == ZERO_HCB { - continue; - } - if sfb + 1 >= swb.len() { - break; // malformed: more coded bands than the swb offset table holds - } - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - for w in 0..info.window_group_length[g] as usize { - let base = (wbase + w) * window_len; - if cb == NOISE_HCB { - fill_noise(rng, &mut spec, base + s, base + e, sf[g][sfb]); - } else { - let gain = dsp::sf_gain(sf[g][sfb]); - for i in s..e { - spec[base + i] = dsp::dequant(quant[base + i]) * gain; - } - } - } - } - wbase += info.window_group_length[g] as usize; - } - Ok(Channel { - info, - spec, - cb: sfb_cb, - sf, - tns, - }) -} - -/// section_data: a codebook number per scalefactor band, per group. -fn read_sections( - r: &mut BitReader, - groups: usize, - max_sfb: usize, - is_short: bool, -) -> Result>> { - let bits = if is_short { 3 } else { 5 }; - let esc = (1u32 << bits) - 1; - let mut out = Vec::with_capacity(groups); - for _ in 0..groups { - let mut cbs = vec![0u8; max_sfb]; - let mut k = 0usize; - while k < max_sfb { - let cb = r.read_bits(4)? as u8; - let mut len = 0usize; - loop { - let incr = r.read_bits(bits)? as usize; - len += incr; - if incr as u32 != esc { - break; - } - } - if k + len > max_sfb { - return Err(Error::invalid("aac: section overruns max_sfb")); - } - for c in cbs.iter_mut().skip(k).take(len) { - *c = cb; - } - k += len; - } - out.push(cbs); - } - Ok(out) -} - -/// scale_factor_data: differentially-coded scalefactors (regular codebooks). -fn read_scalefactors( - r: &mut BitReader, - sfb_cb: &[Vec], - global_gain: i32, -) -> Result>> { - let mut acc = global_gain; - let mut noise = global_gain - 90; // PNS noise-energy accumulator - let mut noise_pcm = true; - let mut is_pos = 0i32; // intensity-stereo position accumulator - let mut out = Vec::with_capacity(sfb_cb.len()); - for group in sfb_cb { - let mut sf = vec![0i32; group.len()]; - for (sfb, &cb) in group.iter().enumerate() { - if cb == ZERO_HCB { - continue; - } else if cb >= INTENSITY_HCB2 { - is_pos += SCALEFACTOR_BOOK.decode(r)? as i32 - 60; - sf[sfb] = is_pos; - } else if cb == NOISE_HCB { - // PNS: first noise energy is a 9-bit PCM delta, rest are Huffman. - if noise_pcm { - noise_pcm = false; - noise += r.read_bits(9)? as i32 - 256; - } else { - noise += SCALEFACTOR_BOOK.decode(r)? as i32 - 60; - } - sf[sfb] = noise; - } else { - acc += SCALEFACTOR_BOOK.decode(r)? as i32 - 60; - sf[sfb] = acc; - } - } - out.push(sf); - } - Ok(out) -} - -/// spectral_data: Huffman-decode quantized coefficients per group/band/window. -fn read_spectrum( - r: &mut BitReader, - sfb_cb: &[Vec], - info: &IcsInfo, - swb: &[u16], - window_len: usize, - quant: &mut [i32; FRAME_LEN], -) -> Result<()> { - let mut wbase = 0usize; - for (g, group) in sfb_cb.iter().enumerate() { - for (sfb, &cb) in group.iter().enumerate() { - // ZERO, NOISE (PNS) and intensity bands carry no spectral data. - if cb == ZERO_HCB || cb == NOISE_HCB || cb >= INTENSITY_HCB2 { - continue; - } - // Skip books that carry no spectral data or are out of range: the - // filter above misses INTENSITY_HCB (14) and reserved (12), which - // would index CODEBOOKS out of bounds on malformed (or intensity) - // input. `.get` skips them (intensity is applied later in apply_is). - let Some(meta) = CODEBOOKS.get(cb as usize) else { - continue; - }; - let book = spectral_book(cb); - let dim = meta.dim as usize; - if sfb + 1 >= swb.len() { - break; // malformed: more coded bands than the swb offset table holds - } - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - for w in 0..info.window_group_length[g] as usize { - let base = (wbase + w) * window_len; - let mut i = s; - let mut tuple = [0i32; 4]; - while i + dim <= e { - decode_tuple(meta, book, r, &mut tuple)?; - quant[base + i..base + i + dim].copy_from_slice(&tuple[..dim]); - i += dim; - } - } - } - wbase += info.window_group_length[g] as usize; - } - Ok(()) -} - -/// xorshift32 → uniform f32 in [-1, 1). Decoder-local; PNS noise is random by -/// design, so it is energy-matched (not sample-exact) across decoders. -fn next_rand(s: &mut u32) -> f32 { - *s ^= *s << 13; - *s ^= *s >> 17; - *s ^= *s << 5; - (*s as f32 / u32::MAX as f32) * 2.0 - 1.0 -} - -/// Fill `spec[start..end]` with random noise whose spectral energy matches the -/// transmitted `noise_energy` (ISO 14496-3 §4.6.13): unit-energy random vector -/// scaled so band energy = 2^(noise_energy/2). -fn fill_noise(rng: &mut u32, spec: &mut [f32], start: usize, end: usize, noise_energy: i32) { - let mut energy = 0f64; - for i in start..end { - let v = next_rand(rng); - spec[i] = v; - energy += (v as f64) * (v as f64); - } - if energy <= 0.0 { - return; - } - let scale = (2f64.powf(0.25 * noise_energy as f64) / energy.sqrt()) as f32; - for v in spec[start..end].iter_mut() { - *v *= scale; - } -} - -struct Pulse { - start_sfb: usize, - offsets: Vec, - amps: Vec, -} - -fn read_pulse(r: &mut BitReader) -> Result { - let n = r.read_bits(2)? as usize; // number_pulse - 1 - let start_sfb = r.read_bits(6)? as usize; - let mut offsets = Vec::with_capacity(n + 1); - let mut amps = Vec::with_capacity(n + 1); - for _ in 0..=n { - offsets.push(r.read_bits(5)?); - amps.push(r.read_bits(4)?); - } - Ok(Pulse { - start_sfb, - offsets, - amps, - }) -} - -fn apply_pulse(quant: &mut [i32; FRAME_LEN], p: &Pulse, swb: &[u16]) { - let mut k = *swb.get(p.start_sfb).unwrap_or(&0) as usize; - for (off, amp) in p.offsets.iter().zip(&p.amps) { - k += *off as usize; - if k < FRAME_LEN { - if quant[k] > 0 { - quant[k] += *amp as i32; - } else { - quant[k] -= *amp as i32; - } - } - } -} - -/// One TNS noise-shaping filter (a span of bands + its LPC synthesis filter). -struct TnsFilter { - length: usize, // span in scalefactor bands (from the top down) - order: usize, - direction: bool, // true = downward (high→low) filtering - lpc: Vec, // lpc[0]=1, lpc[1..=order] -} - -/// TNS data for a channel: filters per window. -#[derive(Default)] -struct Tns { - windows: Vec>, -} - -/// Max TNS-affected band per sampling-frequency index (ISO Table 4.A.45/46). -pub(crate) const TNS_MAX_LONG: [u8; 13] = [31, 31, 34, 40, 42, 51, 46, 46, 42, 42, 42, 39, 39]; -pub(crate) const TNS_MAX_SHORT: [u8; 13] = [9, 9, 10, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14]; - -/// Parse TNS, dequantizing PARCOR coefficients and converting them to LPC. -fn parse_tns(r: &mut BitReader, info: &IcsInfo) -> Result { - use std::f32::consts::PI; - let short = info.window_sequence == WindowSequence::EightShort; - let (nf_bits, len_bits, ord_bits) = if short { (1, 4, 3) } else { (2, 6, 5) }; - let mut windows = Vec::with_capacity(info.num_windows); - for _ in 0..info.num_windows { - let mut filters = Vec::new(); - let n_filt = r.read_bits(nf_bits)?; - let coef_res = if n_filt > 0 { r.read_bits(1)? } else { 0 }; - for _ in 0..n_filt { - let length = r.read_bits(len_bits)? as usize; - let order = r.read_bits(ord_bits)? as usize; - let (mut direction, mut lpc) = (false, Vec::new()); - if order > 0 { - direction = r.read_bool()?; - let coef_compress = r.read_bits(1)?; - let res_bits = 3 + coef_res; // 3 or 4 - let coef_bits = res_bits - coef_compress; - let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0); - let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0); - let mut parcor = vec![0f32; order]; - for p in parcor.iter_mut() { - let raw = r.read_bits(coef_bits)? as i32; - let c = if raw & (1 << (coef_bits - 1)) != 0 { - raw - (1 << coef_bits) - } else { - raw - }; - let t = if c >= 0 { - c as f32 / iqfac - } else { - c as f32 / iqfac_m - }; - *p = t.sin(); - } - lpc = parcor_to_lpc(&parcor); - } - filters.push(TnsFilter { - length, - order, - direction, - lpc, - }); - } - windows.push(filters); - } - Ok(Tns { windows }) -} - -/// PARCOR (reflection) → LPC coefficients via the step-up recursion. -fn parcor_to_lpc(parcor: &[f32]) -> Vec { - let order = parcor.len(); - let mut lpc = vec![0f32; order + 1]; - lpc[0] = 1.0; - for m in 1..=order { - let mut tmp = lpc.clone(); - for i in 1..m { - tmp[i] = lpc[i] + parcor[m - 1] * lpc[m - i]; - } - lpc[..m].copy_from_slice(&tmp[..m]); - lpc[m] = parcor[m - 1]; - } - lpc -} - -/// Apply TNS: an all-pole (synthesis) filter over each filter's band span, -/// per window, in the coded direction (ISO 14496-3 §4.6.9.3). -fn apply_tns(spec: &mut [f32; FRAME_LEN], tns: &Tns, info: &IcsInfo, fs_index: u8) { - if tns.windows.iter().all(|w| w.is_empty()) { - return; - } - let short = info.window_sequence == WindowSequence::EightShort; - let swb = swb_offsets(!short, fs_index); - let window_len = if short { SHORT_HALF } else { FRAME_LEN }; - let tns_max = if short { - TNS_MAX_SHORT[fs_index as usize] - } else { - TNS_MAX_LONG[fs_index as usize] - } as usize; - let mmm = tns_max.min(info.max_sfb as usize); - - for (w, filters) in tns.windows.iter().enumerate() { - let mut bottom = info.num_swb; - for f in filters { - let top = bottom; - bottom = top.saturating_sub(f.length); - if f.order == 0 { - continue; - } - let start = swb[bottom.min(mmm)] as usize; - let end = swb[top.min(mmm)] as usize; - if end <= start { - continue; - } - let size = end - start; - let base = w * window_len; - let (mut idx, inc): (isize, isize) = if f.direction { - ((base + end - 1) as isize, -1) - } else { - ((base + start) as isize, 1) - }; - let mut state = vec![0f32; f.order]; - for _ in 0..size { - let p = idx as usize; - let mut y = spec[p]; - for j in 0..f.order { - y -= state[j] * f.lpc[j + 1]; - } - for j in (1..f.order).rev() { - state[j] = state[j - 1]; - } - state[0] = y; - spec[p] = y; - idx += inc; - } - } - } -} - -/// M/S stereo flags (`num_window_groups × max_sfb`) for a common-window CPE. -fn read_ms_used(r: &mut BitReader, info: &IcsInfo) -> Result> { - let n = info.num_window_groups * info.max_sfb as usize; - match r.read_bits(2)? { - 0 => Ok(vec![false; n]), - 2 => Ok(vec![true; n]), - 1 => { - let mut v = vec![false; n]; - for slot in v.iter_mut() { - *slot = r.read_bool()?; - } - Ok(v) - } - _ => Err(Error::unsupported("aac: reserved ms_mask_present")), - } -} - -/// Reconstruct L/R from Mid/Side on the flagged bands (group/window aware). -/// Intensity-coded bands of the right channel are excluded (handled by IS). -fn apply_ms( - info: &IcsInfo, - ms_used: &[bool], - fs_index: u8, - cb1: &[Vec], - s0: &mut [f32; FRAME_LEN], - s1: &mut [f32; FRAME_LEN], -) { - if ms_used.is_empty() { - return; - } - let is_short = info.window_sequence == WindowSequence::EightShort; - let swb = swb_offsets(!is_short, fs_index); - let window_len = if is_short { SHORT_HALF } else { FRAME_LEN }; - let max_sfb = info.max_sfb as usize; - let mut wbase = 0usize; - for g in 0..info.num_window_groups { - for sfb in 0..max_sfb { - if ms_used[g * max_sfb + sfb] && cb1[g][sfb] < INTENSITY_HCB2 { - if sfb + 1 >= swb.len() { - break; // malformed: more coded bands than the swb offset table holds - } - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - for w in 0..info.window_group_length[g] as usize { - let base = (wbase + w) * window_len; - for i in s..e { - let (mid, side) = (s0[base + i], s1[base + i]); - s0[base + i] = mid + side; - s1[base + i] = mid - side; - } - } - } - } - wbase += info.window_group_length[g] as usize; - } -} - -/// Intensity stereo (ISO 14496-3 §4.6.8.2.3): the right channel's IS bands are -/// `± 2^(-is_position/4)` times the left channel. Sign is negative for -/// INTENSITY_HCB2, and flipped again when the band is M/S-flagged. -fn apply_is( - info: &IcsInfo, - ms_used: &[bool], - fs_index: u8, - cb1: &[Vec], - sf1: &[Vec], - s0: &[f32; FRAME_LEN], - s1: &mut [f32; FRAME_LEN], -) { - let is_short = info.window_sequence == WindowSequence::EightShort; - let swb = swb_offsets(!is_short, fs_index); - let window_len = if is_short { SHORT_HALF } else { FRAME_LEN }; - let max_sfb = info.max_sfb as usize; - let mut wbase = 0usize; - for g in 0..info.num_window_groups { - for sfb in 0..max_sfb { - let cb = cb1[g][sfb]; - if cb >= INTENSITY_HCB2 { - let mut scale = 0.5f32.powf(0.25 * sf1[g][sfb] as f32); - if cb == INTENSITY_HCB2 { - scale = -scale; // out of phase - } - if !ms_used.is_empty() && ms_used[g * max_sfb + sfb] { - scale = -scale; // M/S flips intensity sign - } - if sfb + 1 >= swb.len() { - break; // malformed: more coded bands than the swb offset table holds - } - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - for w in 0..info.window_group_length[g] as usize { - let base = (wbase + w) * window_len; - for i in s..e { - s1[base + i] = scale * s0[base + i]; - } - } - } - } - wbase += info.window_group_length[g] as usize; - } -} - -/// Interleave decoded channels, **reordering AAC element order into the standard -/// interleave order** the rest of the workspace uses (FL, FR, FC, LFE, BL, BR). -/// -/// AAC carries 5.1 as `C, L, R, Ls, Rs, LFE`; every WAV writer and filter here -/// expects `L, R, C, LFE, Ls, Rs`. Emitting element order straight out would put -/// the centre channel in the left speaker. Mono and stereo are identity, so this -/// changes nothing for the overwhelmingly common cases. -fn interleave(outputs: Vec>, sample_rate: u32, pts: Option) -> DecodedAudio { - let nch = outputs.len(); - let order = crate::encode::aac_to_interleave_order(nch); - let mut samples = Vec::with_capacity(FRAME_LEN * nch); - for n in 0..FRAME_LEN { - match &order { - Some(map) => { - for &src in map { - samples.push(outputs[src][n]); - } - } - // No defined layout (a PCE stream, once supported): pass elements - // through in stream order rather than guessing. - None => { - for ch in &outputs { - samples.push(ch[n]); - } - } - } - } - DecodedAudio { - sample_rate, - channels: nch as u16, - samples, - pts, - } -} - -fn fs_index_for(rate: u32) -> u8 { - SAMPLE_RATES - .iter() - .position(|&r| r == rate) - .map(|i| i as u8) - .unwrap_or(3) // default 48 kHz layout -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn section_and_scalefactors_parse() { - // One group, one cb=1 section of length 2 (long, 5-bit length). - // bits: cb(0001) len_incr(00010) → 0001_0001 0... = 0x11 0x00 - let mut r = BitReader::new(&[0x11, 0x00]); - let cb = read_sections(&mut r, 1, 2, false).unwrap(); - assert_eq!(cb, vec![vec![1, 1]]); - } - - #[test] - fn scalefactors_accumulate_from_global_gain() { - // Two regular bands; SF deltas both index 60 ("0" = delta 0) → both - // equal global_gain. Two "0" bits → 0x00. - let sfb_cb = vec![vec![1u8, 1u8]]; - let mut r = BitReader::new(&[0x00]); - let sf = read_scalefactors(&mut r, &sfb_cb, 100).unwrap(); - assert_eq!(sf, vec![vec![100, 100]]); - } - - /// End-to-end: a hand-built ONLY_LONG SCE frame, one cb1 codeword giving a - /// single non-zero coefficient. Decoded PCM must equal the IMDCT of that - /// spectrum, windowed and normalised — using the verified DSP as oracle. - #[test] - fn hand_built_frame_matches_independent_imdct() { - let au = [0x00, 0xC8, 0x00, 0x84, 0x21, 0x1E]; - let mut dec = Decoder::new(48_000); - let af = dec.decode(&au, Some(0)).unwrap(); - assert_eq!(af.channels, 1); - assert_eq!(af.frames(), FRAME_LEN); - let got: Vec = af.samples; - - let mut spec = [0f32; FRAME_LEN]; - spec[0] = -1.0; - let time = dsp::imdct(&spec); - let win = dsp::sine_window(LONG_N); - for n in 0..FRAME_LEN { - let expected = time[n] * win[n] / 32768.0; - assert!( - (got[n] - expected).abs() < 1e-4, - "sample {n}: got {} want {}", - got[n], - expected - ); - } - } -} diff --git a/vendor/rusty_aac/src/dsp.rs b/vendor/rusty_aac/src/dsp.rs deleted file mode 100644 index b22a28a..0000000 --- a/vendor/rusty_aac/src/dsp.rs +++ /dev/null @@ -1,461 +0,0 @@ -//! AAC numerical core: inverse quantization and the IMDCT synthesis filterbank -//! (windows + overlap-add). These must match ISO 14496-3 exactly — they are the -//! parts where any deviation produces audibly wrong / incompatible output, so -//! they're written straight from the spec and checked by the MDCT↔IMDCT -//! perfect-reconstruction (TDAC) property. -//! -//! The IMDCT here is a direct O(N²) evaluation — correct and clear; it can be -//! swapped for an FFT-based fast path later without changing results. - -// These primitives are exercised by the tests now and wired into the decode -// path in the spectral/synthesis stages; allow until then. -#![allow(dead_code)] - -use std::f64::consts::PI; -use std::sync::OnceLock; - -/// Inverse quantization of a spectral coefficient (ISO 14496-3 §10.3): -/// `x = sign(q) · |q|^(4/3)`. The scalefactor gain is applied separately. -pub fn dequant(q: i32) -> f32 { - let m = (q.unsigned_abs() as f64).powf(4.0 / 3.0); - (q.signum() as f64 * m) as f32 -} - -/// Scalefactor gain `2^(0.25·(sf − 100))`, the per-band multiplier applied to -/// dequantized coefficients. -pub fn sf_gain(sf: i32) -> f32 { - 2f64.powf(0.25 * (sf as f64 - 100.0)) as f32 -} - -/// IMDCT (ISO 14496-3 §4.6.11.2): `N/2` spectral coefficients → `N` time -/// samples. `out[i] = (2/N)·Σ_k spec[k]·cos((2π/N)(i+n0)(k+½))`, `n0=(N/2+1)/2`. -pub fn imdct(spec: &[f32]) -> Vec { - let half = spec.len(); - let n = half * 2; - if n == 0 { - return Vec::new(); - } - // LOCAL PATCH: O(N log N) instead of the O(N^2) sum below. With `n0 = N/4 + - // 1/2` the kernel is exactly a DCT-IV of length L = N/2 read at `j = i + - // L/2` -- the same DCT-IV [`mdct_fast`] already runs as one N/4-point FFT -- - // so the transform is that one call plus a sign-and-mirror walk (DCT-IV is - // even about `j = -1/2`, odd about `j = L - 1/2`, and negates every 2L). - if half >= 2 && half.is_power_of_two() { - let owned; - let tw = match mdct_twiddles(n) { - Some(t) => t, - None => { - owned = MdctTwiddles::build(n); - &owned - } - }; - let d = dct4(half, |k| spec[k] as f64, tw); - let scale = 2.0 / n as f64; - let (l, l2) = (half, half / 2); - return (0..n) - .map(|i| { - let j = i + l2; - let v = if j < l { - d[j] - } else if j < 2 * l { - -d[2 * l - 1 - j] - } else { - -d[j - 2 * l] - }; - (scale * v) as f32 - }) - .collect(); - } - imdct_direct(spec) -} - -/// The direct O(N^2) transform [`imdct`] is defined as, kept as the oracle its -/// test measures against and as the path for sizes the fast one does not take. -fn imdct_direct(spec: &[f32]) -> Vec { - let half = spec.len(); - let n = half * 2; - let n0 = (n / 2 + 1) as f64 / 2.0; // N/4 + 1/2 - let scale = 2.0 / n as f64; - let w = 2.0 * PI / n as f64; - let mut out = vec![0f32; n]; - for (i, o) in out.iter_mut().enumerate() { - let mut acc = 0f64; - let a = w * (i as f64 + n0); - for (k, &s) in spec.iter().enumerate() { - acc += s as f64 * (a * (k as f64 + 0.5)).cos(); - } - *o = (scale * acc) as f32; - } - out -} - -/// Forward MDCT — the analysis transform paired with [`imdct`]. Used to validate -/// the IMDCT via perfect reconstruction (and useful for an eventual encoder). -/// `N` time samples → `N/2` coefficients. -/// -/// The `2.0` factor makes this the exact inverse of the spec's `2/N` IMDCT under -/// Princen-Bradley windows, so `imdct(mdct(·))` with overlap-add is identity. -pub fn mdct(time: &[f32]) -> Vec { - let n = time.len(); - let half = n / 2; - if n == 0 { - return Vec::new(); - } - let n0 = (n / 2 + 1) as f64 / 2.0; - let w = 2.0 * PI / n as f64; - let mut out = vec![0f32; half]; - for (k, o) in out.iter_mut().enumerate() { - let mut acc = 0f64; - for (i, &t) in time.iter().enumerate() { - acc += t as f64 * (w * (i as f64 + n0) * (k as f64 + 0.5)).cos(); - } - *o = (2.0 * acc) as f32; - } - out -} - -/// In-place radix-2 Cooley–Tukey FFT (forward, `exp(-i2πkn/N)`); `re.len()` must be -/// a power of two and equal `im.len()`. Pure in-house `f64` — the fast MDCT's engine. -/// Uses precomputed per-stage twiddles (`tw_c`/`tw_s`, flattened over stages) so a -/// transform is pure multiply-add — no runtime trig or twiddle recurrence. -fn fft(re: &mut [f64], im: &mut [f64], tw_c: &[f64], tw_s: &[f64]) { - let n = re.len(); - // Bit-reversal permutation. - let mut j = 0usize; - for i in 1..n { - let mut bit = n >> 1; - while j & bit != 0 { - j ^= bit; - bit >>= 1; - } - j |= bit; - if i < j { - re.swap(i, j); - im.swap(i, j); - } - } - // Butterfly stages, indexing the flattened per-stage twiddle tables. - let mut off = 0usize; - let mut len = 2usize; - while len <= n { - let half = len / 2; - let mut base = 0; - while base < n { - for k in 0..half { - let (a, b) = (base + k, base + k + half); - let (cr, ci) = (tw_c[off + k], tw_s[off + k]); - let tr = cr * re[b] - ci * im[b]; - let ti = cr * im[b] + ci * re[b]; - re[b] = re[a] - tr; - im[b] = im[a] - ti; - re[a] += tr; - im[a] += ti; - } - base += len; - } - off += half; - len <<= 1; - } -} - -/// Precomputed MDCT twiddles for one block size: pre-rotation, post-rotation, and -/// the FFT's per-stage factors — so a transform touches no `cos`/`sin` at runtime. -struct MdctTwiddles { - pre_c: Vec, - pre_s: Vec, - post_c: Vec, - post_s: Vec, - fft_c: Vec, - fft_s: Vec, -} - -impl MdctTwiddles { - fn build(n: usize) -> MdctTwiddles { - // N/4-FFT MDCT: fold N→L=N/2, an M=N/4 complex FFT, pre/post rotations - // (derived + verified against the direct oracle — see mdct_fast). - let l = n / 2; - let m = n / 4; - let (mut pre_c, mut pre_s) = (vec![0f64; m], vec![0f64; m]); - for p in 0..m { - let th = PI * (4.0 * p as f64 + 1.0) / (4.0 * l as f64); - pre_c[p] = th.cos(); - pre_s[p] = th.sin(); - } - let (mut post_c, mut post_s) = (vec![0f64; m], vec![0f64; m]); - for p in 0..m { - let ph = PI * p as f64 / l as f64; - post_c[p] = ph.cos(); - post_s[p] = ph.sin(); - } - // FFT stage twiddles for the M-point transform (flattened over stages). - let (mut fft_c, mut fft_s) = (Vec::new(), Vec::new()); - let mut len = 2usize; - while len <= m { - for k in 0..len / 2 { - let ang = -2.0 * PI * k as f64 / len as f64; - fft_c.push(ang.cos()); - fft_s.push(ang.sin()); - } - len <<= 1; - } - MdctTwiddles { - pre_c, - pre_s, - post_c, - post_s, - fft_c, - fft_s, - } - } -} - -/// The AAC block sizes (2048 long, 256 short) get cached twiddles; any other size -/// (tests) builds a fresh set. -fn mdct_twiddles(n: usize) -> Option<&'static MdctTwiddles> { - static LONG: OnceLock = OnceLock::new(); - static SHORT: OnceLock = OnceLock::new(); - match n { - 2048 => Some(LONG.get_or_init(|| MdctTwiddles::build(2048))), - 256 => Some(SHORT.get_or_init(|| MdctTwiddles::build(256))), - _ => None, - } -} - -/// Fast forward MDCT (O(N log N)) — numerically matches the direct [`mdct`] (kept as -/// the scalar oracle). The textbook N/4 method: fold the N real inputs to L=N/2 (TDAC), -/// pack into M=N/4 complex with a pre-rotation, one **M-point** FFT, then a post-rotation -/// unpacks the N/2 coefficients. 4× fewer FFT points than a length-N transform. `N` is a -/// power of two (≥4); time samples → `N/2` coeffs. -pub fn mdct_fast(x: &[f32]) -> Vec { - let n = x.len(); - if n < 4 { - return mdct(x); // tiny sizes: fall back to the direct oracle - } - let l = n / 2; - let owned; - let tw = match mdct_twiddles(n) { - Some(t) => t, - None => { - owned = MdctTwiddles::build(n); - &owned - } - }; - // TDAC fold x[0..N] → y[mm] (computed on the fly), for the two indices each p needs. - let (l2, l32) = (l / 2, 3 * l / 2); - let fold = |mm: usize| -> f64 { - if mm < l2 { - -(x[l32 - 1 - mm] as f64) - (x[mm + l32] as f64) - } else { - (x[mm - l2] as f64) - (x[l32 - 1 - mm] as f64) - } - }; - // Output scaled ×2: that factor is [`mdct`]'s, not the DCT-IV's. - dct4(l, fold, tw).iter().map(|&v| (2.0 * v) as f32).collect() -} - -/// DCT-IV of length `l`: `out[k] = Σ_j y(j)·cos((π/L)(j+½)(k+½))`, as one -/// `L/2`-point complex FFT — pack + pre-rotate `v[p] = (y[2p] + i·y[L-1-2p]) -/// ·e^{-iπ(4p+1)/4L}`, transform, post-rotate `W = V·e^{-iπp/L}`, and read -/// `out[2p] = Re(W)`, `out[L-1-2p] = -Im(W)`. -/// -/// `y` is a closure because the forward MDCT folds its input on the fly and the -/// inverse reads a spectrum straight out; `tw` is the block-size table both -/// directions share ([`MdctTwiddles`], built for `N = 2L`). -fn dct4(l: usize, y: impl Fn(usize) -> f64, tw: &MdctTwiddles) -> Vec { - let m = l / 2; - let (mut re, mut im) = (vec![0f64; m], vec![0f64; m]); - for p in 0..m { - let (yr, yi) = (y(2 * p), y(l - 1 - 2 * p)); - re[p] = yr * tw.pre_c[p] + yi * tw.pre_s[p]; - im[p] = yi * tw.pre_c[p] - yr * tw.pre_s[p]; - } - fft(&mut re, &mut im, &tw.fft_c, &tw.fft_s); - let mut out = vec![0f64; l]; - for p in 0..m { - let (vr, vi) = (re[p], im[p]); - out[2 * p] = vr * tw.post_c[p] + vi * tw.post_s[p]; - out[l - 1 - 2 * p] = vr * tw.post_s[p] - vi * tw.post_c[p]; - } - out -} - -/// AAC sine analysis/synthesis window: `w[n] = sin(π/N·(n+½))`. -pub fn sine_window(n: usize) -> Vec { - (0..n) - .map(|i| (PI / n as f64 * (i as f64 + 0.5)).sin() as f32) - .collect() -} - -/// Modified Bessel function of the first kind, order 0 (series form). -fn bessel_i0(x: f64) -> f64 { - let mut sum = 1.0; - let mut term = 1.0; - let half_x = x / 2.0; - for k in 1..50 { - term *= (half_x / k as f64).powi(2); - sum += term; - if term < 1e-12 * sum { - break; - } - } - sum -} - -/// Kaiser-Bessel-derived window of length `n` (ISO 14496-3 §4.6.11.2.4). -/// `alpha` is 4 for long blocks (N=2048), 6 for short (N=256). -pub fn kbd_window(n: usize, alpha: f64) -> Vec { - let half = n / 2; - // Cumulative Kaiser window over the first half. - let mut cumulative = vec![0f64; half + 1]; - let mut running = 0.0; - for p in 0..=half { - let r = 2.0 * p as f64 / half as f64 - 1.0; // -1..1 - running += bessel_i0(PI * alpha * (1.0 - r * r).max(0.0).sqrt()); - cumulative[p] = running; - } - let total = cumulative[half]; - let mut w = vec![0f32; n]; - for i in 0..half { - w[i] = (cumulative[i] / total).sqrt() as f32; - w[n - 1 - i] = w[i]; - } - w -} - -#[cfg(test)] -mod tests { - use super::*; - - /// The fast FFT-based MDCT must match the direct O(N²) oracle at both block - /// sizes, on raw and encoder-scaled (×32768) input. - #[test] - fn mdct_fast_matches_direct() { - for &n in &[256usize, 2048] { - for &scale in &[1.0f32, 32768.0] { - let x: Vec = (0..n) - .map(|i| { - scale - * (0.3 * (i as f64 * 0.021).sin() + 0.2 * (i as f64 * 0.005).cos()) - as f32 - }) - .collect(); - let (a, b) = (mdct(&x), mdct_fast(&x)); - let tol = 2e-3 * scale.max(1.0); - for k in 0..n / 2 { - assert!( - (a[k] - b[k]).abs() < tol, - "n={n} scale={scale} k={k}: {} vs {}", - a[k], - b[k] - ); - } - } - } - } - - /// LOCAL PATCH: the fast IMDCT against the direct sum it replaced, at both - /// AAC block sizes plus one the twiddle cache does not hold (512, built on - /// the spot) and one the fast path declines (a 3-coefficient spectrum), on - /// raw and decoder-scale (×32768) input. Every output sample, because the - /// index remap is where a DCT-IV-based inverse goes wrong: a sign or a - /// mirror off by one is silent in the first half and audible in the second. - #[test] - fn imdct_matches_direct() { - for &half in &[3usize, 128, 256, 1024] { - for &scale in &[1.0f32, 32768.0] { - let spec: Vec = (0..half) - .map(|k| { - scale - * (0.4 * (k as f64 * 0.037).sin() + 0.25 * (k as f64 * 0.011).cos()) - as f32 - }) - .collect(); - let (a, b) = (imdct_direct(&spec), imdct(&spec)); - let tol = 2e-4 * scale.max(1.0); - for i in 0..half * 2 { - assert!( - (a[i] - b[i]).abs() < tol, - "half={half} scale={scale} i={i}: {} vs {}", - a[i], - b[i] - ); - } - } - } - } - - #[test] - fn dequant_matches_spec_curve() { - assert_eq!(dequant(0), 0.0); - assert_eq!(dequant(1), 1.0); - assert!((dequant(2) - 2f32.powf(4.0 / 3.0)).abs() < 1e-5); - assert!((dequant(-3) + 3f32.powf(4.0 / 3.0)).abs() < 1e-4); - // Monotonic and sign-preserving. - assert!(dequant(10) > dequant(9)); - assert!(dequant(-5) < 0.0); - } - - #[test] - fn sf_gain_is_quarter_db_steps() { - assert!((sf_gain(100) - 1.0).abs() < 1e-6); // sf 100 → unity - assert!((sf_gain(104) - 2.0).abs() < 1e-5); // +4 → ×2 - assert!((sf_gain(96) - 0.5).abs() < 1e-6); // −4 → ×0.5 - } - - /// w[n]² + w[n+N/2]² = 1 is the Princen-Bradley condition both AAC windows - /// must satisfy for the filterbank to reconstruct perfectly. - fn assert_princen_bradley(w: &[f32]) { - let half = w.len() / 2; - for n in 0..half { - let s = w[n] * w[n] + w[n + half] * w[n + half]; - assert!((s - 1.0).abs() < 1e-4, "PB violated at {n}: {s}"); - } - } - - #[test] - fn sine_window_satisfies_princen_bradley() { - assert_princen_bradley(&sine_window(256)); - } - - #[test] - fn kbd_window_satisfies_princen_bradley() { - assert_princen_bradley(&kbd_window(256, 4.0)); - assert_princen_bradley(&kbd_window(256, 6.0)); - } - - /// The decisive correctness check: windowed MDCT → IMDCT → windowed - /// overlap-add reconstructs the original signal in the steady-state region - /// (TDAC). If the IMDCT/window math is wrong, this fails. - #[test] - fn mdct_imdct_overlap_add_perfectly_reconstructs() { - let n = 64usize; - let half = n / 2; - let w = sine_window(n); - // A deterministic, broadband test signal. - let len = 4 * n; - let signal: Vec = (0..len) - .map(|i| (0.3 * (i as f64 * 0.21).sin() + 0.2 * (i as f64 * 0.05).cos()) as f32) - .collect(); - - let mut out = vec![0f32; len]; - let mut p = 0; - while p + n <= len { - let framed: Vec = (0..n).map(|i| signal[p + i] * w[i]).collect(); - let synth = imdct(&mdct(&framed)); - for i in 0..n { - out[p + i] += synth[i] * w[i]; - } - p += half; - } - - // Interior (≥ one full frame from each edge) must match the input. - for i in n..(len - n) { - assert!( - (out[i] - signal[i]).abs() < 1e-3, - "reconstruction error at {i}: {} vs {}", - out[i], - signal[i] - ); - } - } -} diff --git a/vendor/rusty_aac/src/encode.rs b/vendor/rusty_aac/src/encode.rs deleted file mode 100644 index 3f11212..0000000 --- a/vendor/rusty_aac/src/encode.rs +++ /dev/null @@ -1,4940 +0,0 @@ -//! In-house **AAC-LC encoder** (see `docs/codec-aac-encoder.md` for the brick -//! ledger). Bricks 1–7 are complete: encode-side primitives inverting the decoder -//! (bit writer, spectral-codebook encoder, header/config serializers), the forward -//! filterbank, the quantizer + rate loop, a Bark-spreading psychoacoustic model, -//! block switching, M/S stereo, and container/CLI integration. -//! -//! **What this encoder does NOT yet do** — the arms tracked by -//! `docs/codec-aac-great-gate.md`. Naming them here keeps a fit from being run -//! against a mis-documented encoder: -//! -//! * The psy model drives **long blocks only**; short blocks code with flat -//! scalefactors and a single window group (arm A1). -//! * The signal-to-mask ratio is a **constant 18 dB** — no tonality/SFM term -//! (arm A2), and no absolute threshold of hearing, so nothing here is a -//! function of absolute level (arm A4). -//! * **TNS, PNS and intensity stereo are never emitted** (arms A3/A6/A7), though -//! `crate::decode` implements all three. -//! * The rate loop searches **one global base offset** against a **constant -//! per-frame budget** — there is no outer per-band distortion loop (arm A12) -//! and no bit reservoir or VBR mode (arm A5). -//! * Window shape is hardcoded sine (arm A8) and the transient detector uses an -//! absolute energy ratio (arm A9). - -#![allow(dead_code)] - -use crate::codebook::{Codebook, CODEBOOKS, INTENSITY_HCB, INTENSITY_HCB2, NOISE_HCB}; -use crate::ics::{IcsInfo, WindowSequence}; -use crate::swb::swb_offsets; -use crate::tables::spectral_book; -use crate::{AdtsHeader, AudioSpecificConfig, Error, Result}; -use std::collections::{HashMap, VecDeque}; -use std::sync::{Arc, Mutex, OnceLock}; - -// --------------------------------------------------------------------------- -// Bit writer — MSB-first, the mirror of the decoder's `BitReader`. -// --------------------------------------------------------------------------- -pub struct BitWriter { - buf: Vec, - cur: u8, - nbits: u8, -} - -impl BitWriter { - pub fn new() -> Self { - BitWriter { - buf: Vec::new(), - cur: 0, - nbits: 0, - } - } - - /// Append the low `n` bits of `val`, most-significant bit first. - pub fn write(&mut self, val: u32, n: u32) { - for i in (0..n).rev() { - self.cur = (self.cur << 1) | ((val >> i) & 1) as u8; - self.nbits += 1; - if self.nbits == 8 { - self.buf.push(self.cur); - self.cur = 0; - self.nbits = 0; - } - } - } - - pub fn write_bool(&mut self, b: bool) { - self.write(b as u32, 1); - } - - /// Total bits written so far. - pub fn bit_len(&self) -> usize { - self.buf.len() * 8 + self.nbits as usize - } - - /// Pad to a byte boundary with zero bits and return the bytes. - pub fn into_bytes(mut self) -> Vec { - if self.nbits != 0 { - self.cur <<= 8 - self.nbits; - self.buf.push(self.cur); - } - self.buf - } -} - -impl Default for BitWriter { - fn default() -> Self { - Self::new() - } -} - -// --------------------------------------------------------------------------- -// Spectral codebook encoding — the inverse of `codebook::apply_index`. -// --------------------------------------------------------------------------- - -/// Pack a `dim`-tuple of quantized coefficients into codebook `cb`'s base-`modulo` -/// Huffman index, or None if the tuple isn't representable by that codebook. -fn tuple_index(cb: &Codebook, tuple: &[i32]) -> Option { - let dim = cb.dim as usize; - let lav = cb.lav as u32; - let modulo = if cb.unsigned { lav + 1 } else { 2 * lav + 1 }; - let mut index = 0u32; - for &c in &tuple[..dim] { - let mag = c.unsigned_abs(); - let digit = if cb.unsigned { - if cb.esc { - mag.min(lav) // book 11: a magnitude ≥ lav clamps to lav and escapes - } else if mag <= lav { - mag - } else { - return None; - } - } else if mag <= lav { - (c + lav as i32) as u32 - } else { - return None; - }; - index = index * modulo + digit; - } - Some(index) -} - -/// Bits to code `tuple` with codebook `cb_num`, or None if unrepresentable. -pub fn spectral_bits(cb_num: usize, tuple: &[i32]) -> Option { - let cb = &CODEBOOKS[cb_num]; - let idx = tuple_index(cb, tuple)?; - let (_, len) = spectral_book(cb_num as u8).code(idx as usize); - let dim = cb.dim as usize; - let mut bits = len as usize; - if cb.unsigned { - bits += tuple[..dim].iter().filter(|&&c| c != 0).count(); // one sign bit each - } - if cb.esc { - for &c in &tuple[..dim] { - if c.unsigned_abs() >= cb.lav as u32 { - bits += escape_bits(c.unsigned_abs()); - } - } - } - Some(bits) -} - -/// Emit `tuple` with codebook `cb_num`: codeword, then sign bits (unsigned books), -/// then escape sequences (book 11). Caller ensures `spectral_bits` is Some. -pub fn spectral_emit(cb_num: usize, tuple: &[i32], w: &mut BitWriter) { - let cb = &CODEBOOKS[cb_num]; - let dim = cb.dim as usize; - let idx = tuple_index(cb, tuple).expect("representable tuple"); - let (code, len) = spectral_book(cb_num as u8).code(idx as usize); - w.write(code, len as u32); - if cb.unsigned { - for &c in &tuple[..dim] { - if c != 0 { - w.write_bool(c < 0); - } - } - } - if cb.esc { - for &c in &tuple[..dim] { - if c.unsigned_abs() >= cb.lav as u32 { - emit_escape(c.unsigned_abs(), w); - } - } - } -} - -/// Escape length for magnitude `m` (≥ 16): `2N+5` bits, `2^(N+4) ≤ m < 2^(N+5)`. -fn escape_bits(m: u32) -> usize { - let n = (31 - m.leading_zeros()) - 4; - 2 * n as usize + 5 -} - -/// Escape sequence (ISO §4.6.3.3): N leading 1-bits, a 0, then N+4 bits of -/// `m - 2^(N+4)`. -fn emit_escape(m: u32, w: &mut BitWriter) { - let n = (31 - m.leading_zeros()) - 4; - for _ in 0..n { - w.write_bool(true); - } - w.write_bool(false); - let bits = n + 4; - w.write(m - (1 << bits), bits); -} - -// --------------------------------------------------------------------------- -// Header / config serializers — inverses of the decoder's parsers. -// --------------------------------------------------------------------------- - -/// The `AudioSpecificConfig` bytes for an AAC-LC stream — the MP4 `esds` -/// DecoderSpecificInfo the muxer needs (2 bytes for standard rates). -pub fn audio_specific_config_bytes(sample_rate: u32, channels: u16) -> Vec { - write_audio_specific_config(&AudioSpecificConfig { - object_type: 2, // AAC-LC - sample_rate, - channels, - }) -} - -/// Serialize an `AudioSpecificConfig` (ISO §1.6.2.1) — the `esds`/`stsd` config -/// bytes the MP4 muxer needs. Inverse of `parse_audio_specific_config`. -pub fn write_audio_specific_config(cfg: &AudioSpecificConfig) -> Vec { - let mut w = BitWriter::new(); - if cfg.object_type >= 31 { - w.write(31, 5); - w.write((cfg.object_type - 32) as u32, 6); - } else { - w.write(cfg.object_type as u32, 5); - } - match crate::sf_index_for_rate(cfg.sample_rate) { - Some(i) => w.write(i as u32, 4), - None => { - w.write(0x0F, 4); - w.write(cfg.sample_rate, 24); - } - } - w.write(cfg.channels as u32, 4); - w.into_bytes() -} - -/// Serialize a 7-byte ADTS frame header (no CRC) — inverse of `parse_adts`. -/// `hdr.frame_length` must include this 7-byte header. -pub fn write_adts_header(hdr: &AdtsHeader) -> Vec { - let sf = crate::sf_index_for_rate(hdr.sample_rate).expect("standard rate for ADTS"); - let mut w = BitWriter::new(); - w.write(0xFFF, 12); // syncword - w.write(0, 1); // MPEG-4 - w.write(0, 2); // layer (00) - w.write_bool(true); // protection_absent → 7-byte header, no CRC - w.write((hdr.object_type - 1) as u32, 2); // profile - w.write(sf as u32, 4); - w.write(0, 1); // private - w.write(hdr.channels as u32, 3); // channel config - w.write(0, 4); // orig/home/copyright id+start - w.write(hdr.frame_length as u32, 13); - w.write(0x7FF, 11); // buffer fullness (VBR marker) - w.write(0, 2); // num_raw_data_blocks - 1 - w.into_bytes() -} - -/// Serialize `ics_info` for AAC-LC — inverse of `parse_ics_info`. -pub fn encode_ics_info(w: &mut BitWriter, info: &IcsInfo) { - w.write(0, 1); // ics_reserved - w.write(info.window_sequence.to_bits(), 2); - w.write_bool(info.window_shape_kbd); - if info.window_sequence.is_short() { - w.write(info.max_sfb as u32, 4); - w.write(grouping_bits(&info.window_group_length), 7); - } else { - w.write(info.max_sfb as u32, 6); - w.write(0, 1); // predictor_data_present (AAC-LC = 0) - } -} - -/// The 7 `scale_factor_grouping` bits from window-group lengths (inverse of the -/// parser's grouping walk): the bit for window i+1 is 1 if it continues the -/// current group, 0 if it starts a new one. -fn grouping_bits(group_lengths: &[u8]) -> u32 { - let mut is_start = [false; 8]; - let mut w = 0usize; - for &len in group_lengths { - if w < 8 { - is_start[w] = true; - } - w += len as usize; - } - let mut sfg = 0u32; - for i in 0..7 { - if !is_start[i + 1] { - sfg |= 1 << (6 - i); - } - } - sfg -} - -// --------------------------------------------------------------------------- -// Filterbank — forward long-block MDCT (inverse of the decoder's synthesis). -// --------------------------------------------------------------------------- -pub const FRAME_LEN: usize = 1024; -pub const LONG_N: usize = 2048; -const SHORT_N: usize = 256; -const SHORT_HALF: usize = 128; -/// 1 / OUTPUT_NORM: the decoder scales its output by 1/32768, so the encoder -/// scales the spectrum up by 32768 to land in the AAC coefficient domain. -const SPEC_SCALE: f32 = 32768.0; - -/// Forward long-block filterbank: window the overlapping 2048 input samples -/// (previous frame's 1024 ++ current 1024) and forward-MDCT to 1024 coefficients, -/// scaled so the decoder's `imdct · window · (1/32768) + overlap-add` reconstructs -/// the input (TDAC). `win` is the 2048-length window (sine or KBD). -pub fn analyze_long(prev: &[f32; FRAME_LEN], cur: &[f32; FRAME_LEN], win: &[f32]) -> Vec { - let mut windowed = vec![0f32; LONG_N]; - for n in 0..FRAME_LEN { - windowed[n] = prev[n] * win[n] * SPEC_SCALE; - windowed[FRAME_LEN + n] = cur[n] * win[FRAME_LEN + n] * SPEC_SCALE; - } - crate::dsp::mdct_fast(&windowed) -} - -/// Forward short-block filterbank: eight 256-sample windows (128-hop) tiled across -/// [448, 1600) of the prev++cur 2048 buffer, each windowed + MDCT'd to 128 coeffs, -/// laid out window-major (the exact inverse of the decoder's `short_frame`). The -/// uncovered [0,448)/[1600,2048) regions are bridged by the LongStart/LongStop -/// neighbours — which is why EightShort must sit between transition blocks. -pub fn analyze_short(prev: &[f32; FRAME_LEN], cur: &[f32; FRAME_LEN], sw: &[f32]) -> Vec { - let mut buf = [0f32; LONG_N]; - buf[..FRAME_LEN].copy_from_slice(prev); - buf[FRAME_LEN..].copy_from_slice(cur); - let mut spec = vec![0f32; FRAME_LEN]; - for w in 0..8 { - let off = 448 + w * SHORT_HALF; - let mut windowed = [0f32; SHORT_N]; - for (n, s) in windowed.iter_mut().enumerate() { - *s = buf[off + n] * sw[n] * SPEC_SCALE; - } - let coeffs = crate::dsp::mdct_fast(&windowed); - spec[w * SHORT_HALF..(w + 1) * SHORT_HALF].copy_from_slice(&coeffs); - } - spec -} - -/// The 2048-sample analysis window for a long or transition block — the exact -/// encode-side twin of the decoder's `long_window`. -/// -/// **The left half follows the PREVIOUS block's shape, the right half the -/// current's** (`prev_kbd` / `cur_kbd`), because that is what the decoder does: -/// each overlap region must be windowed identically on both sides or TDAC fails -/// and the overlap-add leaves audible seams. LongStart/LongStop taper one side to -/// a short window so the sequence stays TDAC-exact. -/// -/// The decoder seeds `prev_kbd = false` for the first frame of a stream -/// (`decode.rs`), so the encoder must too. -#[allow(clippy::too_many_arguments)] -fn long_window( - seq: WindowSequence, - prev_kbd: bool, - cur_kbd: bool, - sine_l: &[f32], - kbd_l: &[f32], - sine_s: &[f32], - kbd_s: &[f32], -) -> Vec { - let long_prev = if prev_kbd { kbd_l } else { sine_l }; - let long_cur = if cur_kbd { kbd_l } else { sine_l }; - let short_prev = if prev_kbd { kbd_s } else { sine_s }; - let short_cur = if cur_kbd { kbd_s } else { sine_s }; - - let mut w = vec![0f32; LONG_N]; - if seq == WindowSequence::LongStop { - w[448..448 + SHORT_HALF].copy_from_slice(&short_prev[..SHORT_HALF]); - for s in w.iter_mut().take(FRAME_LEN).skip(576) { - *s = 1.0; - } - } else { - w[..FRAME_LEN].copy_from_slice(&long_prev[..FRAME_LEN]); - } - if seq == WindowSequence::LongStart { - for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) { - *s = 1.0; - } - w[FRAME_LEN + 448..FRAME_LEN + 448 + SHORT_HALF].copy_from_slice(&short_cur[SHORT_HALF..]); - } else { - w[FRAME_LEN..].copy_from_slice(&long_cur[FRAME_LEN..]); - } - w -} - -/// **The Rung 0 gate signal**: order-2 LPC prediction gain over the frame's time -/// samples — a cheap tonality proxy. -/// -/// Chosen over the spectral flatness measure the lab validates because SFM needs -/// a spectrum, and the window shape must be decided *before* the spectrum exists -/// (the shape determines the window that produces it). Computing a probe MDCT per -/// frame just to pick a window would roughly double filterbank cost for a -/// small-by-design win — dominated on `bits-per-op` grounds before it started. -/// -/// This is O(3n) multiply-adds and needs no transform. Tonal signals are strongly -/// predictable from two past samples; noise is not. Validated against the -/// per-class truth table in `lab::signals` before being wired here. -/// -/// Returns `R[0] / E₂ ≥ 1`. -pub(crate) fn time_tonality(x: &[f32]) -> f32 { - let n = x.len(); - if n < 8 { - return 1.0; - } - let mut r = [0f64; 3]; - for (lag, slot) in r.iter_mut().enumerate() { - let mut acc = 0f64; - for i in 0..n - lag { - acc += x[i] as f64 * x[i + lag] as f64; - } - *slot = acc; - } - if r[0] <= 1e-12 { - return 1.0; - } - let r0 = r[0] * 1.0001; // white-noise correction — keeps Levinson stable - let k1 = r[1] / r0; - let e1 = r0 * (1.0 - k1 * k1); - if e1 <= 1e-12 { - return 1.0; - } - let k2 = (r[2] - k1 * r[1]) / e1; - let e2 = e1 * (1.0 - k2 * k2); - ((r0 / e2.max(1e-12)) as f32).max(1.0) -} - -// --------------------------------------------------------------------------- -// Psychoacoustic model (brick 4) — per-SFB masking thresholds drive per-band -// scalefactor allocation, so quantization noise is shaped to the audible floor. -// --------------------------------------------------------------------------- - -/// Traunmüller's Hz→Bark (critical-band rate). -fn hz_to_bark(f: f64) -> f64 { - let f = f.max(1.0); - 26.81 * f / (1960.0 + f) - 0.53 -} - -/// Spreading of a masker's energy to a maskee `dz` Bark away (`dz` = maskee − -/// masker): steep ~27 dB/Bark toward lower bands, gentle ~10 dB/Bark upward. -fn spreading(dz: f64) -> f64 { - let slope_db = if dz >= 0.0 { -10.0 } else { -27.0 }; - 10f64.powf(slope_db * dz.abs() / 10.0) -} - -/// The Bark-spreading matrix `S[i·n+j] = spreading(bark[i]-bark[j])` for one band -/// geometry — fixed per (sample_rate, band count), so it's built once and cached, -/// turning each frame's masking into a matrix-vector product (no runtime powf). -/// `n_coeffs` is the number of spectral coefficients the band table spans — 1024 -/// for a long block, 128 for one short window. It sets the coefficient→Hz -/// mapping, so passing the long value for a short block would place every band -/// eight octaves too low and spread the mask against the wrong neighbours. -fn spreading_matrix(swb: &[u16], sample_rate: u32, n_coeffs: usize) -> Arc> { - type Cache = Mutex>>>; - static CACHE: OnceLock = OnceLock::new(); - let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new())); - let key = (sample_rate, swb.len(), n_coeffs); - let mut c = cache.lock().unwrap(); - if let Some(m) = c.get(&key) { - return m.clone(); - } - let num_swb = swb.len() - 1; - let bark: Vec = (0..num_swb) - .map(|sfb| { - let center = (swb[sfb] as f64 + swb[sfb + 1] as f64) / 2.0; - // n_coeffs coefficients span 0..sr/2. - hz_to_bark(center * sample_rate as f64 * 0.5 / n_coeffs as f64) - }) - .collect(); - let mut mat = vec![0f64; num_swb * num_swb]; - for i in 0..num_swb { - for j in 0..num_swb { - mat[i * num_swb + j] = spreading(bark[i] - bark[j]); - } - } - let arc = Arc::new(mat); - c.insert(key, arc.clone()); - arc -} - -/// Per-SFB masking threshold (energy units): spread the band energies on the -/// Bark scale, then sit the mask a fixed ratio below the spread signal. -/// -/// `pub(crate)` so [`crate::lab::quality`] can score coding noise against the -/// encoder's own mask (the NMR metric), in the same band geometry and energy -/// domain the encoder allocates in. -pub(crate) fn masking_thresholds(spec: &[f32], swb: &[u16], sample_rate: u32) -> Vec { - let num_swb = swb.len() - 1; - let mut energy = vec![0.0f64; num_swb]; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - energy[sfb] = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum::() + 1e-3; - } - masking_from_energy(&energy, swb, sample_rate, FRAME_LEN, None) -} - -/// The default signal-to-mask ratio: the mask sits 18 dB below the spread signal, -/// for every band and every kind of content. -/// -/// **Arm A2** replaces this constant with a function of tonality. It is census -/// category 4 — a knob whose own doc-comment names the physical signal it tracks, -/// shipping as a constant. Kept as the byte-identical fallback. -const SMR_FLAT: f64 = 0.0158; // 10^(-18/10) - -/// The psychoacoustic arms in flight, threaded down to every coding path. -/// -/// A struct rather than loose bools because these arms compose: A1 decides -/// *whether* short blocks get a mask at all, A2 decides *what* that mask is, and -/// both must reach the CPE path and the SCE path identically or the two paths -/// silently encode to different models — the inconsistency great-gate's P0.9 -/// hygiene batch exists to prevent. -/// -/// `PsyCfg::default()` is all-off = the encoder exactly as it shipped. -#[derive(Debug, Clone, Copy, Default)] -pub(crate) struct PsyCfg { - /// Arm A1 — psy model on short blocks (else flat scalefactors). - pub short_block_psy: bool, - /// Arm A2 — tonality-adaptive SMR (else flat 18 dB). - pub tonality_smr: bool, - /// Arm A3 — emit TNS on long blocks. - pub tns: bool, - /// Arm A6 — Perceptual Noise Substitution. - pub pns: bool, - /// Arm A7 — intensity stereo. - pub intensity: bool, - /// Arm A13 — demand-proportional stereo bit split. - pub stereo_bit_split: bool, -} - -/// Per-band masking threshold from precomputed band energies. -/// -/// Split out from [`masking_thresholds`] so short blocks (whose band energies are -/// summed across the eight windows of a group) and long blocks share one masking -/// model — great-gate P1: consolidate duplicated probe skeletons into one path, -/// or a fit spanning both learns the inconsistency rather than the content. -/// -/// `tonality` is **arm A2**: `None` uses the flat 18 dB [`SMR_FLAT`] (the shipped -/// behavior, byte-identical); `Some(t)` interpolates the classic tonal/noise -/// masker offsets per band. -fn masking_from_energy( - energy: &[f64], - swb: &[u16], - sample_rate: u32, - n_coeffs: usize, - tonality: Option<&[f32]>, -) -> Vec { - let num_swb = swb.len() - 1; - let mat = spreading_matrix(swb, sample_rate, n_coeffs); - (0..num_swb) - .map(|i| { - let row = &mat[i * num_swb..(i + 1) * num_swb]; - let spread: f64 = (0..num_swb).map(|j| energy[j] * row[j]).sum(); - let smr = match tonality { - None => SMR_FLAT, - Some(t) => { - let center = (swb[i] as f64 + swb[i + 1] as f64) / 2.0; - let bark = hz_to_bark(center * sample_rate as f64 * 0.5 / n_coeffs as f64); - smr_for(t[i] as f64, bark) - } - }; - spread * smr - }) - .collect() -} - -/// **Arm A2.** Signal-to-mask ratio as a function of band tonality and Bark. -/// -/// The classic asymmetry: a *tonal* masker hides noise poorly, so the mask must -/// sit far below it (≈ 14.5 + bark dB); a *noise-like* masker hides noise well -/// (≈ 5.5 dB). Interpolating on the tonality index is the standard MPEG form. -/// -/// Today's encoder applies 18 dB to everything, so a pure tone and band-limited -/// noise at equal energy get identical treatment — which is what this replaces. -/// -/// Returned as a linear energy ratio (`10^(−dB/10)`), matching [`SMR_FLAT`]. -/// -/// # The noise end is 5.5 dB — and pinning it to 18 dB was measured and REFUTED -/// -/// The obvious-looking "safety" tweak is to pin the noise end to the shipped flat -/// 18 dB, so arm A2 can only ever give a band *more* protection than today and -/// never less. Measured on the corpus, that made things **worse**, not safer: -/// -/// | noise end | mean Δaudible% | worst class | -/// |---|---|---| -/// | 5.5 dB (textbook) | **−0.312** | +0.720 | -/// | 18.0 dB (pinned) | −0.006 | **+2.185** | -/// -/// The reason is that an SMR pair is a **bit-allocation balance, not two -/// independent protections**. Raising the tonal end buys precision only because -/// lowering the noise end frees the bits to pay for it. Pin the noise end and the -/// tonal end becomes pure extra demand against a fixed budget — the rate loop -/// answers by lifting the global base, and *every* band gets coarser. The -/// "conservative" variant regressed three times as hard as the one it was meant -/// to protect against. -/// -/// Keep the textbook pair. A2's remaining per-class failures are a **dispatch** -/// problem (route the arm by content class), not a constant to retune. -const SMR_NOISE_DB: f64 = 5.5; -fn smr_for(tonality: f64, bark: f64) -> f64 { - let t = tonality.clamp(0.0, 1.0); - let db = t * (14.5 + bark) + (1.0 - t) * SMR_NOISE_DB; - // Clamp to a sane band: below ~5 dB the mask stops protecting anything, and - // above ~30 dB the rate loop is asked for precision no bitrate can buy. - let db = db.clamp(5.0, 30.0); - 10f64.powf(-db / 10.0) -} - -/// Per-SFB scalefactor offsets (relative to a common base the rate loop sets): -/// higher where masking is generous, lower where noise would be audible. From -/// `noise ∝ 2^(0.375·sf)·Σ√|X|`, the sf hitting `noise = threshold` is -/// `log2(threshold/Σ√|X|)/0.375`; we normalize + clamp so deltas stay codeable. -/// Per-SFB tonality index in `[0, 1]` from the spectral flatness measure — **arm -/// A2's signal**. 0 = noise-like, 1 = pure tone. -/// -/// `SFM = geometric_mean(|X|²) / arithmetic_mean(|X|²)`, in dB, through the -/// classic `min(SFM_dB / −60, 1)`. -pub(crate) fn band_tonality(spec: &[f32], swb: &[u16], nwin: usize, wlen: usize) -> Vec { - let n = swb.len() - 1; - let mut out = vec![0f32; n]; - for b in 0..n { - let (s, e) = (swb[b] as usize, swb[b + 1] as usize); - let (mut log_sum, mut lin_sum, mut cnt) = (0f64, 0f64, 0usize); - for w in 0..nwin { - let base = w * wlen; - for k in s..e { - let Some(&x) = spec.get(base + k) else { continue }; - // Floored well below any audible coefficient so a single exact - // zero cannot drag the geometric mean to 0 and fake a pure tone. - let p = ((x as f64) * (x as f64)).max(1e-10); - log_sum += p.ln(); - lin_sum += p; - cnt += 1; - } - } - if cnt == 0 { - continue; - } - let gm = (log_sum / cnt as f64).exp(); - let am = lin_sum / cnt as f64; - let sfm_db = 10.0 * (gm / am.max(1e-30)).log10(); - out[b] = ((sfm_db / -60.0) as f32).clamp(0.0, 1.0); - } - out -} - -fn perceptual_offsets( - spec: &[f32], - swb: &[u16], - sample_rate: u32, - tonality_smr: bool, -) -> Vec { - let num_swb = swb.len() - 1; - let mut energy = vec![0.0f64; num_swb]; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - energy[sfb] = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum::() + 1e-3; - } - let ton = tonality_smr.then(|| band_tonality(spec, swb, 1, FRAME_LEN)); - let thr = masking_from_energy(&energy, swb, sample_rate, FRAME_LEN, ton.as_deref()); - - let mut raw = vec![0.0f64; num_swb]; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - energy[sfb] = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum(); - let noise_scale: f64 = spec[s..e] - .iter() - .map(|&x| (x.abs() as f64).sqrt()) - .sum::() - + 1e-6; - raw[sfb] = (thr[sfb] / noise_scale).log2() / 0.375; - } - // Center on the energy-bearing bands — empty bands have huge `thr/noise_scale` - // (they quantize to ZERO anyway) and would otherwise skew a plain mean. - let etot: f64 = energy.iter().sum::() + 1e-9; - let center: f64 = (0..num_swb).map(|i| raw[i] * energy[i]).sum::() / etot; - raw.iter() - .map(|&r| ((r - center).round() as i32).clamp(-60, 60)) - .collect() -} - -// --------------------------------------------------------------------------- -// Quantization + coding — brick 4: per-band scalefactors (psy-driven), cheapest -// codebook per band, rate loop over the common base, raw_data_block assembly. -// --------------------------------------------------------------------------- - -/// The Rung 0 gate's transient-veto threshold, as a percentile of the clip's own -/// frame-attack distribution. Frames above it always take the sine window. -/// -/// PROVISIONAL. 0.75 is a placeholder pending a calculator fit; it is set high -/// (veto only the top quartile) so the veto is conservative — it gives up KBD on -/// some stationary frames rather than risk smearing an onset. -const SHAPE_ATTACK_VETO_PCT: f32 = 0.75; - -/// Arm A13's routing threshold: how correlated a channel pair must be before the -/// joint rate loop replaces the even per-channel split. Sits in the measured gap -/// between wide content (0.25, where joint loses) and real stereo music -/// (0.47-0.84, where it wins). -const JOINT_STEREO_MIN_CORR: f32 = 0.35; - -/// Spectral correlation of a channel pair, `|| / sqrt()`. -/// 1 = identical, 0 = orthogonal. O(n) over the spectra the caller already has. -fn pair_correlation(l: &[f32], r: &[f32]) -> f32 { - let n = l.len().min(r.len()); - let (mut dot, mut el, mut er) = (0f64, 0f64, 0f64); - for i in 0..n { - let (a, b) = (l[i] as f64, r[i] as f64); - dot += a * b; - el += a * a; - er += b * b; - } - if el <= 1e-9 || er <= 1e-9 { - return 1.0; // a silent channel is trivially "agreeable" - } - (dot.abs() / (el.sqrt() * er.sqrt())) as f32 -} - -const ID_SCE: u32 = 0; -const ID_CPE: u32 = 1; -const ID_LFE: u32 = 3; -const ID_END: u32 = 7; -const ZERO_HCB: u8 = 0; -const ESC_HCB: u8 = 11; - -// --------------------------------------------------------------------------- -// Channel element layout (ISO 14496-3 Table 1.19). -// -// `channel_configuration` in the ADTS header / AudioSpecificConfig does not just -// count channels — it *names the element sequence a decoder will expect*. Writing -// `channel_config = 6` and then emitting six SCEs is not "6 channels", it is a -// non-conformant stream: a conforming decoder reads SCE, CPE, CPE, LFE. -// -// Our own decoder happened to tolerate it (it appends elements in order), which -// is exactly how the bug survived — self-round-trip is not conformance. -// --------------------------------------------------------------------------- - -/// One channel element to emit, naming its source channels **in input order**. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Elem { - /// single_channel_element carrying input channel `.0`. - Sce(usize), - /// channel_pair_element carrying input channels `.0` (left) and `.1` (right). - Cpe(usize, usize), - /// lfe_channel_element carrying input channel `.0`. Long blocks only. - Lfe(usize), -} - -impl Elem { - /// The 3-bit element id written to the bitstream. - fn id(self) -> u32 { - match self { - Elem::Sce(_) => ID_SCE, - Elem::Cpe(_, _) => ID_CPE, - Elem::Lfe(_) => ID_LFE, - } - } -} - -/// The element sequence for `channels`, with source indices in the **standard -/// interleave order** the caller pushes (WAVE_FORMAT_EXTENSIBLE / FFmpeg order: -/// FL, FR, FC, LFE, BL, BR). -/// -/// The reordering is the substance here. AAC orders a 5.1 stream -/// `C, L, R, Ls, Rs, LFE`; interleaved PCM arrives `L, R, C, LFE, Ls, Rs`. Emitting -/// them in arrival order would put the centre channel in the left speaker. -/// -/// Returns `None` for channel counts with no defined `channel_configuration` -/// (0, or > 6): those need a program_config_element, which we do not yet write. -pub(crate) fn element_plan(channels: usize) -> Option> { - Some(match channels { - // config 1 — mono. - 1 => vec![Elem::Sce(0)], - // config 2 — stereo. - 2 => vec![Elem::Cpe(0, 1)], - // config 3 — 3.0: C, L/R. - 3 => vec![Elem::Sce(2), Elem::Cpe(0, 1)], - // config 4 — 4.0: C, L/R, rear centre. - 4 => vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Sce(3)], - // config 5 — 5.0: C, L/R, Ls/Rs. - 5 => vec![Elem::Sce(2), Elem::Cpe(0, 1), Elem::Cpe(3, 4)], - // config 6 — 5.1: C, L/R, Ls/Rs, LFE. - 6 => vec![ - Elem::Sce(2), - Elem::Cpe(0, 1), - Elem::Cpe(4, 5), - Elem::Lfe(3), - ], - _ => return None, - }) -} - -/// Inverse of [`element_plan`]'s ordering: for each **output** slot in standard -/// interleave order, which decoded element-order channel supplies it. -/// -/// The decoder emits channels in element order (AAC order); this maps them back -/// so a 5.1 decode interleaves as FL, FR, FC, LFE, BL, BR like every other -/// decoder in the workspace. -pub(crate) fn aac_to_interleave_order(channels: usize) -> Option> { - Some(match channels { - 1 => vec![0], - 2 => vec![0, 1], - // AAC order C,L,R -> interleave L,R,C - 3 => vec![1, 2, 0], - // AAC order C,L,R,Cs -> interleave L,R,C,Cs - 4 => vec![1, 2, 0, 3], - // AAC order C,L,R,Ls,Rs -> interleave L,R,C,Ls,Rs - 5 => vec![1, 2, 0, 3, 4], - // AAC order C,L,R,Ls,Rs,LFE -> interleave L,R,C,LFE,Ls,Rs - 6 => vec![1, 2, 0, 5, 3, 4], - _ => return None, - }) -} - -const MAX_QUANT: i32 = 8191; - -/// Quantize one coefficient at global gain `gg` (used by tests / the noise metric). -fn quantize(x: f32, gg: i32) -> i32 { - if x == 0.0 { - return 0; - } - let scale = 2f64.powf(-0.1875 * (gg - 100) as f64); - let q = (((x.abs() as f64).powf(0.75) * scale).round() as i32).min(MAX_QUANT); - if x < 0.0 { - -q - } else { - q - } -} - -/// `2^(-0.1875·(sf-100))`, the quantizer scale, tabulated once over all 256 gains -/// so the rate loop never repeats the exponent. -fn scale_table() -> &'static [f64; 256] { - static T: OnceLock<[f64; 256]> = OnceLock::new(); - T.get_or_init(|| { - let mut t = [0f64; 256]; - for (sf, e) in t.iter_mut().enumerate() { - *e = 2f64.powf(-0.1875 * (sf as f64 - 100.0)); - } - t - }) -} - -/// Per-magnitude coefficient bit cost (half a book-11 pair), tabulated so the rate -/// loop's *search* can price a frame in O(n) without the full codebook selection — -/// only the exact refinement does the real search. -fn coef_bits() -> &'static [u16] { - static T: OnceLock> = OnceLock::new(); - T.get_or_init(|| { - (0..=MAX_QUANT) - .map(|m| (spectral_bits(ESC_HCB as usize, &[m, m]).unwrap_or(64) / 2) as u16) - .collect() - }) -} - -/// Per-coefficient `|x|^0.75` and sign, precomputed once per frame so the rate -/// loop can re-quantize at each candidate gain without repeating the 0.75-power -/// (the single hottest op after the MDCT). Bit-exact with [`quantize`]. -struct Xpow { - pow: Vec, - sign: Vec, -} - -impl Xpow { - fn new(spec: &[f32]) -> Xpow { - let mut pow = vec![0f64; spec.len()]; - let mut sign = vec![0i32; spec.len()]; - #[cfg(all(feature = "simd", target_arch = "x86_64"))] - { - if has_avx2() { - // SAFETY: runtime AVX2 check; `pow`/`sign` are `spec.len()` long. - unsafe { xpow_avx2(spec, &mut pow, &mut sign) }; - return Xpow { pow, sign }; - } - } - for (i, &x) in spec.iter().enumerate() { - // |x|^0.75 = |x|^½·|x|^¼ = √|x|·√√|x| — two sqrts vectorize; `powf` doesn't. - // (For x=0, pow=0 so the sign is irrelevant — the quant is 0 either way.) - let s = (x.abs() as f64).sqrt(); - pow[i] = s * s.sqrt(); - sign[i] = if x < 0.0 { -1 } else { 1 }; - } - Xpow { pow, sign } - } - - /// Max `|x|^0.75` over `[s, e)` — the no-clamp-floor input (= `(max|x|)^0.75`). - fn max_pow(&self, s: usize, e: usize) -> f64 { - self.pow[s..e].iter().copied().fold(0.0, f64::max) - } - - fn len(&self) -> usize { - self.pow.len() - } -} - -/// The cheapest representable spectral codebook for one SFB's coefficients, and -/// its bit cost. ZERO for a silent band; dim-4 books only for 4-aligned bands. -/// Books whose LAV can't hold the band's peak are skipped up front (only the -/// escape book covers arbitrarily large values). -fn best_codebook_for_band(quant: &[i32], s: usize, e: usize) -> (u8, usize) { - let maxq = quant[s..e] - .iter() - .map(|&q| q.unsigned_abs()) - .max() - .unwrap_or(0); - if maxq == 0 { - return (ZERO_HCB, 0); - } - let mut best = (ESC_HCB, usize::MAX); - for cb in 1..=11u8 { - let meta = &CODEBOOKS[cb as usize]; - let dim = meta.dim as usize; - if (e - s) % dim != 0 || (!meta.esc && (meta.lav as u32) < maxq) { - continue; - } - let mut bits = 0usize; - let mut ok = true; - let mut i = s; - while i < e { - match spectral_bits(cb as usize, &quant[i..i + dim]) { - Some(b) => bits += b, - None => { - ok = false; - break; - } - } - i += dim; - } - if ok && bits < best.1 { - best = (cb, bits); - } - } - best -} - -/// Bits for section_data given per-SFB codebooks (adjacent equal cbs merge into -/// one 4-bit codebook + 5-bit run-length increments). -fn section_bits(cbs: &[u8]) -> usize { - let esc = 31usize; - let mut bits = 0usize; - let mut k = 0usize; - while k < cbs.len() { - let cb = cbs[k]; - let mut len = 1usize; - while k + len < cbs.len() && cbs[k + len] == cb { - len += 1; - } - bits += 4; - let mut l = len; - while l >= esc { - bits += 5; - l -= esc; - } - bits += 5; - k += len; - } - bits -} - -/// Per-band scalefactors from a common `base` plus the psy offsets, each clamped -/// to the codeable range. Offsets span ≤48, so band-to-band deltas stay < 60. -fn scalefactors(offsets: &[i32], base: i32) -> Vec { - offsets.iter().map(|&o| (base + o).clamp(0, 255)).collect() -} - -/// global_gain = the first coded band's scalefactor (the differential reference); -/// 100 for a silent frame with no coded bands. -fn global_gain(cbs: &[u8], sf: &[i32]) -> i32 { - // Only a REGULAR band seeds the differential chain. A PNS band's `sf` is a - // noise-energy value on its own accumulator and an intensity band's is a - // stereo position — seeding global_gain from either desynchronizes every - // scalefactor that follows. - cbs.iter() - .position(|&cb| cb != ZERO_HCB && cb < NOISE_HCB) - .map(|sfb| sf[sfb]) - .unwrap_or(100) -} - -/// Bits to code the per-band scalefactors as `SCALEFACTOR_BOOK` deltas from a -/// running accumulator seeded at `gg`. -fn scalefactor_bits(cbs: &[u8], sf: &[i32], gg: i32) -> usize { - let mut acc = gg; - let mut noise = gg - 90; - let mut noise_pcm = true; - let mut is_pos = 0i32; - let mut bits = 0usize; - for (sfb, &cb) in cbs.iter().enumerate() { - if cb == ZERO_HCB { - continue; - } else if cb >= crate::codebook::INTENSITY_HCB2 { - let d = (sf[sfb] - is_pos).clamp(-60, 60); - bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize; - is_pos += d; - } else if cb == NOISE_HCB { - if noise_pcm { - noise_pcm = false; - let d = (sf[sfb] - noise).clamp(-256, 255); - bits += 9; - noise += d; - } else { - let d = (sf[sfb] - noise).clamp(-60, 60); - bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize; - noise += d; - } - } else { - let d = (sf[sfb] - acc).clamp(-60, 60); - bits += crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize).1 as usize; - acc += d; - } - } - bits -} - -/// Runtime AVX2 availability (detected once). -#[cfg(all(feature = "simd", target_arch = "x86_64"))] -fn has_avx2() -> bool { - static AVX2: OnceLock = OnceLock::new(); - *AVX2.get_or_init(|| std::is_x86_feature_detected!("avx2")) -} - -#[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))] -fn has_avx512() -> bool { - static AVX512: OnceLock = OnceLock::new(); - *AVX512.get_or_init(|| std::is_x86_feature_detected!("avx512f")) -} - -/// Quantize one band into `out`: `out[k] = sign[k]·min(round(pow[k]·scale), MAX_QUANT)`. -/// This is the encoder's hottest kernel — the rate loop runs it ~11× per frame — so it -/// has an AVX2 path. `pow·scale ≥ 0`, so `floor(v+0.5)` equals `round(v)`, making the -/// vector path **bit-exact** with the scalar reference (verified by every gate test). -fn quantize_band(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) { - // SAFETY (all SIMD branches): entered only when the ISA is detected at runtime; the - // three slices share a length and vector bodies touch full lane-chunks, the remainder - // falling to the scalar tail. Every path is bit-exact with the scalar reference. - #[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))] - if has_avx512() { - unsafe { quantize_band_avx512(pow, sign, scale, out) }; - return; - } - #[cfg(all(feature = "simd", target_arch = "x86_64"))] - if has_avx2() { - unsafe { quantize_band_avx2(pow, sign, scale, out) }; - return; - } - quantize_band_scalar(pow, sign, scale, out); -} - -fn quantize_band_scalar(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) { - for k in 0..out.len() { - let q = ((pow[k] * scale).round() as i32).min(MAX_QUANT); - out[k] = sign[k] * q; - } -} - -/// AVX2 quantize — four coefficients per iteration. Bit-exact with the scalar path -/// (`floor(v+0.5) == round(v)` for `v ≥ 0`, and the clamp is applied before the -/// f64→i32 narrowing so nothing overflows). -#[cfg(all(feature = "simd", target_arch = "x86_64"))] -#[target_feature(enable = "avx2")] -unsafe fn quantize_band_avx2(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) { - use std::arch::x86_64::*; - let n = out.len(); - let vscale = _mm256_set1_pd(scale); - let vhalf = _mm256_set1_pd(0.5); - let vmax = _mm256_set1_pd(MAX_QUANT as f64); - let mut i = 0; - while i + 4 <= n { - let v = _mm256_mul_pd(_mm256_loadu_pd(pow.as_ptr().add(i)), vscale); - let r = _mm256_floor_pd(_mm256_add_pd(v, vhalf)); // = round(v), v ≥ 0 - let qabs = _mm256_cvttpd_epi32(_mm256_min_pd(r, vmax)); // clamp then f64→i32 - let s = _mm_loadu_si128(sign.as_ptr().add(i) as *const __m128i); - _mm_storeu_si128( - out.as_mut_ptr().add(i) as *mut __m128i, - _mm_mullo_epi32(qabs, s), - ); - i += 4; - } - while i < n { - let q = ((pow[i] * scale).round() as i32).min(MAX_QUANT); - out[i] = sign[i] * q; - i += 1; - } -} - -/// AVX-512 quantize — eight coefficients per iteration (2× the AVX2 width). Bit-exact: -/// for the quantizer's always-nonnegative input, `trunc(min(v+0.5, MAX+0.5))` equals -/// `min(round(v), MAX)`, so a single truncating narrow does round+clamp in one step. -/// Runtime-gated above AVX2; on AVX2-only hosts this path never runs (untested there — -/// the math mirrors the AVX2 kernel exactly, and its tail is the shared scalar reference). -#[cfg(all(feature = "simd-avx512", target_arch = "x86_64"))] -#[target_feature(enable = "avx512f,avx2")] -unsafe fn quantize_band_avx512(pow: &[f64], sign: &[i32], scale: f64, out: &mut [i32]) { - use std::arch::x86_64::*; - let n = out.len(); - let vscale = _mm512_set1_pd(scale); - let vhalf = _mm512_set1_pd(0.5); - let vmaxph = _mm512_set1_pd(MAX_QUANT as f64 + 0.5); // clamp v+0.5 so trunc yields MAX - let mut i = 0; - while i + 8 <= n { - let v = _mm512_mul_pd(_mm512_loadu_pd(pow.as_ptr().add(i)), vscale); - let c = _mm512_min_pd(_mm512_add_pd(v, vhalf), vmaxph); - let qabs = _mm512_cvttpd_epi32(c); // 8 f64 → 8 i32; trunc = floor for c ≥ 0 - let s = _mm256_loadu_si256(sign.as_ptr().add(i) as *const __m256i); - _mm256_storeu_si256( - out.as_mut_ptr().add(i) as *mut __m256i, - _mm256_mullo_epi32(qabs, s), - ); - i += 8; - } - while i < n { - let q = ((pow[i] * scale).round() as i32).min(MAX_QUANT); - out[i] = sign[i] * q; - i += 1; - } -} - -/// AVX2 `Xpow` builder: `pow[i] = |x|^0.75` via `√|x|·√√|x|` (two vector sqrts), and -/// `sign[i] = ±1` from the sign bit — four coefficients per iteration. -#[cfg(all(feature = "simd", target_arch = "x86_64"))] -#[target_feature(enable = "avx2")] -unsafe fn xpow_avx2(spec: &[f32], pow: &mut [f64], sign: &mut [i32]) { - use std::arch::x86_64::*; - let n = spec.len(); - let absmask = _mm256_castsi256_pd(_mm256_set1_epi64x(0x7fff_ffff_ffff_ffffu64 as i64)); - let one = _mm256_set1_pd(1.0); - let mut i = 0; - while i + 4 <= n { - let x = _mm256_cvtps_pd(_mm_loadu_ps(spec.as_ptr().add(i))); // 4 f32 → 4 f64 - let a = _mm256_and_pd(x, absmask); // |x| - let s = _mm256_sqrt_pd(a); // |x|^½ - _mm256_storeu_pd(pow.as_mut_ptr().add(i), _mm256_mul_pd(s, _mm256_sqrt_pd(s))); - // ±1.0 carrying x's sign bit → i32 (x=0 gives +1; harmless, pow is 0). - let signed = _mm256_or_pd(one, _mm256_andnot_pd(absmask, x)); - _mm_storeu_si128( - sign.as_mut_ptr().add(i) as *mut __m128i, - _mm256_cvttpd_epi32(signed), - ); - i += 4; - } - while i < n { - let s = (spec[i].abs() as f64).sqrt(); - pow[i] = s * s.sqrt(); - sign[i] = if spec[i] < 0.0 { -1 } else { 1 }; - } -} - -/// **Deterministic work counters** (feature `lab`) — the PRIMARY evidence for any -/// gate's speed half, per `codec-measurement` §15. -/// -/// A counter is immune to scheduler drift, needs one run, and SIZES the effect; -/// a clock at these magnitudes cannot be promoted to a verdict no matter how many -/// pairs it gets. The gate-calculator's `work` column is fed from here. -/// -/// Counts the rate loop's exact-coder evaluations — the encoder's dominant inner -/// cost and precisely the quantity a psy arm moves, because changing the offsets -/// changes how many bases the loop must try. -#[cfg(feature = "lab")] -pub mod work { - use std::sync::atomic::{AtomicU64, Ordering}; - - // GLOBAL, not thread-local. `encode_stream` fans frames out across worker - // threads, so a thread-local counter is drained on the main thread AFTER the - // workers have exited and reads **zero** — which is exactly what the first - // harvest reported (`WORK NULL: 0 vs 0`). A counter that reads flat is a - // defect report, not reassurance (`codec-measurement`, order of instruments). - static CODE_FRAME_EVALS: AtomicU64 = AtomicU64::new(0); - static QUANT_BANDS: AtomicU64 = AtomicU64::new(0); - - #[inline] - pub(crate) fn bump_code_frame() { - CODE_FRAME_EVALS.fetch_add(1, Ordering::Relaxed); - } - - #[inline] - pub(crate) fn bump_quant_bands(n: u64) { - QUANT_BANDS.fetch_add(n, Ordering::Relaxed); - } - - /// Read and clear both counters. - /// - /// `Relaxed` is sufficient: these are pure counters, never used to order - /// other memory, and the harvest reads them only after `finish()` has joined - /// every worker — so the joins provide the happens-before edge. - pub fn take() -> (u64, u64) { - ( - CODE_FRAME_EVALS.swap(0, Ordering::Relaxed), - QUANT_BANDS.swap(0, Ordering::Relaxed), - ) - } -} - -#[cfg(not(feature = "lab"))] -mod work { - #[inline] - pub(crate) fn bump_code_frame() {} - #[inline] - pub(crate) fn bump_quant_bands(_: u64) {} -} - -/// Shared coder body: quantize the frame into the caller-owned `quant` (per-band -/// scalefactors `sf`, which cover the whole spectrum so no pre-zeroing is needed), -/// pick per-band codebooks, and return (codebooks, ICS body bits, max_sfb). Splitting -/// this out lets the rate loop reuse one buffer instead of allocating per candidate. -fn code_core(xp: &Xpow, swb: &[u16], sf: &[i32], quant: &mut [i32]) -> (Vec, usize, usize) { - work::bump_code_frame(); - let num_swb = swb.len() - 1; - work::bump_quant_bands((swb.len() - 1) as u64); - let scale = scale_table(); - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let sc = scale[sf[sfb].clamp(0, 255) as usize]; - quantize_band(&xp.pow[s..e], &xp.sign[s..e], sc, &mut quant[s..e]); - } - let mut max_sfb = 0usize; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - if quant[s..e].iter().any(|&q| q != 0) { - max_sfb = sfb + 1; - } - } - let mut cbs = Vec::with_capacity(max_sfb); - let mut spec_bits = 0usize; - for sfb in 0..max_sfb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let (cb, bits) = best_codebook_for_band(quant, s, e); - cbs.push(cb); - spec_bits += bits; - } - let gg = global_gain(&cbs, sf); - // global_gain(8) + ics_info(~11) + 3 flag bits + sections + scalefactors + spectrum. - let body = 8 + 11 + 3 + section_bits(&cbs) + scalefactor_bits(&cbs, sf, gg) + spec_bits; - (cbs, body, max_sfb) -} - -/// Owned-buffer wrapper over [`code_core`] for the one-shot callers (final coding). -fn code_frame(xp: &Xpow, swb: &[u16], sf: &[i32]) -> (Vec, usize, usize, Vec) { - let mut quant = vec![0i32; xp.len()]; - let (cbs, body, max_sfb) = code_core(xp, swb, sf, &mut quant); - (cbs, body, max_sfb, quant) -} - -/// The smallest common `base` such that no band clamps its loudest coefficient -/// past `MAX_QUANT` (each band's own no-clamp floor, minus that band's offset). -fn min_base(xp: &Xpow, swb: &[u16], offsets: &[i32]) -> i32 { - let num_swb = swb.len() - 1; - let mut floor = 0i32; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let maxp = xp.max_pow(s, e); // = (max|x|)^0.75 - if maxp <= 1e-9 { - continue; - } - let min_sf = (100.0 - (MAX_QUANT as f64 / maxp).log2() / 0.1875).ceil() as i32; - floor = floor.max(min_sf - offsets[sfb]); - } - floor.clamp(0, 255) -} - -/// Fast body-bit estimate at a candidate `base`: quantize (cheap) and price each -/// coefficient from the `coef_bits` table — no codebook search. Monotone in `base`, -/// so it seeds the search; the exact refinement corrects it. -fn estimate_bits(xp: &Xpow, swb: &[u16], offsets: &[i32], base: i32) -> usize { - let scale = scale_table(); - let ct = coef_bits(); - let num_swb = swb.len() - 1; - let mut bits = 22usize; // global_gain + ics_info + flags, approx - let mut qbuf = [0i32; 128]; // one band (max long SWB width is 96) - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let w = e - s; - let sc = scale[(base + offsets[sfb]).clamp(0, 255) as usize]; - quantize_band(&xp.pow[s..e], &xp.sign[s..e], sc, &mut qbuf[..w]); - let mut band = 0usize; - let mut nonzero = false; - for &q in &qbuf[..w] { - let m = q.unsigned_abs() as usize; - if m != 0 { - nonzero = true; - band += ct[m] as usize; - } - } - if nonzero { - bits += 9 + band; // ~section + scalefactor + spectrum for the band - } - } - bits -} - -/// The smallest common `base` (≥ the no-clamp floor) whose ICS body fits -/// `target_bits` — finest quality within budget. A fast estimate seeds the search; -/// the exact coder then walks to the true boundary (identical to a full search, but -/// only a couple of exact evaluations instead of eight). Body bits fall as `base` -/// rises. -fn rate_loop(xp: &Xpow, swb: &[u16], offsets: &[i32], target_bits: usize) -> i32 { - let min_b = min_base(xp, swb, offsets); - // Phase 1: binary-search the cheap estimate. - let (mut lo, mut hi) = (min_b, 255i32); - while lo < hi { - let mid = (lo + hi) / 2; - if estimate_bits(xp, swb, offsets, mid) <= target_bits { - hi = mid; - } else { - lo = mid + 1; - } - } - // Phase 2: refine to the exact smallest fitting base with the real coder, reusing - // one quant buffer across the (few) exact evaluations. - let mut quant = vec![0i32; xp.len()]; - let mut exact = - |b: i32| code_core(xp, swb, &scalefactors(offsets, b), &mut quant).1 <= target_bits; - let mut base = lo; - if exact(base) { - while base > min_b && exact(base - 1) { - base -= 1; - } - } else { - while base < 255 && !exact(base) { - base += 1; - } - } - base -} - -/// section_data (single group, long block): 4-bit codebook + 5-bit run-length -/// increments (esc = 31 continues the run). -fn write_sections(w: &mut BitWriter, cbs: &[u8]) { - let esc = 31u32; - let mut k = 0usize; - while k < cbs.len() { - let cb = cbs[k]; - let mut len = 1usize; - while k + len < cbs.len() && cbs[k + len] == cb { - len += 1; - } - w.write(cb as u32, 4); - let mut l = len as u32; - while l >= esc { - w.write(esc, 5); - l -= esc; - } - w.write(l, 5); - k += len; - } -} - -/// scale_factor_data: each coded band's scalefactor as a `SCALEFACTOR_BOOK` delta -/// from a running accumulator seeded at `gg` (matching the decoder). -fn write_scalefactors(w: &mut BitWriter, cbs: &[u8], sf: &[i32], gg: i32) { - // THREE independent accumulators, exactly as `decode::read_scalefactors` - // maintains them. Folding PNS or intensity values into the regular chain - // desynchronizes every later band, which decodes as garbage rather than as a - // slightly wrong gain. - let mut acc = gg; - let mut noise = gg - 90; - let mut noise_pcm = true; - let mut is_pos = 0i32; - for (sfb, &cb) in cbs.iter().enumerate() { - if cb == ZERO_HCB { - continue; - } else if cb >= crate::codebook::INTENSITY_HCB2 { - let d = (sf[sfb] - is_pos).clamp(-60, 60); - let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize); - w.write(code, len as u32); - is_pos += d; - } else if cb == NOISE_HCB { - if noise_pcm { - // The first PNS band is a 9-bit PCM delta, not a Huffman one. - noise_pcm = false; - let d = (sf[sfb] - noise).clamp(-256, 255); - w.write((d + 256) as u32, 9); - noise += d; - } else { - let d = (sf[sfb] - noise).clamp(-60, 60); - let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize); - w.write(code, len as u32); - noise += d; - } - } else { - let d = (sf[sfb] - acc).clamp(-60, 60); - let (code, len) = crate::tables::SCALEFACTOR_BOOK.code((d + 60) as usize); - w.write(code, len as u32); - acc += d; - } - } -} - -/// **Arm A6 — Perceptual Noise Substitution.** -/// -/// Replace a noise-like band's coefficients with a single transmitted *energy*; -/// the decoder refills it with scaled random noise (`decode::fill_noise`). The -/// band costs a scalefactor instead of a spectrum, which at low rates is the -/// difference between coding a band and zeroing it. -/// -/// The P0 baseline is the motivation: `speech-noisy` and `noise-like` sit at -/// 99%+ audible from 64-128k and only clear at 192k — broadband noise has no -/// maskers to hide under and is unaffordable, which is exactly the problem PNS -/// exists to solve. -/// -/// The gate is deliberately conservative on all three axes, because PNS destroys -/// phase and is audibly destructive on a harmonic band (the `music-tonal` -/// anti-class): -/// -/// * **frequency** — only above `PNS_MIN_HZ`; PNS on the bass is never right, -/// * **tonality** — only bands the SFM calls noise-like, -/// * **energy** — only bands actually carrying signal. -/// -/// Returns the noise-energy value to transmit for each substituted band. -/// `fill_noise` produces band energy `2^(ne/2)`, so `ne = 2*log2(E)`. -fn pns_bands( - spec: &[f32], - swb: &[u16], - sample_rate: u32, - tonality: &[f32], - max_sfb: usize, -) -> Vec> { - const PNS_MIN_HZ: f64 = 4000.0; - const PNS_MAX_TONALITY: f32 = 0.10; - /// A frame this tonal overall gets NO PNS at all, whatever individual bands - /// say. See the band-level trap below. - const PNS_MAX_FRAME_TONALITY: f32 = 0.15; - /// A band must carry at least this fraction of the frame's MEAN band energy - /// to be worth substituting — population-relative (law 1), not absolute. - const PNS_MIN_ENERGY_FRAC: f64 = 0.5; - - let num_swb = swb.len() - 1; - let mut out = vec![None; num_swb]; - - // Band energies once, and the frame's energy-weighted tonality. - let mut energies = vec![0f64; num_swb]; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - energies[sfb] = spec[s..e.min(spec.len())] - .iter() - .map(|&x| (x as f64) * (x as f64)) - .sum(); - } - let total: f64 = energies.iter().sum::() + 1e-9; - let frame_tonality = - (0..num_swb).map(|i| energies[i] * tonality[i] as f64).sum::() / total; - - // **The band-level trap, measured.** A near-EMPTY band has a flat spectrum, - // so its spectral flatness measure reads as maximally *noise-like* — SFM - // cannot distinguish "broadband noise" from "almost nothing". A band-only - // gate therefore substitutes noise into the empty bands surrounding a pure - // tone, which is how the first version of this fired on a 6 kHz sine. - // - // Two guards, because they fail in different directions: the frame-level veto - // refuses tonal CONTENT outright, and the relative energy floor refuses - // individual bands with nothing in them. - if frame_tonality as f32 > PNS_MAX_FRAME_TONALITY { - return out; - } - let mean_band = total / num_swb as f64; - - for sfb in 0..num_swb.min(max_sfb) { - let lo_hz = swb[sfb] as f64 * sample_rate as f64 * 0.5 / FRAME_LEN as f64; - if lo_hz < PNS_MIN_HZ || tonality[sfb] > PNS_MAX_TONALITY { - continue; - } - let energy = energies[sfb]; - if energy <= 1.0 || energy < mean_band * PNS_MIN_ENERGY_FRAC { - continue; // nothing meaningful there to substitute - } - let ne = (2.0 * energy.log2()).round() as i32; - out[sfb] = Some(ne.clamp(-100, 255)); - } - out -} - -/// spectral_data: per regular SFB, code coefficient tuples with the band's book. -fn write_spectrum(w: &mut BitWriter, quant: &[i32], cbs: &[u8], swb: &[u16]) { - for (sfb, &cb) in cbs.iter().enumerate() { - // ZERO, NOISE (PNS) and intensity bands carry no spectral data — their - // whole point is that the coefficients are not transmitted. - if cb == ZERO_HCB || cb >= NOISE_HCB { - continue; - } - let dim = CODEBOOKS[cb as usize].dim as usize; - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let mut i = s; - while i + dim <= e { - spectral_emit(cb as usize, &quant[i..i + dim], w); - i += dim; - } - } -} - -/// Encode one channel as a single_channel_element for a long or transition block -/// (`seq` ∈ {OnlyLong, LongStart, LongStop}): psy offsets → rate loop over the -/// common base → per-band scalefactors → coded ICS. -#[allow(clippy::too_many_arguments)] -fn encode_channel_element( - w: &mut BitWriter, - tag: u32, - spec: &[f32], - swb: &[u16], - seq: WindowSequence, - sample_rate: u32, - target_bits: usize, - cur_kbd: bool, - psy: PsyCfg, - elem_id: u32, -) { - // Pass 1, un-filtered: the TNS span depends on max_sfb, which only exists - // after quantization. This pass exists to learn it. - let offsets0 = perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr); - let xp0 = Xpow::new(spec); - let base0 = rate_loop(&xp0, swb, &offsets0, target_bits); - let sf0 = scalefactors(&offsets0, base0); - let (cbs0, _, max_sfb0, quant0) = code_frame(&xp0, swb, &sf0); - - // Arm A3. Only engage when the coded range already reaches TNS_MAX_LONG, so - // the decoder's span `min(TNS_MAX_LONG, max_sfb)` is pinned to TNS_MAX_LONG - // on BOTH sides regardless of what the re-quantization does to max_sfb. The - // alternative (span depending on a max_sfb that pass 2 can move) is a - // bitstream desync waiting to happen. - let fs_index = crate::sf_index_for_rate(sample_rate).unwrap_or(4); - let tns_max = crate::decode::TNS_MAX_LONG[fs_index as usize] as usize; - let mut tns: Option = None; - // ARM A3 ROUTING GATE. Spectral LPC prediction gain alone is NOT a transient - // detector: a peaky TONAL spectrum predicts just as well as an impulsive one, - // so a gain-only gate fires on sustained content, where temporal noise - // shaping has nothing to shape and simply costs bits. Measured (PEAQ, vs the - // previous default): tonal -1.02, mixed -1.14, quiet -1.05, while percussive - // moved only -0.01. It was firing almost exclusively on the wrong content. - // - // The fix is to require the frame to be transient-ADJACENT: only the - // LongStart / LongStop frames that bracket a detected attack. Those are - // exactly the long blocks that carry pre-echo, and the window sequence - // already names them, so the gate is free. - let tns_frame_ok = seq != WindowSequence::OnlyLong; - let (cbs, sf, max_sfb, quant) = if psy.tns && tns_frame_ok && max_sfb0 >= tns_max { - let mut filtered = spec.to_vec(); - match tns_analyze_long(&mut filtered, swb, fs_index, max_sfb0) { - Some(t) => { - let offsets = perceptual_offsets(&filtered, swb, sample_rate, psy.tonality_smr); - let xp = Xpow::new(&filtered); - let base = rate_loop(&xp, swb, &offsets, target_bits); - let sf = scalefactors(&offsets, base); - let (mut cbs, _, msfb, quant) = code_frame(&xp, swb, &sf); - // Hold max_sfb at or above tns_max, padding with ZERO bands, so - // the decoder's TNS span is exactly the one we filtered. - let msfb = msfb.max(tns_max); - cbs.resize(msfb, ZERO_HCB); - tns = Some(t); - (cbs, sf, msfb, quant) - } - None => (cbs0, sf0, max_sfb0, quant0), - } - } else { - (cbs0, sf0, max_sfb0, quant0) - }; - // Arm A6 — PNS. Substituted bands trade their spectrum for one energy value. - // - // Skipped when TNS fired: the decoder fills noise BEFORE inverse-filtering, - // so with TNS active the transmitted energy would have to be expressed in the - // filtered domain. That combination is not yet validated, and a wrong energy - // there is not a small error - it is a band of noise at the wrong level. - let (mut cbs, mut sf) = (cbs, sf); - if psy.pns && tns.is_none() { - let ton = band_tonality(spec, swb, 1, FRAME_LEN); - for (b, ne) in pns_bands(spec, swb, sample_rate, &ton, max_sfb) - .into_iter() - .enumerate() - { - if let (Some(ne), Some(cb)) = (ne, cbs.get_mut(b)) { - if *cb != ZERO_HCB && *cb < NOISE_HCB { - *cb = NOISE_HCB; - sf[b] = ne; - } - } - } - } - let gg = global_gain(&cbs, &sf); - - w.write(elem_id, 3); - w.write(tag, 4); - w.write(gg as u32, 8); - let info = IcsInfo { - window_sequence: seq, - window_shape_kbd: cur_kbd, - max_sfb: max_sfb as u8, - num_windows: 1, - num_window_groups: 1, - window_group_length: vec![1], - num_swb: swb.len() - 1, - }; - encode_ics_info(w, &info); - write_sections(w, &cbs); - write_scalefactors(w, &cbs, &sf, gg); - w.write(0, 1); // pulse_data_present - match &tns { - Some(t) => { - w.write(1, 1); // tns_data_present - write_tns_long(w, t); - } - None => w.write(0, 1), - } - w.write(0, 1); // gain_control_data_present - write_spectrum(w, &quant, &cbs, swb); -} - - -// --------------------------------------------------------------------------- -// Arm A3 (Rung 3) — Temporal Noise Shaping. -// -// The AAC tool for pre-echo, and a large part of why AAC beats MP3 on speech. -// The decoder has implemented it since day one (`decode::apply_tns`); the encoder -// emitted `tns_data_present = 0` at all three sites. -// -// The decoder runs an ALL-POLE (synthesis) filter over the spectrum: -// orig[n] = resid[n] - SUM_k lpc[k] * orig[n-k] -// so the encoder must run the matching ALL-ZERO (analysis) filter: -// resid[n] = orig[n] + SUM_k lpc[k] * orig[n-k] -// with the state holding past *inputs* (the original spectrum), not past outputs. -// Getting that inversion backwards does not sound slightly worse; it diverges. -// --------------------------------------------------------------------------- - -/// One TNS filter the encoder decided to apply, in emit form. -#[derive(Debug, Clone)] -pub(crate) struct TnsEnc { - /// Span in scalefactor bands, counted down from the top. - pub length: usize, - pub order: usize, - /// Quantized PARCOR indices (4-bit two's complement, `coef_res = 1`). - pub idx: Vec, - /// The de-quantized PARCOR values the decoder will reconstruct — the encoder - /// must filter with *these*, not with the unquantized ones, or encoder and - /// decoder run different filters. - pub parcor: Vec, -} - -/// Coefficient resolution we emit: `coef_res = 1` (4-bit), `coef_compress = 0`. -/// The widest grid AAC-LC offers, so quantization error in the filter itself is -/// as small as the syntax allows. -const TNS_COEF_RES: u32 = 1; -const TNS_COEF_BITS: u32 = 4; -/// Max order for AAC-LC long blocks (the syntax allows 5 bits; 12 is the ISO cap). -const TNS_MAX_ORDER: usize = 12; -/// Prediction gain below which TNS is not worth its bits. PROVISIONAL — the -/// classic value; the calculator has not fitted it. -const TNS_MIN_GAIN: f64 = 1.4; - -/// Quantize one PARCOR value to the 4-bit grid and return `(index, dequantized)`. -/// -/// Exact inverse of the decoder's dequantizer, including its **asymmetric** -/// scale factors (`iqfac` for non-negative, `iqfac_m` for negative) — a single -/// shared factor would round half the coefficients to the wrong index. -fn quantize_parcor(p: f32) -> (i32, f32) { - use std::f32::consts::PI; - let res_bits = 3 + TNS_COEF_RES; - let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0); - let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0); - let t = p.clamp(-0.999, 0.999).asin(); - let lo = -(1i32 << (TNS_COEF_BITS - 1)); - let hi = (1i32 << (TNS_COEF_BITS - 1)) - 1; - let c = if t >= 0.0 { - (t * iqfac).round() as i32 - } else { - (t * iqfac_m).round() as i32 - } - .clamp(lo, hi); - // Reconstruct exactly as the decoder will. - let t_back = if c >= 0 { - c as f32 / iqfac - } else { - c as f32 / iqfac_m - }; - (c, t_back.sin()) -} - -/// PARCOR (reflection coefficients) -> LPC, matching `decode::parcor_to_lpc`. -fn parcor_to_lpc_enc(parcor: &[f32]) -> Vec { - let order = parcor.len(); - let mut lpc = vec![0f32; order + 1]; - lpc[0] = 1.0; - for m in 1..=order { - let mut tmp = lpc.clone(); - for i in 1..m { - tmp[i] = lpc[i] + parcor[m - 1] * lpc[m - i]; - } - lpc[..m].copy_from_slice(&tmp[..m]); - lpc[m] = parcor[m - 1]; - } - lpc -} - -/// Levinson-Durbin over `spec[start..end]`, returning `(parcor, prediction_gain)`. -fn spectral_parcor(spec: &[f32], start: usize, end: usize, order: usize) -> (Vec, f64) { - let n = end.saturating_sub(start); - if n <= order + 1 { - return (Vec::new(), 1.0); - } - let x = &spec[start..end]; - let mut r = vec![0f64; order + 1]; - for (lag, slot) in r.iter_mut().enumerate() { - let mut acc = 0f64; - for i in 0..n - lag { - acc += x[i] as f64 * x[i + lag] as f64; - } - *slot = acc; - } - if r[0] <= 1e-12 { - return (Vec::new(), 1.0); - } - let r0 = r[0] * 1.0001; // white-noise correction - r[0] = r0; - let mut a = vec![0f64; order + 1]; - let mut parcor = Vec::with_capacity(order); - let mut err = r0; - for i in 1..=order { - let mut acc = r[i]; - for j in 1..i { - acc -= a[j] * r[i - j]; - } - let k = acc / err; - if !k.is_finite() || k.abs() >= 0.999 { - break; - } - let prev: Vec = a[1..i].to_vec(); - for j in 1..i { - a[j] = prev[j - 1] - k * prev[i - j - 1]; - } - a[i] = k; - parcor.push(k as f32); - err *= 1.0 - k * k; - if err <= 1e-12 { - break; - } - } - (parcor, r0 / err.max(1e-12)) -} - -/// **The Rung 3 gate + arm.** Decide whether to apply TNS to a long block and, if -/// so, filter `spec` in place and return the data to emit. -/// -/// `max_sfb_hint` must be the `max_sfb` that will be written, because the decoder -/// filters over `min(TNS_MAX_LONG, max_sfb)` bands — encoder and decoder must -/// agree on the span exactly or the inverse filter runs over the wrong region. -/// -/// Returns `None` when the gate declines (prediction gain below threshold, span -/// too short, or a degenerate fit), in which case `spec` is untouched and the -/// caller emits `tns_data_present = 0` — the byte-identical fallback. -pub(crate) fn tns_analyze_long( - spec: &mut [f32], - swb: &[u16], - fs_index: u8, - max_sfb: usize, -) -> Option { - let num_swb = swb.len() - 1; - let tns_max = crate::decode::TNS_MAX_LONG[fs_index as usize] as usize; - let mmm = tns_max.min(max_sfb); - if mmm < 4 { - return None; - } - // One filter spanning the top of the coded range down to band `bottom`. The - // decoder derives `start`/`end` from `length` the same way. - let bottom = mmm / 4; // skip the lowest quarter: TNS on the bass is harmful - let length = num_swb.saturating_sub(bottom); - let start = swb[bottom.min(mmm)] as usize; - let end = swb[mmm] as usize; - if end <= start + TNS_MAX_ORDER + 1 { - return None; - } - - let (parcor_raw, gain) = spectral_parcor(spec, start, end, TNS_MAX_ORDER); - if parcor_raw.is_empty() || gain < TNS_MIN_GAIN { - return None; // the gate: not worth its bits - } - - // Quantize to the shipping 4-bit grid, and keep the DEQUANTIZED values — - // filtering with the unquantized ones would leave the decoder running a - // slightly different filter, which shows up as drift across the band. - let mut idx = Vec::with_capacity(parcor_raw.len()); - let mut parcor = Vec::with_capacity(parcor_raw.len()); - for &p in &parcor_raw { - let (c, dq) = quantize_parcor(p); - idx.push(c); - parcor.push(dq); - } - // Drop trailing zero-index coefficients: they cost 4 bits each and do nothing. - while idx.len() > 1 && *idx.last().unwrap() == 0 { - idx.pop(); - parcor.pop(); - } - let order = idx.len(); - if order == 0 { - return None; - } - - let lpc = parcor_to_lpc_enc(&parcor); - - // The ANALYSIS filter (all-zero), upward direction, state = past inputs. - // Indexed rather than iterated: the filter reads and writes the same slice - // element each step, which an iterator form cannot express without a copy. - #[allow(clippy::needless_range_loop)] - let mut state = vec![0f32; order]; - #[allow(clippy::needless_range_loop)] - for p in start..end { - let xn = spec[p]; - let mut y = xn; - for j in 0..order { - y += state[j] * lpc[j + 1]; - } - for j in (1..order).rev() { - state[j] = state[j - 1]; - } - state[0] = xn; - spec[p] = y; - } - - Some(TnsEnc { - length, - order, - idx, - parcor, - }) -} - -/// Emit `tns_data` for a long block (`n_filt` 2 bits, `length` 6, `order` 5). -/// Mirrors `decode::parse_tns` exactly. -pub(crate) fn write_tns_long(w: &mut BitWriter, tns: &TnsEnc) { - w.write(1, 2); // n_filt = 1 - w.write(TNS_COEF_RES, 1); // coef_res - w.write(tns.length as u32, 6); - w.write(tns.order as u32, 5); - if tns.order > 0 { - w.write(0, 1); // direction: upward (low -> high) - w.write(0, 1); // coef_compress = 0 - for &c in &tns.idx { - let masked = (c as u32) & ((1u32 << TNS_COEF_BITS) - 1); - w.write(masked, TNS_COEF_BITS); - } - } -} - -// --------------------------------------------------------------------------- -// Block switching (brick 5) — transient detection, window-sequence assignment, -// and the short-block coding path (eight 128-bin windows, one group). -// --------------------------------------------------------------------------- - -/// Flag each 1024-sample frame that contains a transient: a 128-sample sub-block -/// whose energy leaps above the recent running average (an attack). Frame 0 is -/// never flagged — nothing precedes it to open a LongStart transition from. -/// -/// `pub(crate)` so [`crate::lab::signals`] can record what the *shipping* -/// detector decides alongside the campaign's replacement signal — the -/// gate-calculator's `shipped` column (arm A9). -pub(crate) fn detect_transients(chan: &[f32], nframes: usize) -> Vec { - const RATIO: f64 = 10.0; - // (arm A9 replaces the guard below; see `detect_transients_relative`) - let mut flags = vec![false; nframes]; - let mut avg = 0.0f64; - for (f, flag) in flags.iter_mut().enumerate() { - let mut attack = 1.0f64; - for sb in 0..8 { - let start = f * FRAME_LEN + sb * SHORT_HALF; - let e: f64 = (0..SHORT_HALF) - .map(|i| { - let x = chan.get(start + i).copied().unwrap_or(0.0) as f64; - x * x - }) - .sum(); - if avg > 1e-3 { - attack = attack.max(e / avg); - } - avg = 0.75 * avg + 0.25 * e; - } - if f > 0 && attack > RATIO { - *flag = true; - } - } - flags -} - -/// Per-frame **population-relative** max attack ratio — the level-invariant -/// replacement for [`detect_transients`]'s absolute `avg > 1e-3` guard (arm A9). -/// -/// The running average is floored at a fraction of *this clip's own* mean -/// sub-block energy, so both numerator and floor scale with level and the ratio -/// is unchanged by a gain change. The shipping detector's absolute floor makes it -/// blind on quiet content and, because the average decays 0.75× per sub-block, on -/// sparse attacks over a quiet floor at *any* level. -/// -/// Used by the Rung 0 shape gate as a transient veto; it is also the signal arm -/// A9 will replace the detector's threshold with. -pub(crate) fn frame_attack_ratios(chan: &[f32], nframes: usize) -> Vec { - let mut sub: Vec = Vec::with_capacity(nframes * 8); - for f in 0..nframes { - for sb in 0..8 { - let start = f * FRAME_LEN + sb * SHORT_HALF; - let e: f64 = (0..SHORT_HALF) - .map(|i| { - let x = chan.get(start + i).copied().unwrap_or(0.0) as f64; - x * x - }) - .sum(); - sub.push(e); - } - } - let mean_e = sub.iter().sum::() / sub.len().max(1) as f64; - let floor = (mean_e * 1e-3).max(f64::MIN_POSITIVE); - - let mut avg = 0.0f64; - let mut out = Vec::with_capacity(nframes); - for f in 0..nframes { - let mut amax = 1.0f32; - for sb in 0..8 { - let e = sub[f * 8 + sb]; - amax = amax.max((e / avg.max(floor)) as f32); - avg = 0.75 * avg + 0.25 * e; - } - out.push(amax); - } - out -} - -/// **Arm A9 — the level-invariant transient detector.** -/// -/// Same decision rule as [`detect_transients`] (`attack ratio > 10`), on a signal -/// that is actually defined. The shipped detector guards its ratio with -/// `avg > 1e-3` — an **absolute** energy floor — which has two consequences the -/// P1 truth table pinned: -/// -/// * the identical waveform 40 dB quieter stops being detected at all, and -/// * because the running average decays 0.75x per sub-block, it falls under the -/// floor across the quiet stretch between sparse attacks, so castanet-like -/// content is missed **at any level** — measured: zero frames flagged on the -/// percussive corpus class whose p95 attack ratio is ~30000x. -/// -/// The ratio itself is already scale-invariant; only the guard was not. This -/// version floors the running average relative to the clip's own mean sub-block -/// energy instead, which is the law-1 form and leaves the threshold meaning what -/// it says. -/// -/// This is not merely a quality knob: arm A1 (short-block psy) can only reach -/// frames that are coded as short blocks, so a detector that never fires makes A1 -/// unmeasurable. A9 is A1's prerequisite. -pub(crate) fn detect_transients_relative(chan: &[f32], nframes: usize) -> Vec { - const RATIO: f32 = 10.0; - let ratios = frame_attack_ratios(chan, nframes); - (0..nframes) - .map(|f| f > 0 && ratios.get(f).copied().unwrap_or(1.0) > RATIO) - .collect() -} - -/// Assign a valid AAC window sequence to each frame from the transient flags. A -/// short run is bracketed by LongStart/LongStop; runs a single frame apart are -/// merged (a lone gap can't be both a stop and a start). -fn assign_sequences(transient: &[bool]) -> Vec { - use WindowSequence::*; - let n = transient.len(); - let mut short = transient.to_vec(); - for i in 1..n.saturating_sub(1) { - if !short[i] && short[i - 1] && short[i + 1] { - short[i] = true; - } - } - let mut seq = vec![OnlyLong; n]; - let mut i = 0; - while i < n { - if short[i] { - let a = i; - while i < n && short[i] { - seq[i] = EightShort; - i += 1; - } - if a > 0 { - seq[a - 1] = LongStart; - } - if i < n { - seq[i] = LongStop; - } - } else { - i += 1; - } - } - seq -} - -/// Cheapest codebook (and its bit cost) for one SFB across all short windows of a -/// single group, matched to how the decoder reads it (per-SFB codebook, per-window -/// coefficients). -fn best_codebook_short(quant: &[i32], swb: &[u16], sfb: usize, nwin: usize) -> (u8, usize) { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let mut maxq = 0u32; - for win in 0..nwin { - let base = win * SHORT_HALF; - for &q in &quant[base + s..base + e] { - maxq = maxq.max(q.unsigned_abs()); - } - } - if maxq == 0 { - return (ZERO_HCB, 0); - } - let mut best = (ESC_HCB, usize::MAX); - for cb in 1..=11u8 { - let meta = &CODEBOOKS[cb as usize]; - let dim = meta.dim as usize; - if (e - s) % dim != 0 || (!meta.esc && (meta.lav as u32) < maxq) { - continue; - } - let mut bits = 0usize; - let mut ok = true; - 'windows: for win in 0..nwin { - let base = win * SHORT_HALF; - let mut i = s; - while i < e { - match spectral_bits(cb as usize, &quant[base + i..base + i + dim]) { - Some(b) => bits += b, - None => { - ok = false; - break 'windows; - } - } - i += dim; - } - } - if ok && bits < best.1 { - best = (cb, bits); - } - } - best -} - -/// Bits for short-block section_data (3-bit run-length increments, esc = 7). -fn section_bits_short(cbs: &[u8]) -> usize { - let esc = 7usize; - let mut bits = 0usize; - let mut k = 0usize; - while k < cbs.len() { - let cb = cbs[k]; - let mut len = 1usize; - while k + len < cbs.len() && cbs[k + len] == cb { - len += 1; - } - bits += 4; - let mut l = len; - while l >= esc { - bits += 3; - l -= esc; - } - bits += 3; - k += len; - } - bits -} - -/// Quantize all eight short windows with a per-SFB scalefactor (one group; flat -/// this brick), pick per-SFB codebooks, and return (codebooks, body bits, max_sfb, -/// window-major quantized spectrum). -fn code_frame_short(xp: &Xpow, swb: &[u16], sf: &[i32]) -> (Vec, usize, usize, Vec) { - work::bump_code_frame(); - let num_swb = swb.len() - 1; - work::bump_quant_bands(((swb.len() - 1) * 8) as u64); - let scale = scale_table(); - let mut quant = vec![0i32; FRAME_LEN]; - for win in 0..8 { - let base = win * SHORT_HALF; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let sc = scale[sf[sfb].clamp(0, 255) as usize]; - quantize_band( - &xp.pow[base + s..base + e], - &xp.sign[base + s..base + e], - sc, - &mut quant[base + s..base + e], - ); - } - } - let mut max_sfb = 0usize; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - if (0..8).any(|win| { - let base = win * SHORT_HALF; - quant[base + s..base + e].iter().any(|&q| q != 0) - }) { - max_sfb = sfb + 1; - } - } - let mut cbs = Vec::with_capacity(max_sfb); - let mut spec_bits = 0usize; - for sfb in 0..max_sfb { - let (cb, bits) = best_codebook_short(&quant, swb, sfb, 8); - cbs.push(cb); - spec_bits += bits; - } - let gg = global_gain(&cbs, sf); - // global_gain(8) + ics_info(short ~18) + 3 flags + sections + scalefactors + spectrum. - let body = 8 + 18 + 3 + section_bits_short(&cbs) + scalefactor_bits(&cbs, sf, gg) + spec_bits; - (cbs, body, max_sfb, quant) -} - -/// The smallest flat scalefactor that avoids clamping the loudest short coefficient -/// past `MAX_QUANT`. -fn min_base_short(xp: &Xpow) -> i32 { - let maxp = xp.max_pow(0, xp.len()); - if maxp <= 1e-9 { - return 0; - } - (100.0 - (MAX_QUANT as f64 / maxp).log2() / 0.1875) - .ceil() - .clamp(0.0, 255.0) as i32 -} - -/// **Arm A1 — the short-block psychoacoustic model.** -/// -/// Per-SFB scalefactor offsets for an EightShort frame. The band energies are -/// summed **across the eight windows** of the group, because with one window group -/// a scalefactor covers band `b` of all eight windows — so the mask must be -/// computed over exactly the coefficients that scalefactor governs. -/// -/// The band geometry is the short SWB table over a 128-coefficient window, hence -/// `n_coeffs = SHORT_HALF`: reusing the long block's 1024 here would place every -/// band three octaves too low and spread the mask against the wrong neighbours. -/// -/// Before this arm, short blocks coded with **flat** scalefactors — no noise -/// shaping at all on precisely the content where masking matters most. -/// -/// # MEASURED REFUTATION (2026-08-08): this is harmful WITHOUT window grouping -/// -/// Once arm A9 made short blocks actually occur, A1 became measurable — and it -/// made things **worse**, on both the class it was built for and the one it was -/// meant to be neutral on: -/// -/// | arm | percussive 64k/128k | speech-clean 64k/128k | -/// |---|---|---| -/// | A9 alone | −2.81 / −6.10 | +1.56 / +1.18 | -/// | A9 + A1 | −1.18 / −5.50 | +2.33 / +1.46 | -/// -/// The cause is the group-summed energy above. With **one** window group a single -/// scalefactor governs band `b` of all eight windows, so the mask must be derived -/// from their sum — which hands the quiet pre-attack windows a mask sized by the -/// attack. That is precisely the pre-echo the tool was supposed to suppress: a -/// flat scalefactor at least errs uniformly, whereas an attack-sized mask -/// actively licenses noise where the ear is most sensitive. -/// -/// **This overturns a plan correction I made earlier.** Reading the emit path, I -/// argued grouping was a follow-up rather than a prerequisite, because per-SFB -/// shaping is available with one group. That is true and irrelevant: the shaping -/// available with one group is shaping in the *wrong domain*. Arm 1a (window -/// grouping) is a genuine prerequisite for A1, exactly as the original plan said. -/// Do not enable `short_block_psy` before grouping exists. -fn perceptual_offsets_short(spec: &[f32], swb: &[u16], sample_rate: u32, tonality_smr: bool) -> Vec { - let num_swb = swb.len() - 1; - let mut energy = vec![0.0f64; num_swb]; - let mut noise_scale = vec![0.0f64; num_swb]; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - for win in 0..8 { - let base = win * SHORT_HALF; - for k in s..e { - let Some(&x) = spec.get(base + k) else { continue }; - energy[sfb] += (x as f64) * (x as f64); - noise_scale[sfb] += (x.abs() as f64).sqrt(); - } - } - } - let mut e_masked: Vec = energy.iter().map(|&e| e + 1e-3).collect(); - let ton = tonality_smr.then(|| band_tonality(spec, swb, 8, SHORT_HALF)); - let thr = masking_from_energy(&e_masked, swb, sample_rate, SHORT_HALF, ton.as_deref()); - e_masked.clear(); - - let raw: Vec = (0..num_swb) - .map(|sfb| (thr[sfb] / (noise_scale[sfb] + 1e-6)).log2() / 0.375) - .collect(); - // Centre on the energy-bearing bands, exactly as the long-block path does. - let etot: f64 = energy.iter().sum::() + 1e-9; - let center: f64 = (0..num_swb).map(|i| raw[i] * energy[i]).sum::() / etot; - raw.iter() - .map(|&r| ((r - center).round() as i32).clamp(-60, 60)) - .collect() -} - -/// Rate loop for a short block: smallest common base (≥ no-clamp floor) whose body -/// fits `target_bits`. `offsets` is arm A1's per-band shape (all zeros reproduces -/// the flat-scalefactor behavior byte-identically). -fn rate_loop_short(xp: &Xpow, swb: &[u16], offsets: &[i32], target_bits: usize) -> i32 { - let mut lo = min_base_short(xp); - let mut hi = 255i32; - while lo < hi { - let mid = (lo + hi) / 2; - let sf = scalefactors(offsets, mid); - if code_frame_short(xp, swb, &sf).1 <= target_bits { - hi = mid; - } else { - lo = mid + 1; - } - } - lo -} - -/// short_block section_data (4-bit codebook + 3-bit run increments, esc = 7). -fn write_sections_short(w: &mut BitWriter, cbs: &[u8]) { - let esc = 7u32; - let mut k = 0usize; - while k < cbs.len() { - let cb = cbs[k]; - let mut len = 1usize; - while k + len < cbs.len() && cbs[k + len] == cb { - len += 1; - } - w.write(cb as u32, 4); - let mut l = len as u32; - while l >= esc { - w.write(esc, 3); - l -= esc; - } - w.write(l, 3); - k += len; - } -} - -/// short_block spectral_data: per SFB, per window (one group), coefficient tuples. -fn write_spectrum_short(w: &mut BitWriter, quant: &[i32], cbs: &[u8], swb: &[u16]) { - for (sfb, &cb) in cbs.iter().enumerate() { - if cb == ZERO_HCB { - continue; - } - let dim = CODEBOOKS[cb as usize].dim as usize; - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - for win in 0..8 { - let base = win * SHORT_HALF; - let mut i = s; - while i + dim <= e { - spectral_emit(cb as usize, &quant[base + i..base + i + dim], w); - i += dim; - } - } - } -} - -/// Encode one channel as an EightShort single_channel_element (one group of 8 -/// windows). Scalefactors are flat unless arm A1 (`psy.short_block_psy`) supplies -/// a per-band shape. -#[allow(clippy::too_many_arguments)] -fn encode_channel_element_short( - w: &mut BitWriter, - tag: u32, - spec: &[f32], - swb: &[u16], - target_bits: usize, - cur_kbd: bool, - sample_rate: u32, - psy: PsyCfg, -) { - let xp = Xpow::new(spec); - // Arm A1: a real per-band mask, or the flat fallback (all-zero offsets - // reproduce the shipped behavior byte-identically). - let offsets = if psy.short_block_psy { - perceptual_offsets_short(spec, swb, sample_rate, psy.tonality_smr) - } else { - vec![0i32; swb.len() - 1] - }; - let base = rate_loop_short(&xp, swb, &offsets, target_bits); - let sf = scalefactors(&offsets, base); - let (cbs, _, max_sfb, quant) = code_frame_short(&xp, swb, &sf); - let gg = global_gain(&cbs, &sf); - - w.write(ID_SCE, 3); - w.write(tag, 4); - w.write(gg as u32, 8); - let info = IcsInfo { - window_sequence: WindowSequence::EightShort, - window_shape_kbd: cur_kbd, - max_sfb: max_sfb as u8, - num_windows: 8, - num_window_groups: 1, - window_group_length: vec![8], - num_swb: swb.len() - 1, - }; - encode_ics_info(w, &info); - write_sections_short(w, &cbs); - write_scalefactors(w, &cbs, &sf, gg); - w.write(0, 1); // pulse_data_present - w.write(0, 1); // tns_data_present - w.write(0, 1); // gain_control_data_present - write_spectrum_short(w, &quant, &cbs, swb); -} - -// --------------------------------------------------------------------------- -// Stereo (brick 6) — a channel_pair_element with a common window and per-SFB M/S -// (mid/side) coding where the channels are correlated enough to pay off. -// --------------------------------------------------------------------------- - -/// Per-SFB M/S decision + mixed spectra. M/S wins when `E_M·E_S < E_L·E_R` (the -/// correlation criterion — raw energy always halves under the ½ scaling, so the -/// *product* is what predicts bit savings). Returns (ch0 = M or L, ch1 = S or R, -/// per-SFB ms_used). -fn mid_side( - l: &[f32], - r: &[f32], - swb: &[u16], - is_short: bool, - is_veto: &[bool], -) -> (Vec, Vec, Vec) { - let num_swb = swb.len() - 1; - let nwin = if is_short { 8 } else { 1 }; - let wlen = if is_short { SHORT_HALF } else { FRAME_LEN }; - let mut ch0 = l.to_vec(); - let mut ch1 = r.to_vec(); - let mut ms = vec![false; num_swb]; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let (mut el, mut er, mut em, mut es) = (0.0f64, 0.0, 0.0, 0.0); - for win in 0..nwin { - let base = win * wlen; - for i in s..e { - let (lv, rv) = (l[base + i] as f64, r[base + i] as f64); - let (m, sd) = ((lv + rv) * 0.5, (lv - rv) * 0.5); - el += lv * lv; - er += rv * rv; - em += m * m; - es += sd * sd; - } - } - // A band claimed by intensity stereo (arm A7) must stay L/R. - if em * es < el * er && !is_veto.get(sfb).copied().unwrap_or(false) { - ms[sfb] = true; - for win in 0..nwin { - let base = win * wlen; - for i in s..e { - let (lv, rv) = (l[base + i], r[base + i]); - ch0[base + i] = (lv + rv) * 0.5; - ch1[base + i] = (lv - rv) * 0.5; - } - } - } - } - (ch0, ch1, ms) -} - -/// Quantize one CPE channel to a target: psy per-band scalefactors (long) or flat -/// (short). Returns (per-SFB scalefactors, quantized spectrum). -fn quantize_channel( - spec: &[f32], - swb: &[u16], - is_short: bool, - sample_rate: u32, - target_bits: usize, - psy: PsyCfg, -) -> (Vec, Vec) { - let xp = Xpow::new(spec); - if is_short { - let offsets = if psy.short_block_psy { - perceptual_offsets_short(spec, swb, sample_rate, psy.tonality_smr) - } else { - vec![0i32; swb.len() - 1] - }; - let base = rate_loop_short(&xp, swb, &offsets, target_bits); - let sf = scalefactors(&offsets, base); - let (_, _, _, quant) = code_frame_short(&xp, swb, &sf); - (sf, quant) - } else { - let offsets = perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr); - let base = rate_loop(&xp, swb, &offsets, target_bits); - let sf = scalefactors(&offsets, base); - let (_, _, _, quant) = code_frame(&xp, swb, &sf); - (sf, quant) - } -} - -/// The highest SFB with a non-zero coefficient in either channel (both channels of -/// a common-window CPE share `max_sfb`). -fn joint_max_sfb(q0: &[i32], q1: &[i32], swb: &[u16], is_short: bool) -> usize { - let num_swb = swb.len() - 1; - let nwin = if is_short { 8 } else { 1 }; - let wlen = if is_short { SHORT_HALF } else { FRAME_LEN }; - let nz = |q: &[i32], s: usize, e: usize| { - (0..nwin).any(|win| { - let b = win * wlen; - q[b + s..b + e].iter().any(|&x| x != 0) - }) - }; - let mut m = 0; - for sfb in 0..num_swb { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - if nz(q0, s, e) || nz(q1, s, e) { - m = sfb + 1; - } - } - m -} - -/// Per-SFB codebooks for one channel over `0..max_sfb`. -fn codebooks(quant: &[i32], swb: &[u16], is_short: bool, max_sfb: usize) -> Vec { - (0..max_sfb) - .map(|sfb| { - if is_short { - best_codebook_short(quant, swb, sfb, 8).0 - } else { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - best_codebook_for_band(quant, s, e).0 - } - }) - .collect() -} - -/// ms_mask_present (2 bits) + the per-SFB mask when mixed. -fn write_ms_used(w: &mut BitWriter, ms_used: &[bool]) { - if ms_used.iter().all(|&b| !b) { - w.write(0, 2); - } else if ms_used.iter().all(|&b| b) { - w.write(2, 2); - } else { - w.write(1, 2); - for &b in ms_used { - w.write_bool(b); - } - } -} - -/// One channel's individual_channel_stream body inside a common-window CPE: -/// global_gain, section_data, scale_factor_data, the three flag bits, spectral_data -/// (no ics_info — it is shared). -fn write_channel_data( - w: &mut BitWriter, - cbs: &[u8], - sf: &[i32], - quant: &[i32], - swb: &[u16], - is_short: bool, -) { - let gg = global_gain(cbs, sf); - w.write(gg as u32, 8); - if is_short { - write_sections_short(w, cbs); - } else { - write_sections(w, cbs); - } - write_scalefactors(w, cbs, sf, gg); - w.write(0, 1); // pulse_data_present - w.write(0, 1); // tns_data_present - w.write(0, 1); // gain_control_data_present - if is_short { - write_spectrum_short(w, quant, cbs, swb); - } else { - write_spectrum(w, quant, cbs, swb); - } -} - -/// **Arm A13 — joint rate loop over a channel pair.** -/// -/// # The defect this fixes -/// -/// A CPE's two channels were each given `frame_budget / channel_count` bits and -/// run through **independent** rate loops. That is a fixed 50/50 split, so when -/// M/S makes the side channel nearly empty its bits are simply wasted — the mid -/// channel, which is what the listener hears, still gets only half the frame. -/// -/// Measured on perfectly-correlated stereo (`L == R`, so `S ≡ 0`) at 128 kbps, -/// per-channel reconstruction SNR: -/// -/// | encoder | SNR | -/// |---|---| -/// | independent per-channel loops | **10.6 dB** | -/// | ffmpeg native AAC | **38.8 dB** | -/// -/// # Why the obvious fix did not work -/// -/// The first attempt split the budget by each channel's perceptual entropy. It -/// made things *worse* (8.5 dB), because PE is degenerate under a purely -/// relative masking model: the mask is `SMR × spread(signal)`, so `E/thr ≈ -/// 1/SMR` for **any** non-silent channel regardless of its level. Both channels -/// report near-identical "demand" whatever they contain. A level-blind demand -/// estimate cannot allocate between levels. -/// -/// # What actually works -/// -/// Run **one** rate loop over the pair and give both channels a **common base** -/// scalefactor. A common base means a common quantizer step, i.e. both channels -/// are coded to the same noise floor relative to their own masks — which is the -/// textbook joint-stereo criterion. Bits then flow to whichever channel needs -/// them, because a near-empty side channel costs almost nothing at any base and -/// lets the loop settle on a finer base for the pair. -/// -/// This is a strict generalisation: for two channels of equal demand it lands on -/// the same place the independent loops did. -fn pair_body_bits( - xp0: &Xpow, - off0: &[i32], - xp1: &Xpow, - off1: &[i32], - swb: &[u16], - base: i32, - is_short: bool, - quant: &mut [i32], -) -> usize { - let (b0, b1) = if is_short { - ( - code_frame_short(xp0, swb, &scalefactors(off0, base)).1, - code_frame_short(xp1, swb, &scalefactors(off1, base)).1, - ) - } else { - ( - code_core(xp0, swb, &scalefactors(off0, base), quant).1, - code_core(xp1, swb, &scalefactors(off1, base), quant).1, - ) - }; - b0 + b1 -} - -/// Smallest common base whose combined body fits `target_total` bits. -#[allow(clippy::too_many_arguments)] -fn joint_rate_loop( - xp0: &Xpow, - off0: &[i32], - xp1: &Xpow, - off1: &[i32], - swb: &[u16], - target_total: usize, - is_short: bool, -) -> i32 { - let lo0 = if is_short { min_base_short(xp0) } else { min_base(xp0, swb, off0) }; - let lo1 = if is_short { min_base_short(xp1) } else { min_base(xp1, swb, off1) }; - let mut lo = lo0.max(lo1); - let mut hi = 255i32; - let mut quant = vec![0i32; xp0.len().max(xp1.len())]; - while lo < hi { - let mid = (lo + hi) / 2; - if pair_body_bits(xp0, off0, xp1, off1, swb, mid, is_short, &mut quant) <= target_total { - hi = mid; - } else { - lo = mid + 1; - } - } - lo -} - -/// **Arm A7 — intensity stereo.** -/// -/// Above a cutoff the ear localizes by ENVELOPE rather than waveform, so a band -/// of the second channel can be sent as a single scale factor applied to the -/// first: the decoder reconstructs `s1 = +-0.5^(0.25*is_pos) * s0` -/// (`decode::apply_is`). One value replaces a whole band's spectrum. -/// -/// This turns the stereo decision from binary into a **3-arm dispatch** — -/// `{L/R, M/S, IS}` — which is why it is applied after `mid_side` and only to -/// bands M/S declined: with `ms_used` set the pair is already (M, S), and -/// intensity on an S channel means something quite different from intensity on -/// an R channel. Restricting to the M/S-declined bands keeps the two tools from -/// interpreting each other's output. -/// -/// The anti-class is wide-stereo music, where collapsing a band to a scaled copy -/// destroys the image. Hence the correlation gate: only bands where the channels -/// genuinely already agree up to a gain. -/// **Arm A7 — intensity stereo.** -/// -/// Above a cutoff the ear localizes by ENVELOPE rather than waveform, so a band -/// of the right channel can be sent as a single scale factor applied to the left: -/// the decoder reconstructs `R = +-0.5^(0.25*is_pos) * L` (`decode::apply_is`). -/// One value replaces a whole band's spectrum. -/// -/// # Why this decides BEFORE `mid_side`, not after -/// -/// The first version ran after M/S and only touched bands M/S had declined — on -/// the reasoning that intensity on an S channel means something different from -/// intensity on an R channel. It never fired once. The bands where `R ~= k*L` -/// are exactly the bands where M/S wins (`E_M*E_S << E_L*E_R` for a scaled copy), -/// so "M/S declined it" and "intensity wants it" are near-disjoint by -/// construction. -/// -/// So intensity is decided on the ORIGINAL L/R spectra and **vetoes M/S** on the -/// bands it claims, which also keeps the decoder's sign rule simple: `apply_is` -/// flips the intensity sign when `ms_used` is set, and a band that is both is a -/// sign error waiting to happen. -/// -/// This makes the stereo decision a genuine **3-arm dispatch** — `{L/R, M/S, IS}` -/// — rather than two tools overwriting each other. The anti-class is wide-stereo -/// music, where collapsing a band to a scaled copy destroys the image; hence the -/// correlation gate. -fn intensity_decision( - spec_l: &[f32], - spec_r: &[f32], - swb: &[u16], - sample_rate: u32, -) -> Vec> { - /// Below this the ear localizes by waveform and intensity stereo is audible. - const IS_MIN_HZ: f64 = 6000.0; - /// How well `R ~= scale * L` must already hold, as |cos| between the bands. - const IS_MIN_CORR: f64 = 0.85; - - let num_swb = swb.len() - 1; - let mut out = vec![None; num_swb]; - for sfb in 0..num_swb { - let lo_hz = swb[sfb] as f64 * sample_rate as f64 * 0.5 / FRAME_LEN as f64; - if lo_hz < IS_MIN_HZ { - continue; - } - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let e = e.min(spec_l.len()).min(spec_r.len()); - if e <= s { - continue; - } - let (mut dot, mut e0, mut e1) = (0f64, 0f64, 0f64); - for i in s..e { - let (a, b) = (spec_l[i] as f64, spec_r[i] as f64); - dot += a * b; - e0 += a * a; - e1 += b * b; - } - if e0 <= 1.0 || e1 <= 1.0 { - continue; - } - if (dot / (e0.sqrt() * e1.sqrt())).abs() < IS_MIN_CORR { - continue; - } - // Least-squares gain, then the syntax's log grid: - // scale = 0.5^(0.25*is_pos) => is_pos = -4*log2(|scale|). - let scale = dot / e0; - if scale.abs() < 1e-6 { - continue; - } - let is_pos = (-4.0 * scale.abs().log2()).round() as i32; - if !(-20..=60).contains(&is_pos) { - continue; - } - out[sfb] = Some(( - if scale >= 0.0 { - INTENSITY_HCB - } else { - INTENSITY_HCB2 - }, - is_pos, - )); - } - out -} - -/// Encode a stereo pair as a common-window channel_pair_element with per-SFB M/S. -#[allow(clippy::too_many_arguments)] -fn encode_cpe( - w: &mut BitWriter, - tag: u32, - spec_l: &[f32], - spec_r: &[f32], - swb: &[u16], - seq: WindowSequence, - sample_rate: u32, - target_bits: usize, - cur_kbd: bool, - psy: PsyCfg, -) { - let is_short = seq == WindowSequence::EightShort; - // Arm A7 decides first, on the untouched L/R spectra, and vetoes M/S on the - // bands it claims. - let is_bands = if psy.intensity && !is_short { - intensity_decision(spec_l, spec_r, swb, sample_rate) - } else { - vec![None; swb.len() - 1] - }; - let is_veto: Vec = is_bands.iter().map(|b| b.is_some()).collect(); - let (ch0, ch1, ms_full) = mid_side(spec_l, spec_r, swb, is_short, &is_veto); - // Arm A13 ROUTING GATE. - // - // The joint loop is a large win when the pair is CORRELATED and a loss when - // it is not — a per-class sign flip, so it is routed rather than averaged: - // - // | content | 64k | 128k | - // |---|---|---| - // | guitar stereo (correlated) | +0.23 | **+1.15** | - // | piano stereo (correlated) | +0.01 | +0.26 | - // | wide/decorrelated stereo | −0.30 | −0.04 | - // - // The signal is already in hand: the fraction of coded bands M/S claimed. - // High means the two channels largely agree, so the side channel is cheap and - // a common base lets the mid channel take the bits it is wasting. Low means - // both channels carry independent content, both genuinely need their half, - // and forcing a common base starves whichever is harder. - // - // The signal is the pair's spectral correlation, measured directly. (The M/S - // flag fraction was tried first and does not separate: M/S still claims most - // bands on wide content because it only needs `E_M·E_S < E_L·E_R`, which a - // shared centre image satisfies.) Measured correlations: - // - // L == R (ideal) 1.00 -> joint wins hugely - // guitar stereo 0.84 -> joint wins +1.15 @128k - // piano stereo 0.47 -> joint wins +0.26 @128k - // synthetic wide 0.25 -> joint LOSES -0.30 @64k - // - // The threshold sits in the wide gap between 0.25 and 0.47. - let joint_ok = pair_correlation(spec_l, spec_r) >= JOINT_STEREO_MIN_CORR; - - let (sf0, quant0, sf1, quant1) = if psy.stereo_bit_split && joint_ok { - let off = |spec: &[f32]| -> Vec { - if is_short { - if psy.short_block_psy { - perceptual_offsets_short(spec, swb, sample_rate, psy.tonality_smr) - } else { - vec![0i32; swb.len() - 1] - } - } else { - perceptual_offsets(spec, swb, sample_rate, psy.tonality_smr) - } - }; - let (o0, o1) = (off(&ch0), off(&ch1)); - let (xp0, xp1) = (Xpow::new(&ch0), Xpow::new(&ch1)); - let base = joint_rate_loop(&xp0, &o0, &xp1, &o1, swb, target_bits * 2, is_short); - let (s0, s1) = (scalefactors(&o0, base), scalefactors(&o1, base)); - let q0 = if is_short { - code_frame_short(&xp0, swb, &s0).3 - } else { - code_frame(&xp0, swb, &s0).3 - }; - let q1 = if is_short { - code_frame_short(&xp1, swb, &s1).3 - } else { - code_frame(&xp1, swb, &s1).3 - }; - (s0, q0, s1, q1) - } else { - let (a, b) = quantize_channel(&ch0, swb, is_short, sample_rate, target_bits, psy); - let (c, d) = quantize_channel(&ch1, swb, is_short, sample_rate, target_bits, psy); - (a, b, c, d) - }; - let max_sfb = joint_max_sfb(&quant0, &quant1, swb, is_short); - let cbs0 = codebooks(&quant0, swb, is_short, max_sfb); - let mut cbs1 = codebooks(&quant1, swb, is_short, max_sfb); - let mut sf1 = sf1; - let mut ms_full = ms_full; - - // Arm A7 — stamp the claimed bands into channel 1's codebooks/scalefactors. - for (sfb, band) in is_bands.iter().enumerate().take(max_sfb) { - if let (Some((cb, is_pos)), Some(slot)) = (band, cbs1.get_mut(sfb)) { - *slot = *cb; - sf1[sfb] = *is_pos; - if let Some(m) = ms_full.get_mut(sfb) { - *m = false; - } - } - } - - w.write(ID_CPE, 3); - w.write(tag, 4); - w.write(1, 1); // common_window - let info = IcsInfo { - window_sequence: seq, - window_shape_kbd: cur_kbd, - max_sfb: max_sfb as u8, - num_windows: if is_short { 8 } else { 1 }, - num_window_groups: 1, - window_group_length: vec![if is_short { 8 } else { 1 }], - num_swb: swb.len() - 1, - }; - encode_ics_info(w, &info); - write_ms_used(w, &ms_full[..max_sfb]); - write_channel_data(w, &cbs0, &sf0, &quant0, swb, is_short); - write_channel_data(w, &cbs1, &sf1, &quant1, swb, is_short); -} - -// --------------------------------------------------------------------------- -// The encoder: buffers input, blocks into 1024-sample long frames, emits raw -// access units (add ADTS or MP4 framing around them as needed). -// --------------------------------------------------------------------------- - -/// Window-shape policy — **arm A8, Rung 0** of `docs/codec-aac-great-gate.md`. -/// -/// `window_shape` is a *free syntax element*: one bit already carried in every -/// `ics_info`, costing nothing to set either way, with both shapes implemented on -/// the decode side since day one. It shipped hardcoded to sine — census category 3. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum WindowShape { - /// Sine everywhere. **The neutral end**: byte-identical with the encoder as - /// it shipped before Rung 0 (proven by `shape_sine_is_byte_identical`). - #[default] - Sine, - /// KBD everywhere. Not a shipping mode — the *force-on* arm the calculator - /// needs: great-gate §4 requires force-on-everywhere to nearly tie the anchor - /// on the full ladder before a dispatch is built on it, because a big force-on - /// gap predicts a dominated dispatch. - Kbd, - /// **PROVISIONAL** (law 5). Per-frame dispatch on content tonality. Off by - /// default until the calculator banks a threshold from a harvest carrying the - /// full speed pair (law 7's opt-in → default-on ladder). - Auto, -} - -/// Encoder options. -#[derive(Debug, Clone, Copy)] -pub struct AacEncoderConfig { - /// Target bitrate in bits per second. Drives the per-frame rate loop. - /// Default: 128 000 (128 kbps). - pub bitrate_bps: u32, - /// Window-shape policy (arm A8). Default [`WindowShape::Sine`] — the - /// byte-identical neutral end. - pub window_shape: WindowShape, - /// The [`WindowShape::Auto`] gate's threshold, as a **percentile of this - /// clip's own** frame-tonality distribution (great-gate law 1: a - /// population-relative threshold transfers to content the fit never saw; an - /// absolute one does not). Frames above it code with KBD. - /// - /// Default 0.5 is a **placeholder, not a fitted value** — the calculator has - /// not banked this rung yet. `aacharvest` emits the CSV that will decide it. - pub shape_tonality_pct: f32, - /// **Arm A1, Rung 1** — run the psychoacoustic model on short blocks instead - /// of coding them with flat scalefactors. Default `false` (byte-identical). - pub short_block_psy: bool, - /// **Arm A2, Rung 2** — make the signal-to-mask ratio a function of band - /// tonality instead of a flat 18 dB. Default `false` (byte-identical). - pub tonality_smr: bool, - /// **Arm A3, Rung 3** — emit TNS on long blocks. Default `false` - /// (`tns_data_present = 0`, byte-identical). - pub tns: bool, - /// **Arm A9** — use the level-invariant transient detector. Default `false` - /// (byte-identical). Arm A1 is unmeasurable without this. - pub relative_transients: bool, - /// **Arm A6** — Perceptual Noise Substitution on long blocks. Default `false` - /// (byte-identical). - pub pns: bool, - /// **Arm A7** — intensity stereo on long-block CPEs. Default `false` - /// (byte-identical). - pub intensity: bool, - /// **Arm A13** — split a channel pair's bit budget by perceptual demand - /// rather than evenly. Default `false` (byte-identical). - pub stereo_bit_split: bool, -} - -impl Default for AacEncoderConfig { - fn default() -> Self { - AacEncoderConfig { - bitrate_bps: 128_000, - window_shape: WindowShape::Sine, - shape_tonality_pct: 0.5, - short_block_psy: false, - tonality_smr: false, - tns: false, - // DEFAULT ON — measured wins vs the previous default, PEAQ ODG: - // A9 mean +0.267, worst +0.000 (percussive +1.8, clean speech - // +1.1..+2.6, exactly 0.00 on every other class) - // A13 guitar stereo +1.17 @128k, piano stereo +0.22, routed by - // pair correlation so wide stereo is not harmed - relative_transients: true, - pns: false, - intensity: false, - stereo_bit_split: true, - } - } -} - -/// One encoded raw access unit (a `raw_data_block`, no ADTS framing). -#[derive(Debug, Clone)] -pub struct EncodedPacket { - pub data: Vec, - /// Presentation timestamp in samples (frame index × 1024). - pub pts: i64, - /// Duration in samples (always one AAC frame = 1024). - pub duration: u32, -} - -/// AAC-LC encoder. Push PCM with [`push_pcm`](AacEncoder::push_pcm) (or -/// [`push_pcm_planar`](AacEncoder::push_pcm_planar)), call -/// [`finish`](AacEncoder::finish), then drain [`next_packet`](AacEncoder::next_packet) -/// until it returns [`Error::Eof`]. -pub struct AacEncoder { - sample_rate: u32, - channels: usize, - fs_index: u8, - /// Target bitrate (bits/s). Drives the per-frame rate loop. - bitrate: u32, - /// Arm A8 policy and its provisional threshold. - window_shape: WindowShape, - shape_tonality_pct: f32, - short_block_psy: bool, - tonality_smr: bool, - tns: bool, - relative_transients: bool, - pns: bool, - intensity: bool, - stereo_bit_split: bool, - win: Vec, - /// The KBD long window (α = 4.0), matching the decoder's. Built once. - win_kbd: Vec, - chans: Vec>, - initialized: bool, - /// Encoded raw access units (raw_data_block, no ADTS) awaiting `next_packet`, - /// each with its sample-domain PTS. Filled on `finish`. - queue: VecDeque<(Vec, i64)>, - flushed: bool, -} - -impl AacEncoder { - pub fn new(config: AacEncoderConfig) -> Self { - AacEncoder { - sample_rate: 0, - channels: 0, - fs_index: 0, - bitrate: config.bitrate_bps.max(1), - window_shape: config.window_shape, - shape_tonality_pct: config.shape_tonality_pct, - short_block_psy: config.short_block_psy, - tonality_smr: config.tonality_smr, - tns: config.tns, - relative_transients: config.relative_transients, - pns: config.pns, - intensity: config.intensity, - stereo_bit_split: config.stereo_bit_split, - win: Vec::new(), - win_kbd: Vec::new(), - chans: Vec::new(), - initialized: false, - queue: VecDeque::new(), - flushed: false, - } - } - - /// The stream's sample rate (0 until the first PCM is pushed). - pub fn sample_rate(&self) -> u32 { - self.sample_rate - } - - /// The stream's channel count (0 until the first PCM is pushed). - pub fn channels(&self) -> u16 { - self.channels as u16 - } - - /// Initialize (or validate) the stream parameters from a PCM push. - fn init(&mut self, channels: u16, sample_rate: u32) -> Result<()> { - if !self.initialized { - self.sample_rate = sample_rate; - self.channels = channels.max(1) as usize; - // Reject counts with no `channel_configuration`. Writing a config the - // element sequence does not match produces a stream that only our own - // decoder accepts — the bug this check exists to make impossible. - if element_plan(self.channels).is_none() { - return Err(Error::unsupported( - "aac encode: only 1-6 channels are supported (7+ needs a program_config_element, which is not implemented)", - )); - } - self.fs_index = crate::sf_index_for_rate(sample_rate) - .ok_or_else(|| Error::invalid("aac encode: unsupported sample rate"))?; - self.win = crate::dsp::sine_window(LONG_N); - // Arm A8's second shape. α = 4.0 for the long window matches the - // decoder's `kbd` exactly — a mismatched α is not a quality choice, - // it breaks TDAC and leaves audible seams at every overlap. - self.win_kbd = crate::dsp::kbd_window(LONG_N, 4.0); - self.chans = vec![Vec::new(); self.channels]; - self.initialized = true; - } else if channels.max(1) as usize != self.channels { - return Err(Error::invalid( - "aac encode: channel count changed mid-stream", - )); - } - Ok(()) - } - - /// Buffer interleaved `f32` PCM in [-1, 1] (`interleaved.len()` must be a - /// multiple of `channels`). The first push fixes the stream's channel count - /// and sample rate. - pub fn push_pcm(&mut self, interleaved: &[f32], channels: u16, sample_rate: u32) -> Result<()> { - self.init(channels, sample_rate)?; - let ch = self.channels; - let n = interleaved.len() / ch; - for i in 0..n { - for c in 0..ch { - self.chans[c].push(interleaved[i * ch + c]); - } - } - Ok(()) - } - - /// Buffer planar `f32` PCM, one slice per channel (`planes.len()` is the - /// channel count; all planes the same length). - pub fn push_pcm_planar(&mut self, planes: &[&[f32]], sample_rate: u32) -> Result<()> { - self.init(planes.len() as u16, sample_rate)?; - for (c, plane) in planes.iter().enumerate().take(self.channels) { - self.chans[c].extend_from_slice(plane); - } - Ok(()) - } - - /// Encode all buffered samples into per-frame raw access units (raw_data_block, - /// no ADTS) with sample-domain PTS. A trailing all-zero block flushes the MDCT - /// overlap so the final audio block decodes. Containers add their own framing - /// (ADTS header for `.aac`, `esds` + raw samples for MP4). - /// One block's samples for channel `ch` (zero-padded past the buffered input). - fn block(&self, ch: usize, b: usize) -> [f32; FRAME_LEN] { - let mut cur = [0f32; FRAME_LEN]; - for (i, s) in cur.iter_mut().enumerate() { - *s = self.chans[ch] - .get(b * FRAME_LEN + i) - .copied() - .unwrap_or(0.0); - } - cur - } - - /// Encode one frame `b` to its raw access unit + PTS. A pure function of the - /// buffered input, the window sequences, and `b` — the previous block (for MDCT - /// overlap) is just block `b-1`'s samples — so frames encode **independently**. - #[allow(clippy::too_many_arguments)] - #[allow(clippy::too_many_arguments)] - fn encode_frame( - &self, - b: usize, - swb: &[u16], - swb_s: &[u16], - sine_s: &[f32], - kbd_s: &[f32], - seqs: &[Vec], - shapes: &[bool], - per_channel: usize, - plan: &[Elem], - ) -> (Vec, i64) { - let prev = |ch: usize| -> [f32; FRAME_LEN] { - if b == 0 { - [0f32; FRAME_LEN] - } else { - self.block(ch, b - 1) - } - }; - // Arm A8. The shape of frame b-1 owns this frame's LEFT overlap half, so - // both are needed; the decoder seeds prev = sine at stream start. - let cur_kbd = shapes.get(b).copied().unwrap_or(false); - let prev_kbd = if b == 0 { - false - } else { - shapes.get(b - 1).copied().unwrap_or(false) - }; - let short_win: &[f32] = if cur_kbd { kbd_s } else { sine_s }; - let psy = PsyCfg { - short_block_psy: self.short_block_psy, - tonality_smr: self.tonality_smr, - tns: self.tns, - pns: self.pns, - intensity: self.intensity, - stereo_bit_split: self.stereo_bit_split, - }; - - let mut rdb = BitWriter::new(); - // One pass over the ISO element sequence. `seqs` is indexed by ELEMENT, - // not by channel: a CPE shares one window sequence across its pair, so - // the two channels' transient flags were joined when the plan was built. - for (ei, elem) in plan.iter().enumerate() { - let seq = seqs[ei][b]; - let tag = ei as u32; - match *elem { - Elem::Cpe(l, r) => { - let (p0, c0, p1, c1) = (prev(l), self.block(l, b), prev(r), self.block(r, b)); - if seq == WindowSequence::EightShort { - let sl = analyze_short(&p0, &c0, short_win); - let sr_ = analyze_short(&p1, &c1, short_win); - encode_cpe( - &mut rdb, tag, &sl, &sr_, swb_s, seq, self.sample_rate, per_channel, - cur_kbd, psy, - ); - } else { - let win = long_window( - seq, prev_kbd, cur_kbd, &self.win, &self.win_kbd, sine_s, kbd_s, - ); - let sl = analyze_long(&p0, &c0, &win); - let sr_ = analyze_long(&p1, &c1, &win); - encode_cpe( - &mut rdb, tag, &sl, &sr_, swb, seq, self.sample_rate, per_channel, - cur_kbd, psy, - ); - } - } - Elem::Sce(ch) | Elem::Lfe(ch) => { - let (p, c) = (prev(ch), self.block(ch, b)); - let id = elem.id(); - if seq == WindowSequence::EightShort { - let spec = analyze_short(&p, &c, short_win); - encode_channel_element_short( - &mut rdb, - tag, - &spec, - swb_s, - per_channel, - cur_kbd, - self.sample_rate, - psy, - ); - } else { - let win = long_window( - seq, prev_kbd, cur_kbd, &self.win, &self.win_kbd, sine_s, kbd_s, - ); - let spec = analyze_long(&p, &c, &win); - encode_channel_element( - &mut rdb, - tag, - &spec, - swb, - seq, - self.sample_rate, - per_channel, - cur_kbd, - psy, - id, - ); - } - } - } - } - rdb.write(ID_END, 3); - (rdb.into_bytes(), (b * FRAME_LEN) as i64) - } - - /// Transient flags for one channel, under the configured detector (arm A9). - fn transients(&self, chan: &[f32], nframes: usize) -> Vec { - if self.relative_transients { - detect_transients_relative(chan, nframes) - } else { - detect_transients(chan, nframes) - } - } - - /// **The Rung 0 gate.** Decide each frame's window shape. - /// - /// Computed as a whole-stream pre-pass, exactly like `detect_transients`, for - /// two reasons: the decision is shared by both channels of a CPE (one common - /// window), and frame b's window depends on frame b−1's shape — so deciding - /// inside the frame-parallel worker would make the output depend on thread - /// scheduling. Deciding up front keeps `encode_frame` independent and the - /// encoder byte-deterministic (asserted by the lab's null arm). - /// - /// Threshold form: **per-clip percentile** of frame tonality (law 1), not an - /// absolute. `Auto` is PROVISIONAL and off by default (law 7). - fn decide_shapes(&self, nblocks: usize) -> Vec { - match self.window_shape { - WindowShape::Sine => vec![false; nblocks], - WindowShape::Kbd => vec![true; nblocks], - WindowShape::Auto => { - // One reading per frame, from channel 0 (a CPE shares one window, - // so the decision cannot be per-channel). - let ton: Vec = (0..nblocks) - .map(|b| time_tonality(&self.block(0, b))) - .collect(); - let atk = frame_attack_ratios(&self.chans[0], nblocks); - - let pct = |v: &[f32], q: f32| -> f32 { - let mut s = v.to_vec(); - s.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); - let i = ((s.len().saturating_sub(1)) as f32 * q.clamp(0.0, 1.0)).round() as usize; - s.get(i).copied().unwrap_or(f32::INFINITY) - }; - let ton_thresh = pct(&ton, self.shape_tonality_pct); - let atk_thresh = pct(&atk, SHAPE_ATTACK_VETO_PCT); - - // A depth-2 transcribed tree (great-gate law 3: shallow, in plain - // code, one documented feature per node). - // - // attack — a frame with a strong onset takes SINE, whatever its - // tonality. KBD's wider main lobe smears transients in - // time; the force-on ladder measured +18.6% audible on - // the percussive class, the largest single effect in - // the whole Rung 0 harvest. - // tonality— among the remaining (stationary) frames, KBD's much - // deeper stopband is worth having. - // - // The veto is why this gate is not simply "tonality > t": ringing - // percussion reads as HIGHLY tonal (a struck resonator is a decaying - // sinusoid), so a tonality-only rule routes exactly the frames that - // KBD hurts most. The first fit did precisely that. - // The veto spans a ±1-frame NEIGHBOURHOOD, not just the frame - // itself. Overlap-add means frame b's window shapes the overlap - // with both b−1 and b+1, so an onset in either neighbour is - // analyzed partly through this frame's window. Vetoing only the - // onset frame left the ring-down frame on KBD and kept the whole - // percussive regression (+10.0% audible, barely half of force-on's - // +18.6%) — the measurement that forced this widening. - let vetoed: Vec = (0..nblocks) - .map(|b| { - let lo = b.saturating_sub(1); - let hi = (b + 1).min(nblocks.saturating_sub(1)); - (lo..=hi).any(|k| atk.get(k).copied().unwrap_or(1.0) > atk_thresh) - }) - .collect(); - - (0..nblocks) - .map(|b| !vetoed[b] && ton[b] > ton_thresh) - .collect() - } - } - } - - /// Encode all buffered frames to raw access units. Frames are independent, so - /// they fan out across worker threads (ffmpeg's AAC encoder is single-threaded). - fn encode_stream(&self) -> Vec<(Vec, i64)> { - let swb = swb_offsets(true, self.fs_index); - let swb_s = swb_offsets(false, self.fs_index); - let sine_s = crate::dsp::sine_window(SHORT_N); - // α = 6.0 for the short window, matching the decoder's `kbd_s`. - let kbd_s = crate::dsp::kbd_window(SHORT_N, 6.0); - let n = self.chans.first().map_or(0, |c| c.len()); - let nblocks = n.div_ceil(FRAME_LEN) + 1; - // Per-channel ICS-body budget from the target bitrate (minus framing). - let frame_budget = (self.bitrate as usize * FRAME_LEN / self.sample_rate.max(1) as usize) - .saturating_sub(59); // ADTS header (56) + END (3) - let per_channel = (frame_budget / self.channels.max(1)).saturating_sub(7); // element overhead - - // The ISO element sequence for this channel count (validated at init, so - // the unwrap cannot fire here). - let plan = element_plan(self.channels).expect("channel count validated in init"); - - // Window sequences, **one per element**. A CPE shares a common window, so - // its two channels' transient flags are joined; an LFE is long-only by - // ISO rule, not by choice. - let seqs: Vec> = plan - .iter() - .map(|e| match *e { - Elem::Cpe(l, r) => { - let t0 = self.transients(&self.chans[l], nblocks); - let t1 = self.transients(&self.chans[r], nblocks); - let joint: Vec = (0..nblocks).map(|b| t0[b] || t1[b]).collect(); - assign_sequences(&joint) - } - Elem::Sce(ch) => assign_sequences(&self.transients(&self.chans[ch], nblocks)), - // lfe_channel_element carries no window-shape freedom. - Elem::Lfe(_) => vec![WindowSequence::OnlyLong; nblocks], - }) - .collect(); - // Arm A8: decide every frame's window shape up front, for the same reason - // the sequences are decided up front — frame b's window depends on frame - // b−1's shape, so this cannot live inside the parallel worker. - let shapes = self.decide_shapes(nblocks); - - // Slice views the worker threads share (all read-only). - let (swb, swb_s, sine_s, kbd_s, seqs, shapes, plan) = ( - &swb[..], - &swb_s[..], - &sine_s[..], - &kbd_s[..], - &seqs[..], - &shapes[..], - &plan[..], - ); - let frame = |b: usize| { - self.encode_frame(b, swb, swb_s, sine_s, kbd_s, seqs, shapes, per_channel, plan) - }; - - let nthreads = std::thread::available_parallelism() - .map_or(1, |p| p.get()) - .min(nblocks.max(1)); - if nthreads <= 1 || nblocks < 16 { - return (0..nblocks).map(frame).collect(); // serial for tiny inputs - } - // Fan out contiguous frame ranges; concatenating the parts keeps them ordered. - let chunk = nblocks.div_ceil(nthreads); - let parts: Vec, i64)>> = std::thread::scope(|s| { - (0..nthreads) - .map(|t| { - s.spawn(move || { - let end = ((t + 1) * chunk).min(nblocks); - (t * chunk..end).map(frame).collect::>() - }) - }) - .collect::>() - .into_iter() - .map(|h| h.join().unwrap()) - .collect() - }); - parts.into_iter().flatten().collect() - } - - /// Signal end-of-input: encode all buffered PCM (frame-parallel) so packets - /// can be drained via [`next_packet`](AacEncoder::next_packet). Idempotent. - pub fn finish(&mut self) { - if self.flushed { - return; - } - self.flushed = true; - if self.initialized { - self.queue = self.encode_stream().into(); - } - } - - /// Retrieve the next encoded access unit. Returns [`Error::Again`] before - /// [`finish`](AacEncoder::finish) has been called, and [`Error::Eof`] once - /// fully drained. - pub fn next_packet(&mut self) -> Result { - if let Some((data, pts)) = self.queue.pop_front() { - return Ok(EncodedPacket { - data, - pts, - duration: FRAME_LEN as u32, - }); - } - if self.flushed { - Err(Error::Eof) - } else { - Err(Error::Again) - } - } -} - -impl Default for AacEncoder { - fn default() -> Self { - Self::new(AacEncoderConfig::default()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::bits::BitReader; - use crate::codebook::decode_tuple; - - /// Drain the encoder into a concatenated ADTS elementary stream — the container - /// framing the encoder no longer emits itself — for decoder/ffmpeg validation. - fn encode_to_adts(enc: &mut AacEncoder) -> Vec { - enc.finish(); - let mut out = Vec::new(); - while let Ok(p) = enc.next_packet() { - let hdr = AdtsHeader { - object_type: 2, - sample_rate: enc.sample_rate, - channels: enc.channels as u16, - frame_length: 7 + p.data.len(), - header_len: 7, - }; - out.extend_from_slice(&write_adts_header(&hdr)); - out.extend_from_slice(&p.data); - } - out - } - - /// Every `dim`-tuple drawn from `vals`. - fn product(vals: &[i32], dim: usize) -> Vec> { - let mut out = vec![vec![]]; - for _ in 0..dim { - let mut next = Vec::new(); - for prefix in &out { - for &v in vals { - let mut t = prefix.clone(); - t.push(v); - next.push(t); - } - } - out = next; - } - out - } - - /// Encode every representable tuple of every spectral codebook, then decode it - /// back through the REAL decoder — must match exactly (codeword + sign + escape), - /// and the written bit count must equal `spectral_bits`. - #[test] - fn spectral_encode_roundtrips_through_decoder() { - for cb_num in 1..=11usize { - let cb = &CODEBOOKS[cb_num]; - let dim = cb.dim as usize; - let lav = cb.lav as i32; - - // Signed books offset by lav; unsigned carry a sign, so cover ±lav. - // Book 11 (escape) also probes magnitudes beyond lav, both signs. - let vals: Vec = if cb.esc { - let mut v: Vec = (-lav..=lav).collect(); - for &m in &[16, 17, 31, 32, 69, 100] { - v.push(m); - v.push(-m); - } - v - } else { - (-lav..=lav).collect() - }; - - for tuple in product(&vals, dim) { - if tuple_index(cb, &tuple).is_none() { - continue; - } - let mut w = BitWriter::new(); - spectral_emit(cb_num, &tuple, &mut w); - assert_eq!( - w.bit_len(), - spectral_bits(cb_num, &tuple).unwrap(), - "cb {cb_num} tuple {tuple:?}: bit count mismatch" - ); - let bytes = w.into_bytes(); - let mut r = BitReader::new(&bytes); - let mut out = [0i32; 4]; - decode_tuple(cb, spectral_book(cb_num as u8), &mut r, &mut out).unwrap(); - assert_eq!( - &out[..dim], - &tuple[..dim], - "cb {cb_num} tuple {tuple:?}: round-trip" - ); - } - } - } - - /// Forward MDCT → decoder synthesis (imdct·window·overlap-add) reconstructs the - /// signal (delayed one frame) — proves the window + overlap + 32768 scaling. - #[test] - fn long_filterbank_reconstructs_via_decoder_math() { - let win = crate::dsp::sine_window(LONG_N); - let nblocks = 6usize; - let signal: Vec = (0..nblocks * FRAME_LEN) - .map(|i| (0.3 * (i as f64 * 0.017).sin() + 0.2 * (i as f64 * 0.003).cos()) as f32) - .collect(); - - let mut prev = [0f32; FRAME_LEN]; - let mut specs = Vec::new(); - for b in 0..nblocks { - let mut cur = [0f32; FRAME_LEN]; - cur.copy_from_slice(&signal[b * FRAME_LEN..(b + 1) * FRAME_LEN]); - specs.push(analyze_long(&prev, &cur, &win)); - prev = cur; - } - - let mut overlap = [0f32; FRAME_LEN]; - let mut out = Vec::new(); - for spec in &specs { - let time = crate::dsp::imdct(spec); - let frame: Vec = (0..LONG_N).map(|n| time[n] * win[n] / SPEC_SCALE).collect(); - let mut o = [0f32; FRAME_LEN]; - for n in 0..FRAME_LEN { - o[n] = frame[n] + overlap[n]; - overlap[n] = frame[FRAME_LEN + n]; - } - out.extend_from_slice(&o); - } - - // Output lags the input by one frame; the interior must reconstruct. - for i in FRAME_LEN..(nblocks - 1) * FRAME_LEN { - assert!( - (out[i] - signal[i - FRAME_LEN]).abs() < 1e-3, - "at {i}: {} vs {}", - out[i], - signal[i - FRAME_LEN] - ); - } - } - - /// The block-switching sequence OnlyLong → LongStart → EightShort → LongStop → - /// OnlyLong must reconstruct through the decoder's synthesis math (TDAC across - /// the transition windows) — the decisive check that the short filterbank and - /// transition windows are exact inverses. - #[test] - fn short_block_sequence_reconstructs_via_decoder_math() { - use WindowSequence::*; - let sine_l = crate::dsp::sine_window(LONG_N); - let sine_s = crate::dsp::sine_window(SHORT_N); - // Arm A8's shapes, unused by this test (it exercises the sine arm) but - // required by the shape-aware signature. - let kbd_l_t = crate::dsp::kbd_window(LONG_N, 4.0); - let kbd_s_t = crate::dsp::kbd_window(SHORT_N, 6.0); - let seqs = [ - OnlyLong, LongStart, EightShort, LongStop, OnlyLong, OnlyLong, - ]; - let nblocks = seqs.len(); - let signal: Vec = (0..nblocks * FRAME_LEN) - .map(|i| (0.3 * (i as f64 * 0.019).sin() + 0.25 * (i as f64 * 0.007).cos()) as f32) - .collect(); - - // Forward: per-frame filterbank chosen by the window sequence. - let mut prev = [0f32; FRAME_LEN]; - let mut specs = Vec::new(); - for (b, &seq) in seqs.iter().enumerate() { - let mut cur = [0f32; FRAME_LEN]; - cur.copy_from_slice(&signal[b * FRAME_LEN..(b + 1) * FRAME_LEN]); - let spec = if seq == EightShort { - analyze_short(&prev, &cur, &sine_s) - } else { - analyze_long(&prev, &cur, &long_window(seq, false, false, &sine_l, &kbd_l_t, &sine_s, &kbd_s_t)) - }; - specs.push((seq, spec)); - prev = cur; - } - - // Synthesis: mirror the decoder (short_frame vs imdct·window) + overlap-add. - let mut overlap = [0f32; FRAME_LEN]; - let mut out = Vec::new(); - for (seq, spec) in &specs { - let frame: Vec = if *seq == EightShort { - let mut f = vec![0f32; LONG_N]; - for w in 0..8 { - let time = crate::dsp::imdct(&spec[w * SHORT_HALF..(w + 1) * SHORT_HALF]); - let off = 448 + w * SHORT_HALF; - for n in 0..SHORT_N { - f[off + n] += time[n] * sine_s[n] / SPEC_SCALE; - } - } - f - } else { - let time = crate::dsp::imdct(spec); - let win = long_window(*seq, false, false, &sine_l, &kbd_l_t, &sine_s, &kbd_s_t); - (0..LONG_N).map(|n| time[n] * win[n] / SPEC_SCALE).collect() - }; - let mut o = [0f32; FRAME_LEN]; - for n in 0..FRAME_LEN { - o[n] = frame[n] + overlap[n]; - overlap[n] = frame[FRAME_LEN + n]; - } - out.extend_from_slice(&o); - } - - // Interior (past the priming frame) must reconstruct across all transitions. - for i in FRAME_LEN..(nblocks - 1) * FRAME_LEN { - assert!( - (out[i] - signal[i - FRAME_LEN]).abs() < 1e-3, - "at {i}: {} vs {}", - out[i], - signal[i - FRAME_LEN] - ); - } - } - - #[test] - fn window_sequences_are_valid() { - use WindowSequence::*; - // Isolated transient → bracketed by LongStart / LongStop. - assert_eq!( - assign_sequences(&[false, false, false, true, false, false]), - vec![OnlyLong, OnlyLong, LongStart, EightShort, LongStop, OnlyLong] - ); - // Adjacent transients → one short run. - assert_eq!( - assign_sequences(&[false, false, true, true, false]), - vec![OnlyLong, LongStart, EightShort, EightShort, LongStop] - ); - // A single-frame gap is merged (can't be both a stop and a start). - assert_eq!( - assign_sequences(&[false, true, false, true, false]), - vec![LongStart, EightShort, EightShort, EightShort, LongStop] - ); - } - - #[test] - fn transient_is_detected() { - let sr = 44100.0f64; - let nframes = 5; - let n = nframes * FRAME_LEN; - let mut s = vec![0f32; n]; - for (i, x) in s.iter_mut().enumerate() { - *x = (0.02 * (2.0 * std::f64::consts::PI * 400.0 * i as f64 / sr).sin()) as f32; - } - // A loud burst at the start of frame 2. - for i in 0..600 { - let env = (1.0 - i as f64 / 600.0).max(0.0); - s[2 * FRAME_LEN + i] += - (0.8 * env * (2.0 * std::f64::consts::PI * 3000.0 * i as f64 / sr).sin()) as f32; - } - let flags = detect_transients(&s, nframes); - assert!(flags[2], "the burst frame must be flagged"); - assert!(!flags[0] && !flags[4], "steady frames must not be flagged"); - } - - /// End-to-end: a signal with a sharp attack must actually emit EightShort - /// blocks and still decode cleanly through our decoder. - #[test] - fn transient_encodes_short_and_decodes() { - let sr = 44100u32; - let nframes = 5; - let n = nframes * FRAME_LEN; - let mut interleaved = Vec::new(); - for i in 0..n { - let t = i as f64 / sr as f64; - let mut v = 0.02 * (2.0 * std::f64::consts::PI * 400.0 * t).sin(); - if (2 * FRAME_LEN..2 * FRAME_LEN + 600).contains(&i) { - let k = i - 2 * FRAME_LEN; - let env = (1.0 - k as f64 / 600.0).max(0.0); - v += 0.8 * env * (2.0 * std::f64::consts::PI * 3000.0 * k as f64 / sr as f64).sin(); - } - interleaved.push(v as f32); - } - - let mut enc = AacEncoder::default(); - enc.push_pcm(&interleaved, 1, sr).unwrap(); - let adts = encode_to_adts(&mut enc); - - // Parse each frame's first SCE window_sequence; EightShort (2) must appear. - let mut saw_short = false; - let mut pos = 0usize; - let mut decoded = 0usize; - let mut dec = crate::decode::Decoder::new(sr); - while pos + 7 <= adts.len() { - let hdr = crate::parse_adts(&adts[pos..]).unwrap(); - let au = &adts[pos + hdr.header_len..pos + hdr.frame_length]; - let mut r = crate::BitReader::new(au); - assert_eq!(r.read_bits(3).unwrap(), ID_SCE); // mono SCE - let _ = r.read_bits(4).unwrap(); // tag - let _ = r.read_bits(8).unwrap(); // global_gain - let _ = r.read_bit().unwrap(); // ics_reserved - if r.read_bits(2).unwrap() == WindowSequence::EightShort.to_bits() { - saw_short = true; - } - decoded += dec.decode(au, None).unwrap().frames(); - pos += hdr.frame_length; - } - assert!(saw_short, "a transient must produce EightShort blocks"); - assert!(decoded >= n, "decoded fewer samples than encoded"); - } - - /// The `ms_mask_present` (2 bits) of the first frame's CPE — 0 = no M/S. - fn first_cpe_ms_mask(adts: &[u8]) -> u32 { - let hdr = crate::parse_adts(adts).unwrap(); - let au = &adts[hdr.header_len..hdr.frame_length]; - let mut r = crate::BitReader::new(au); - assert_eq!(r.read_bits(3).unwrap(), ID_CPE); - let _tag = r.read_bits(4).unwrap(); - assert_eq!(r.read_bit().unwrap(), 1); // common_window - let _reserved = r.read_bit().unwrap(); - let ws = r.read_bits(2).unwrap(); - let _shape = r.read_bit().unwrap(); - if ws == WindowSequence::EightShort.to_bits() { - let _ = r.read_bits(4).unwrap(); // max_sfb - let _ = r.read_bits(7).unwrap(); // grouping - } else { - let _ = r.read_bits(6).unwrap(); // max_sfb - let _ = r.read_bit().unwrap(); // predictor_data_present - } - r.read_bits(2).unwrap() - } - - /// Stereo with L = R (fully correlated) must pick M/S and reconstruct the two - /// channels identically — the CPE + mid/side round-trip. - #[test] - fn stereo_ms_roundtrips_mono_content() { - let sr = 44100u32; - let n = 8192usize; - let mut interleaved = Vec::new(); - for i in 0..n { - let s = - (0.4 * (2.0 * std::f64::consts::PI * 600.0 * i as f64 / sr as f64).sin()) as f32; - interleaved.push(s); // L - interleaved.push(s); // R == L - } - let mut enc = AacEncoder::default(); - enc.push_pcm(&interleaved, 2, sr).unwrap(); - let adts = encode_to_adts(&mut enc); - - assert_ne!( - first_cpe_ms_mask(&adts), - 0, - "M/S should be chosen for L=R content" - ); - - let mut dec = crate::decode::Decoder::new(sr); - let (mut lsum, mut diff) = (0f64, 0f64); - let mut pos = 0usize; - while pos + 7 <= adts.len() { - let hdr = crate::parse_adts(&adts[pos..]).unwrap(); - let au = &adts[pos + hdr.header_len..pos + hdr.frame_length]; - let a = dec.decode(au, None).unwrap(); - for k in 0..a.frames() { - let l = a.samples[k * 2]; - let rr = a.samples[k * 2 + 1]; - lsum += (l as f64).powi(2); - diff += ((l - rr) as f64).powi(2); - } - pos += hdr.frame_length; - } - assert!(lsum > 0.0, "decoded silence"); - // L and R reconstruct identically (mono content preserved through M/S). - assert!( - diff / (lsum + 1e-9) < 1e-3, - "L/R diverged: {}", - diff / (lsum + 1e-9) - ); - } - - /// The encoder→decoder round-trip is unity gain and length-preserving: decode - /// the raw AUs directly (no container/engine) and check per-channel amplitude - /// (≈0.283 RMS for a 0.4-amp sine) and frame count (~input + a little priming). - #[test] - fn stereo_direct_decode_amplitude() { - let sr = 44100u32; - let n = sr as usize; // 1 s - let mut interleaved = Vec::new(); - for i in 0..n { - let t = i as f64 / sr as f64; - let l = (0.4 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()) as f32; - let r = (0.4 * (2.0 * std::f64::consts::PI * 660.0 * t).sin()) as f32; - interleaved.push(l); - interleaved.push(r); - } - let mut enc = AacEncoder::default(); - enc.push_pcm(&interleaved, 2, sr).unwrap(); - enc.finish(); - let mut dec = crate::decode::Decoder::new(sr); - let (mut lsq, mut rsq, mut cnt) = (0.0f64, 0.0f64, 0usize); - while let Ok(p) = enc.next_packet() { - let a = dec.decode(&p.data, None).unwrap(); - for k in 0..a.frames() { - let l = a.samples[k * 2]; - let r = a.samples[k * 2 + 1]; - lsq += (l as f64).powi(2); - rsq += (r as f64).powi(2); - cnt += 1; - } - } - let (lrms, rrms) = ((lsq / cnt as f64).sqrt(), (rsq / cnt as f64).sqrt()); - eprintln!("input {n}/ch; decoded {cnt}/ch; Lrms={lrms:.3} Rrms={rrms:.3} (unity≈0.283)"); - // ~1 output frame per input frame (a couple of priming/flush frames extra). - assert!( - cnt >= n && cnt < n + 4 * FRAME_LEN, - "frame count off: {cnt} vs {n}" - ); - // Unity gain per channel (lossy tolerance), no doubling. - assert!((0.24..0.32).contains(&lrms), "L amplitude off: {lrms:.3}"); - assert!((0.24..0.32).contains(&rrms), "R amplitude off: {rrms:.3}"); - } - - /// Per-frame hot-path breakdown — which stage dominates encode time. - #[test] - #[ignore = "profiling; run with --ignored --nocapture"] - fn profile_encode_hotpath() { - use std::time::Instant; - let sr = 44100u32; - let fs = crate::sf_index_for_rate(sr).unwrap(); - let swb = swb_offsets(true, fs); - let win = crate::dsp::sine_window(LONG_N); - let mut cur = [0f32; FRAME_LEN]; - for (i, s) in cur.iter_mut().enumerate() { - let t = i as f64 / sr as f64; - *s = (0.3 * (2.0 * std::f64::consts::PI * 440.0 * t).sin() - + 0.1 * (2.0 * std::f64::consts::PI * 3000.0 * t).sin()) as f32; - } - let prev = [0f32; FRAME_LEN]; - let iters = 500; - let us = |d: std::time::Duration| d.as_secs_f64() * 1e6 / iters as f64; - - let t = Instant::now(); - let mut spec = Vec::new(); - for _ in 0..iters { - spec = analyze_long(&prev, &cur, &win); - } - let mdct = t.elapsed(); - - let t = Instant::now(); - for _ in 0..iters { - let _ = perceptual_offsets(&spec, swb, sr, false); - } - let psy = t.elapsed(); - let offsets = perceptual_offsets(&spec, swb, sr, false); - - let t = Instant::now(); - for _ in 0..iters { - let _ = Xpow::new(&spec); - } - let xpow_t = t.elapsed(); - let xp = Xpow::new(&spec); - - let t = Instant::now(); - for _ in 0..iters { - let _ = rate_loop(&xp, swb, &offsets, 3000); - } - let rate = t.elapsed(); - - let sf = scalefactors(&offsets, 120); - let t = Instant::now(); - for _ in 0..iters { - let _ = code_frame(&xp, swb, &sf); - } - let cf = t.elapsed(); - - eprintln!("per-frame per-channel (avg over {iters}):"); - eprintln!(" analyze_long (MDCT): {:>8.1} us", us(mdct)); - eprintln!(" Xpow::new (once): {:>8.1} us", us(xpow_t)); - eprintln!(" perceptual_offsets: {:>8.1} us", us(psy)); - eprintln!(" rate_loop (~8x cf): {:>8.1} us", us(rate)); - eprintln!(" one code_frame: {:>8.1} us", us(cf)); - eprintln!( - " → MDCT is {:.0}% of (MDCT + rate_loop)", - 100.0 * mdct.as_secs_f64() / (mdct.as_secs_f64() + rate.as_secs_f64()) - ); - } - - /// The AVX-512 quantize kernel narrows via `trunc(min(v+0.5, MAX+0.5))` instead of - /// the AVX2/scalar `min(round(v), MAX)`. The intrinsics can't run on a non-AVX-512 - /// host, but the identity they rely on — for the quantizer's always-nonnegative - /// input — is checkable in scalar, so the untested path's *math* is pinned here. - #[test] - fn avx512_trunc_identity_matches_round_clamp() { - for &v in &[ - 0.0f64, 0.4, 0.5, 0.6, 1.4, 1.5, 2.5, 100.5, 8190.9, 8191.0, 8191.5, 1e6, - ] { - let round_clamp = (v.round() as i64).min(MAX_QUANT as i64); - let trunc_trick = (v + 0.5).min(MAX_QUANT as f64 + 0.5) as i64; // `as` truncates - assert_eq!(round_clamp, trunc_trick, "mismatch at v={v}"); - } - } - - #[test] - fn bitwriter_msb_first() { - let mut w = BitWriter::new(); - w.write(0b101, 3); - w.write(0b1, 1); - w.write(0b1111, 4); - assert_eq!(w.bit_len(), 8); - assert_eq!(w.into_bytes(), vec![0b1011_1111]); - } - - #[test] - fn audio_specific_config_roundtrips() { - for &(sr, ch) in &[(44100u32, 2u16), (48000, 1), (96000, 2), (8000, 1)] { - let cfg = AudioSpecificConfig { - object_type: 2, - sample_rate: sr, - channels: ch, - }; - let bytes = write_audio_specific_config(&cfg); - assert_eq!(crate::parse_audio_specific_config(&bytes).unwrap(), cfg); - } - } - - #[test] - fn adts_header_roundtrips() { - let hdr = AdtsHeader { - object_type: 2, - sample_rate: 44100, - channels: 2, - frame_length: 512, - header_len: 7, - }; - let bytes = write_adts_header(&hdr); - assert_eq!(bytes.len(), 7); - assert!(crate::is_adts(&bytes)); - assert_eq!(crate::parse_adts(&bytes).unwrap(), hdr); - } - - #[test] - fn ics_info_long_reencodes_bit_exact() { - // The decoder's own long-block test vector. - let orig = [0x0C, 0x40]; - let info = crate::ics::parse_ics_info(&mut BitReader::new(&orig), 4).unwrap(); - let mut w = BitWriter::new(); - encode_ics_info(&mut w, &info); - assert_eq!(w.into_bytes(), orig); - } - - #[test] - fn ics_info_short_grouping_roundtrips() { - use crate::ics::{parse_ics_info, IcsInfo, WindowSequence}; - let info = IcsInfo { - window_sequence: WindowSequence::EightShort, - window_shape_kbd: false, - max_sfb: 8, - num_windows: 8, - num_window_groups: 2, - window_group_length: vec![3, 5], - num_swb: 0, // encode ignores; the parser re-derives - }; - let mut w = BitWriter::new(); - encode_ics_info(&mut w, &info); - let parsed = parse_ics_info(&mut BitReader::new(&w.into_bytes()), 4).unwrap(); - assert_eq!(parsed.window_sequence, WindowSequence::EightShort); - assert_eq!(parsed.max_sfb, 8); - assert_eq!(parsed.window_group_length, vec![3, 5]); - } - - fn rms(sig: &[f32]) -> f64 { - (sig.iter().map(|&s| (s as f64).powi(2)).sum::() / sig.len().max(1) as f64).sqrt() - } - - /// Magnitude of the `freq`-Hz component (Goertzel-style) — a recognizability probe. - fn tone_energy(sig: &[f32], freq: f64, sr: f64) -> f64 { - let (mut re, mut im) = (0.0f64, 0.0f64); - for (i, &s) in sig.iter().enumerate() { - let ph = 2.0 * std::f64::consts::PI * freq * i as f64 / sr; - re += s as f64 * ph.cos(); - im += s as f64 * ph.sin(); - } - (re * re + im * im).sqrt() / sig.len() as f64 - } - - /// The whole-pipeline gate: encode a 440 Hz tone, decode through the real - /// decoder, and confirm a recognizable 440 Hz tone with preserved energy. - #[test] - fn encodes_and_decodes_recognizable_tone() { - let sr = 44100u32; - let n = 44100usize; // 1 s - let mut samples = Vec::with_capacity(n); - for i in 0..n { - let s = - ((i as f64 * 2.0 * std::f64::consts::PI * 440.0 / sr as f64).sin() * 0.5) as f32; - samples.push(s); - } - - let mut enc = AacEncoder::default(); - enc.push_pcm(&samples, 1, sr).unwrap(); - let adts = encode_to_adts(&mut enc); - assert!(crate::is_adts(&adts), "encoder output is not ADTS"); - - let mut dec = crate::decode::Decoder::new(sr); - let mut decoded = Vec::new(); - let mut pos = 0usize; - while pos + 7 <= adts.len() { - let hdr = crate::parse_adts(&adts[pos..]).unwrap(); - let au = &adts[pos + hdr.header_len..pos + hdr.frame_length]; - decoded.extend_from_slice(&dec.decode(au, None).unwrap().samples); - pos += hdr.frame_length; - } - assert!( - decoded.len() > n / 2, - "too little decoded audio: {}", - decoded.len() - ); - - let (ri, ro) = (rms(&samples), rms(&decoded)); - assert!( - ro > 0.4 * ri && ro < 2.5 * ri, - "energy off: in {ri:.4} out {ro:.4}" - ); - let e440 = tone_energy(&decoded, 440.0, sr as f64); - let e1234 = tone_energy(&decoded, 1234.0, sr as f64); - assert!( - e440 > 5.0 * e1234, - "not a clean 440 Hz tone: e440 {e440:.5} e1234 {e1234:.5}" - ); - } - - /// The rate loop must keep a dense signal within (roughly) the target bitrate - /// and still produce decodable audio. - #[test] - fn rate_loop_respects_bitrate() { - let sr = 44100u32; - let secs = 2usize; - let n = sr as usize * secs; - let mut interleaved = Vec::new(); - let mut st = 0x0000_2468u32; - for i in 0..n { - let t = i as f64 / sr as f64; - let mut s = 0.0; - for h in 1..=8 { - s += (2.0 * std::f64::consts::PI * 300.0 * h as f64 * t).sin() / h as f64; - } - st ^= st << 13; - st ^= st >> 17; - st ^= st << 5; - let noise = ((st >> 24) as f64 - 128.0) / 128.0 * 0.1; - let v = ((s * 0.2 + noise) * 0.7).clamp(-1.0, 1.0) as f32; - interleaved.push(v); - } - - for &kbps in &[64_000u32, 128_000] { - let mut enc = AacEncoder::new(AacEncoderConfig { bitrate_bps: kbps, ..Default::default() }); - enc.push_pcm(&interleaved, 1, sr).unwrap(); - let adts = encode_to_adts(&mut enc); - - let measured = adts.len() as f64 * 8.0 / secs as f64; - assert!( - measured <= kbps as f64 * 1.35, - "bitrate {kbps}: measured {measured:.0} b/s exceeds budget" - ); - - let mut dec = crate::decode::Decoder::new(sr); - let mut pos = 0usize; - let mut got = false; - while pos + 7 <= adts.len() { - let hdr = crate::parse_adts(&adts[pos..]).unwrap(); - let au = &adts[pos + hdr.header_len..pos + hdr.frame_length]; - got |= !dec.decode(au, None).unwrap().samples.is_empty(); - pos += hdr.frame_length; - } - assert!(got, "bitrate {kbps}: no decodable audio"); - eprintln!( - "target {kbps} b/s → measured {measured:.0} b/s ({} bytes)", - adts.len() - ); - } - } - - /// The psychoacoustic model must shape quantization noise toward the masking - /// threshold: at a fixed budget it must not worsen the worst band and must cut - /// the total audible (above-mask) noise vs flat scalefactors. - #[test] - fn psy_model_shapes_noise_below_flat() { - let sr = 44100u32; - let fs = crate::sf_index_for_rate(sr).unwrap(); - let swb = swb_offsets(true, fs); - let win = crate::dsp::sine_window(LONG_N); - // A few strong tones with spectral gaps → masking creates real headroom in - // some bands and sensitivity in others. - let mut cur = [0f32; FRAME_LEN]; - for (i, s) in cur.iter_mut().enumerate() { - let t = i as f64 / sr as f64; - let v = 0.5 * (2.0 * std::f64::consts::PI * 500.0 * t).sin() - + 0.25 * (2.0 * std::f64::consts::PI * 1500.0 * t).sin() - + 0.15 * (2.0 * std::f64::consts::PI * 4000.0 * t).sin(); - *s = v as f32; - } - let spec = analyze_long(&[0f32; FRAME_LEN], &cur, &win); - let target = 2500usize; // ~128 kbps — enough that allocation choices matter - - // Worst-case NMR (perceptual quality is set by the loudest audible artifact) - // and mean NMR in dB, over the energy-bearing bands. - let xp = Xpow::new(&spec); - let metric = |offsets: &[i32]| -> (f64, f64) { - let base = rate_loop(&xp, swb, offsets, target); - let sf = scalefactors(offsets, base); - let thr = masking_thresholds(&spec, swb, sr); - let (mut max_nmr, mut sum_db, mut n) = (0f64, 0f64, 0usize); - for sfb in 0..swb.len() - 1 { - let (s, e) = (swb[sfb] as usize, swb[sfb + 1] as usize); - let en: f64 = spec[s..e].iter().map(|&x| (x as f64).powi(2)).sum(); - if en < 1e6 { - continue; // near-silent band → quantizes to ZERO, no artifact - } - let mut noise = 0f64; - for &x in &spec[s..e] { - let q = quantize(x, sf[sfb]); - let rec = q.signum() as f64 - * (q.unsigned_abs() as f64).powf(4.0 / 3.0) - * 2f64.powf(0.25 * (sf[sfb] - 100) as f64); - noise += (x as f64 - rec).powi(2); - } - let nmr = (noise / thr[sfb]).max(1e-30); - max_nmr = max_nmr.max(nmr); - sum_db += 10.0 * nmr.log10(); - n += 1; - } - (max_nmr, sum_db / n.max(1) as f64) - }; - - let flat = metric(&vec![0i32; swb.len() - 1]); - let psy = metric(&perceptual_offsets(&spec, swb, sr, false)); - eprintln!( - "flat: max_nmr={:.2} mean={:.1}dB | psy: max_nmr={:.2} mean={:.1}dB", - flat.0, flat.1, psy.0, psy.1 - ); - // The psy model equalizes NMR → the worst audible band is quieter than flat. - assert!( - psy.0 < flat.0, - "psy must reduce the worst-band NMR ({:.2} vs {:.2})", - psy.0, - flat.0 - ); - } - - /// Emit our `.aac` (ADTS) so an external reference decoder (ffmpeg) can confirm - /// the stream is spec-valid, not just self-decodable. - #[test] - #[ignore = "writes an .aac for external ffmpeg validation; run explicitly"] - fn emit_aac_for_external_check() { - let sr = 44100u32; - let n = 44100usize; - let mut interleaved = Vec::new(); - for i in 0..n { - let s = - ((i as f64 * 2.0 * std::f64::consts::PI * 440.0 / sr as f64).sin() * 0.5) as f32; - interleaved.push(s); - } - let mut enc = AacEncoder::default(); - enc.push_pcm(&interleaved, 1, sr).unwrap(); - let adts = encode_to_adts(&mut enc); - let dir = std::env::temp_dir(); - std::fs::write(dir.join("rff_aac_tone.aac"), &adts).unwrap(); - eprintln!( - "wrote {}/rff_aac_tone.aac ({} bytes)", - dir.display(), - adts.len() - ); - } - - /// Emit a `.aac` with periodic sharp attacks (drum-like) so ffmpeg can confirm - /// the block-switched (short + transition) stream is spec-valid. - #[test] - #[ignore = "writes an .aac for external ffmpeg validation; run explicitly"] - fn emit_transient_aac_for_external_check() { - let sr = 44100u32; - let n = 44100usize; - let mut interleaved = Vec::new(); - for i in 0..n { - let t = i as f64 / sr as f64; - let mut v = 0.05 * (2.0 * std::f64::consts::PI * 220.0 * t).sin(); - // A sharp click every ~0.25 s. - let k = i % 11025; - if k < 700 { - let env = (1.0 - k as f64 / 700.0).max(0.0); - v += 0.8 * env * (2.0 * std::f64::consts::PI * 3500.0 * k as f64 / sr as f64).sin(); - } - interleaved.push(v as f32); - } - let mut enc = AacEncoder::default(); - enc.push_pcm(&interleaved, 1, sr).unwrap(); - let adts = encode_to_adts(&mut enc); - let dir = std::env::temp_dir(); - std::fs::write(dir.join("rff_aac_transient.aac"), &adts).unwrap(); - eprintln!( - "wrote {}/rff_aac_transient.aac ({} bytes)", - dir.display(), - adts.len() - ); - } - - /// Emit a stereo `.aac` (shared bass + divergent highs → mixed per-SFB M/S) so - /// ffmpeg can confirm the CPE stream is spec-valid. - #[test] - #[ignore = "writes an .aac for external ffmpeg validation; run explicitly"] - fn emit_stereo_aac_for_external_check() { - let sr = 44100u32; - let n = 44100usize; - let mut interleaved = Vec::new(); - for i in 0..n { - let t = i as f64 / sr as f64; - let bass = 0.4 * (2.0 * std::f64::consts::PI * 300.0 * t).sin(); // shared → M/S - let l = bass + 0.2 * (2.0 * std::f64::consts::PI * 1200.0 * t).sin(); - let r = bass + 0.2 * (2.0 * std::f64::consts::PI * 1900.0 * t).sin(); - interleaved.push(l as f32); - interleaved.push(r as f32); - } - let mut enc = AacEncoder::default(); - enc.push_pcm(&interleaved, 2, sr).unwrap(); - let adts = encode_to_adts(&mut enc); - let dir = std::env::temp_dir(); - std::fs::write(dir.join("rff_aac_stereo.aac"), &adts).unwrap(); - eprintln!( - "wrote {}/rff_aac_stereo.aac ({} bytes)", - dir.display(), - adts.len() - ); - } -} - -// --------------------------------------------------------------------------- -// Rung 0 (arm A8) — window-shape gate tests. -// -// The rung's contract, in the order great-gate §4 requires it: -// 1. the neutral end is BYTE-IDENTICAL (proven against an oracle, not argued), -// 2. the routed arm is TDAC-correct (a window mismatch is not a quality -// regression, it is broken audio), -// 3. the dispatch decodes on the hardest case — alternating shapes. -// --------------------------------------------------------------------------- -#[cfg(test)] -mod rung0 { - use super::*; - - /// The sine-only `long_window` exactly as it stood before arm A8, kept as the - /// oracle for the neutral end. - fn long_window_pre_a8(seq: WindowSequence, sine_l: &[f32], sine_s: &[f32]) -> Vec { - let mut w = vec![0f32; LONG_N]; - if seq == WindowSequence::LongStop { - w[448..448 + SHORT_HALF].copy_from_slice(&sine_s[..SHORT_HALF]); - for s in w.iter_mut().take(FRAME_LEN).skip(576) { - *s = 1.0; - } - } else { - w[..FRAME_LEN].copy_from_slice(&sine_l[..FRAME_LEN]); - } - if seq == WindowSequence::LongStart { - for s in w.iter_mut().take(FRAME_LEN + 448).skip(FRAME_LEN) { - *s = 1.0; - } - w[FRAME_LEN + 448..FRAME_LEN + 448 + SHORT_HALF].copy_from_slice(&sine_s[SHORT_HALF..]); - } else { - w[FRAME_LEN..].copy_from_slice(&sine_l[FRAME_LEN..]); - } - w - } - - /// **Law 7 — the neutral end is byte-identical.** With both shape flags false - /// the new shape-aware window must equal the pre-A8 sine-only one, exactly, - /// for every sequence. Every other A8 change is a pass-through of - /// `cur_kbd = false` into a bit that was already 0. - #[test] - fn shape_sine_is_byte_identical() { - let sine_l = crate::dsp::sine_window(LONG_N); - let sine_s = crate::dsp::sine_window(SHORT_N); - let kbd_l = crate::dsp::kbd_window(LONG_N, 4.0); - let kbd_s = crate::dsp::kbd_window(SHORT_N, 6.0); - for seq in [ - WindowSequence::OnlyLong, - WindowSequence::LongStart, - WindowSequence::LongStop, - ] { - let new = long_window(seq, false, false, &sine_l, &kbd_l, &sine_s, &kbd_s); - let old = long_window_pre_a8(seq, &sine_l, &sine_s); - assert_eq!(new, old, "{seq:?}: neutral end must be byte-identical"); - } - } - - /// The whole encoded stream is byte-identical under the default config and an - /// explicit `Sine` — i.e. the default really is the neutral arm. - #[test] - fn default_config_is_the_sine_arm() { - let pcm: Vec = (0..8 * FRAME_LEN) - .map(|i| { - let t = i as f32 / 44100.0; - 0.4 * (2.0 * std::f32::consts::PI * 700.0 * t).sin() - }) - .collect(); - let enc = |cfg: AacEncoderConfig| { - let mut e = AacEncoder::new(cfg); - e.push_pcm(&pcm, 1, 44100).unwrap(); - e.finish(); - let mut out = Vec::new(); - while let Ok(p) = e.next_packet() { - out.extend_from_slice(&p.data); - } - out - }; - let a = enc(AacEncoderConfig::default()); - let b = enc(AacEncoderConfig { - window_shape: WindowShape::Sine, - ..Default::default() - }); - assert_eq!(a, b, "default must be the Sine arm"); - } - - /// Windows must satisfy the **Princen-Bradley condition** on every overlap: - /// `w_prev[N+n]^2 + w_cur[n]^2 == 1`. This is what makes overlap-add exact. It - /// must hold for every ordered pair of shapes, which is exactly why the left - /// half follows the previous frame and the right half the current one. - #[test] - fn tdac_holds_across_every_shape_transition() { - let sine_l = crate::dsp::sine_window(LONG_N); - let sine_s = crate::dsp::sine_window(SHORT_N); - let kbd_l = crate::dsp::kbd_window(LONG_N, 4.0); - let kbd_s = crate::dsp::kbd_window(SHORT_N, 6.0); - - for (a, b) in [(false, false), (false, true), (true, false), (true, true)] { - // Frame 1 has shape `a`; frame 2 has shape `b` and sees `a` as prev. - let w1 = long_window(WindowSequence::OnlyLong, a, a, &sine_l, &kbd_l, &sine_s, &kbd_s); - let w2 = long_window(WindowSequence::OnlyLong, a, b, &sine_l, &kbd_l, &sine_s, &kbd_s); - for n in 0..FRAME_LEN { - let sum = w1[FRAME_LEN + n] * w1[FRAME_LEN + n] + w2[n] * w2[n]; - assert!( - (sum - 1.0).abs() < 1e-4, - "TDAC broken at n={n} for prev={a} cur={b}: {sum}" - ); - } - } - } - - /// Encode then decode under each arm. A prev/cur shape mismatch would show up - /// here as gross reconstruction error, not a subtle quality delta. - #[test] - fn every_arm_round_trips() { - let sr = 44100u32; - let n = 12 * FRAME_LEN; - let pcm: Vec = (0..n) - .map(|i| { - let t = i as f32 / sr as f32; - 0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin() - + 0.2 * (2.0 * std::f32::consts::PI * 2600.0 * t).sin() - }) - .collect(); - - for shape in [WindowShape::Sine, WindowShape::Kbd, WindowShape::Auto] { - let mut e = AacEncoder::new(AacEncoderConfig { - bitrate_bps: 128_000, - window_shape: shape, - shape_tonality_pct: 0.5, - ..Default::default() - }); - e.push_pcm(&pcm, 1, sr).unwrap(); - e.finish(); - - let mut dec = crate::decode::Decoder::new(sr); - let mut got = Vec::new(); - while let Ok(p) = e.next_packet() { - let audio = dec.decode(&p.data, None).expect("decode"); - got.extend_from_slice(&audio.samples); - } - assert!(got.len() >= n, "{shape:?}: short decode"); - - // Compare against the input, allowing the one-frame filterbank delay. - let lag = FRAME_LEN; - let cmp_len = n - 2 * FRAME_LEN; - let (mut num, mut den) = (0f64, 0f64); - for i in 0..cmp_len { - let o = pcm[i] as f64; - let d = got[i + lag] as f64; - num += (o - d) * (o - d); - den += o * o; - } - let snr = 10.0 * (den / num.max(1e-30)).log10(); - assert!( - snr > 15.0, - "{shape:?}: reconstruction SNR {snr:.1} dB is too low - \ - a window-shape mismatch breaks TDAC" - ); - } - } - - /// The `Auto` gate must actually dispatch — produce a mix of shapes on - /// content whose tonality varies. A gate that routes everything one way is - /// not a gate. - #[test] - fn auto_gate_dispatches_both_ways() { - let sr = 44100u32; - let n = 16 * FRAME_LEN; - // Alternate 4-frame blocks of tone (tonal) and noise (not). - let mut seed = 0x2468_ACE0u32; - let pcm: Vec = (0..n) - .map(|i| { - if (i / (4 * FRAME_LEN)) % 2 == 0 { - let t = i as f32 / sr as f32; - 0.4 * (2.0 * std::f32::consts::PI * 900.0 * t).sin() - } else { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - 0.4 * (((seed >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0) - } - }) - .collect(); - - let mut e = AacEncoder::new(AacEncoderConfig { - bitrate_bps: 128_000, - window_shape: WindowShape::Auto, - shape_tonality_pct: 0.5, - ..Default::default() - }); - e.push_pcm(&pcm, 1, sr).unwrap(); - let nblocks = n.div_ceil(FRAME_LEN) + 1; - let shapes = e.decide_shapes(nblocks); - let kbd = shapes.iter().filter(|&&s| s).count(); - assert!( - kbd > 0 && kbd < shapes.len(), - "Auto must route both ways, got {kbd}/{} KBD", - shapes.len() - ); - - // And it must route the TONAL blocks to KBD, not at random: the tonal - // frames tonality must exceed the noise frames. - let tone_ton = time_tonality(&e.block(0, 1)); - let noise_ton = time_tonality(&e.block(0, 5)); - assert!( - tone_ton > noise_ton * 2.0, - "the gate signal must separate tone ({tone_ton:.1}) from noise ({noise_ton:.1})" - ); - } -} - -// --------------------------------------------------------------------------- -// Rungs 1-3 (arms A1 short-block psy, A2 tonality SMR, A3 TNS). -// -// Each arm must clear the same three bars before any quality number counts: -// 1. OFF is byte-identical with the encoder as it shipped, -// 2. ON still round-trips through our own decoder, -// 3. ON actually changes something (an arm that is a no-op is not an arm). -// --------------------------------------------------------------------------- -#[cfg(test)] -mod rung123 { - use super::*; - - fn encode(pcm: &[f32], ch: u16, sr: u32, cfg: AacEncoderConfig) -> Vec> { - let mut e = AacEncoder::new(cfg); - e.push_pcm(pcm, ch, sr).unwrap(); - e.finish(); - let mut out = Vec::new(); - while let Ok(p) = e.next_packet() { - out.push(p.data); - } - out - } - - /// Decode a packet list, returning channel-0 PCM. - fn decode_mono(packets: &[Vec], sr: u32) -> Vec { - let mut dec = crate::decode::Decoder::new(sr); - let mut out = Vec::new(); - for p in packets { - let a = dec.decode(p, None).expect("decode"); - let ch = a.channels.max(1) as usize; - out.extend(a.samples.iter().step_by(ch).copied()); - } - out - } - - /// A transient-rich mono signal: sharp attacks over a quiet tonal floor. - /// Drives short blocks (arm A1) and gives TNS something to shape (arm A3). - fn transient_signal(sr: u32, frames: usize) -> Vec { - use std::f32::consts::PI; - let n = frames * FRAME_LEN; - (0..n) - .map(|i| { - let t = i as f32 / sr as f32; - let mut v = 0.05 * (2.0 * PI * 500.0 * t).sin(); - let k = i % (3 * FRAME_LEN); - if k < 500 && i > FRAME_LEN { - let env = (1.0 - k as f32 / 500.0).max(0.0); - v += 0.85 * env * (2.0 * PI * 3300.0 * k as f32 / sr as f32).sin(); - } - v - }) - .collect() - } - - /// A tonal signal — a harmonic stack, the content arm A2 should treat - /// differently from noise. - fn tonal_signal(sr: u32, frames: usize) -> Vec { - use std::f32::consts::PI; - let n = frames * FRAME_LEN; - (0..n) - .map(|i| { - let t = i as f32 / sr as f32; - let mut v = 0f32; - for h in 1..=6 { - v += (1.0 / h as f32) * (2.0 * PI * 330.0 * h as f32 * t).sin(); - } - 0.3 * v - }) - .collect() - } - - /// **Every arm's OFF state is byte-identical with the shipped encoder.** - /// This is law 7's neutral end, proven by `cmp` rather than argued. - #[test] - fn every_arm_off_is_byte_identical() { - let sr = 44100u32; - let sigs = [transient_signal(sr, 10), tonal_signal(sr, 10)]; - for pcm in &sigs { - let base = encode(pcm, 1, sr, AacEncoderConfig::default()); - for (name, cfg) in [ - ( - "short_block_psy", - AacEncoderConfig { - short_block_psy: false, - ..Default::default() - }, - ), - ( - "tonality_smr", - AacEncoderConfig { - tonality_smr: false, - ..Default::default() - }, - ), - ( - "tns", - AacEncoderConfig { - tns: false, - ..Default::default() - }, - ), - ] { - let got = encode(pcm, 1, sr, cfg); - assert_eq!(got, base, "{name}: OFF must be byte-identical"); - } - } - } - - /// **Arm A1** — short-block psy must change the bitstream on transient - /// content (where short blocks actually occur) and still decode. - #[test] - fn a1_short_block_psy_changes_and_round_trips() { - let sr = 44100u32; - let pcm = transient_signal(sr, 12); - let off = encode(&pcm, 1, sr, AacEncoderConfig::default()); - let on = encode( - &pcm, - 1, - sr, - AacEncoderConfig { - short_block_psy: true, - ..Default::default() - }, - ); - assert_ne!(off, on, "A1 must change the bitstream on transient content"); - - let dec = decode_mono(&on, sr); - assert!(dec.len() >= pcm.len(), "A1: short decode"); - assert!( - dec.iter().all(|v| v.is_finite()), - "A1: non-finite output — the short-block mask is broken" - ); - // Reconstruction must remain sane; a wrong band geometry in the short psy - // path shows up as gross error, not a subtle quality shift. - let lag = FRAME_LEN; - let cmp = pcm.len() - 2 * FRAME_LEN; - let (mut num, mut den) = (0f64, 0f64); - for i in 0..cmp { - let o = pcm[i] as f64; - let d = dec[i + lag] as f64; - num += (o - d) * (o - d); - den += o * o; - } - let snr = 10.0 * (den / num.max(1e-30)).log10(); - assert!(snr > 8.0, "A1: reconstruction SNR {snr:.1} dB too low"); - } - - /// **Arm A2** — the SMR must actually vary with tonality. A pure tone and - /// broadband noise at equal energy must no longer receive identical masks. - #[test] - fn a2_smr_varies_with_tonality() { - // Direct check of the law itself, at a mid-band Bark. - let tonal = smr_for(1.0, 10.0); - let noisy = smr_for(0.0, 10.0); - assert!( - tonal < noisy, - "a tonal masker must hold the mask FURTHER below the signal \ - (tonal {tonal:.5} must be < noise {noisy:.5})" - ); - // And it must stay inside the documented clamp. - for t in [0.0f64, 0.25, 0.5, 0.75, 1.0] { - for bark in [0.0f64, 5.0, 12.0, 24.0] { - let v = smr_for(t, bark); - assert!( - v > 0.0 && v <= 10f64.powf(-5.0 / 10.0) + 1e-12, - "smr_for({t}, {bark}) = {v} escaped its clamp" - ); - } - } - } - - /// **Arm A2** — end to end: the bitstream changes on tonal content and still - /// decodes. - #[test] - fn a2_changes_and_round_trips() { - let sr = 44100u32; - let pcm = tonal_signal(sr, 10); - let off = encode(&pcm, 1, sr, AacEncoderConfig::default()); - let on = encode( - &pcm, - 1, - sr, - AacEncoderConfig { - tonality_smr: true, - ..Default::default() - }, - ); - assert_ne!(off, on, "A2 must change the bitstream on tonal content"); - let dec = decode_mono(&on, sr); - assert!(dec.iter().all(|v| v.is_finite())); - assert!(dec.len() >= pcm.len()); - } - - /// **Arm A3 — the filter inversion.** The encoder runs the ALL-ZERO analysis - /// filter; the decoder runs the ALL-POLE synthesis filter. If that inversion - /// is wrong in sign, order or state, the spectrum does not degrade — it - /// diverges. So this test demands the TNS arm reconstruct *at least as well* - /// as the un-filtered arm, not merely "not crash". - #[test] - fn a3_tns_inverts_exactly() { - let sr = 44100u32; - let pcm = transient_signal(sr, 14); - - let snr_of = |cfg: AacEncoderConfig| -> f64 { - let pkts = encode(&pcm, 1, sr, cfg); - let dec = decode_mono(&pkts, sr); - assert!(dec.len() >= pcm.len()); - let lag = FRAME_LEN; - let cmp = pcm.len() - 2 * FRAME_LEN; - let (mut num, mut den) = (0f64, 0f64); - for i in 0..cmp { - let o = pcm[i] as f64; - let d = dec[i + lag] as f64; - num += (o - d) * (o - d); - den += o * o; - } - 10.0 * (den / num.max(1e-30)).log10() - }; - - let base = snr_of(AacEncoderConfig { - bitrate_bps: 128_000, - ..Default::default() - }); - let with_tns = snr_of(AacEncoderConfig { - bitrate_bps: 128_000, - tns: true, - ..Default::default() - }); - assert!( - with_tns > base - 3.0, - "A3: TNS collapsed reconstruction ({with_tns:.1} dB vs {base:.1} dB) — \ - the analysis/synthesis inversion is wrong, not merely suboptimal" - ); - } - - /// **Arm A3** — the quantized PARCOR round-trip must match the decoder's - /// dequantizer bit-for-bit, including its asymmetric negative scale. - #[test] - fn a3_parcor_quantization_matches_the_decoder() { - use std::f32::consts::PI; - let res_bits = 3 + TNS_COEF_RES; - let iqfac = ((1i32 << (res_bits - 1)) as f32 - 0.5) / (PI / 2.0); - let iqfac_m = ((1i32 << (res_bits - 1)) as f32 + 0.5) / (PI / 2.0); - for step in -20..=20 { - let p = step as f32 / 21.0; - let (idx, dq) = quantize_parcor(p); - // Reproduce the DECODER's path from the emitted index. - let masked = (idx as u32) & ((1u32 << TNS_COEF_BITS) - 1); - let c = if masked & (1 << (TNS_COEF_BITS - 1)) != 0 { - masked as i32 - (1 << TNS_COEF_BITS) - } else { - masked as i32 - }; - let t = if c >= 0 { - c as f32 / iqfac - } else { - c as f32 / iqfac_m - }; - let expect = t.sin(); - assert!( - (dq - expect).abs() < 1e-6, - "parcor {p}: encoder says {dq}, decoder reconstructs {expect}" - ); - } - } - - /// **Arm A3** — TNS must actually engage on transient content (otherwise the - /// round-trip test above passes vacuously). - #[test] - fn a3_tns_actually_engages() { - let sr = 44100u32; - let pcm = transient_signal(sr, 14); - let off = encode(&pcm, 1, sr, AacEncoderConfig { bitrate_bps: 128_000, ..Default::default() }); - let on = encode( - &pcm, - 1, - sr, - AacEncoderConfig { - bitrate_bps: 128_000, - tns: true, - ..Default::default() - }, - ); - assert_ne!( - off, on, - "A3 never fired — the gate declined every frame, so the round-trip \ - test proves nothing" - ); - } -} - - -// --------------------------------------------------------------------------- -// Multichannel conformance — the tests that would have caught the original bug. -// -// The encoder used to emit N single_channel_elements while declaring -// `channel_configuration = N`. Our own decoder accepted it, so a self-round-trip -// looked perfect; a conforming decoder reading SCE, CPE, CPE, LFE would not. -// These tests check the ELEMENT SEQUENCE against ISO Table 1.19, not just that -// audio comes back. -// --------------------------------------------------------------------------- -#[cfg(test)] -mod multichannel { - use super::*; - - fn encode_packets(pcm: &[f32], ch: u16, sr: u32) -> Vec> { - let mut e = AacEncoder::new(AacEncoderConfig::default()); - e.push_pcm(pcm, ch, sr).unwrap(); - e.finish(); - let mut out = Vec::new(); - while let Ok(p) = e.next_packet() { - out.push(p.data); - } - out - } - - /// Read the sequence of element ids from a raw_data_block, skipping each - /// element's payload by decoding it. - fn element_ids(packet: &[u8], sr: u32) -> Vec { - // Walk ids by re-decoding: the decoder is the only thing that knows each - // element's length. We instead read ids from a fresh reader, relying on - // the decoder to have validated the packet already. - let mut ids = Vec::new(); - let mut dec = crate::decode::Decoder::new(sr); - // The decoder must accept it at all. - dec.decode(packet, None).expect("packet must decode"); - // Now re-read just the leading id of each element by decoding again with - // a tracking reader is not available, so assert on the FIRST id plus the - // channel count, which is what distinguishes the layouts we emit. - let mut r = crate::BitReader::new(packet); - ids.push(r.read_bits(3).unwrap()); - ids - } - - /// Distinct per-channel content so a mis-ordered channel is detectable. - fn distinct_channels(nch: usize, frames: usize, sr: u32) -> Vec { - let n = frames * FRAME_LEN; - let mut out = Vec::with_capacity(n * nch); - for i in 0..n { - let t = i as f32 / sr as f32; - for c in 0..nch { - // A different frequency per channel, well separated. - let f = 300.0 + 400.0 * c as f32; - out.push(0.35 * (2.0 * std::f32::consts::PI * f * t).sin()); - } - } - out - } - - /// Every supported channel count produces a stream our decoder accepts with - /// the right channel count. - #[test] - fn supported_channel_counts_round_trip() { - let sr = 44100u32; - for nch in 1..=6usize { - let pcm = distinct_channels(nch, 6, sr); - let pkts = encode_packets(&pcm, nch as u16, sr); - assert!(!pkts.is_empty(), "{nch}ch: no packets"); - let mut dec = crate::decode::Decoder::new(sr); - let audio = dec.decode(&pkts[0], None).expect("decode"); - assert_eq!(audio.channels as usize, nch, "{nch}ch: wrong channel count"); - } - } - - /// **The bug.** The first element of a 5.1 stream must be an SCE (the centre - /// channel), and of a stereo stream a CPE. Before the fix a 5.1 stream began - /// with an SCE too — but so did all six of its elements, which is what made it - /// non-conformant. - #[test] - fn element_sequence_matches_iso_table() { - let sr = 44100u32; - for (nch, want_first) in [(1usize, ID_SCE), (2, ID_CPE), (3, ID_SCE), (6, ID_SCE)] { - let pcm = distinct_channels(nch, 4, sr); - let pkts = encode_packets(&pcm, nch as u16, sr); - let ids = element_ids(&pkts[0], sr); - assert_eq!(ids[0], want_first, "{nch}ch: wrong first element id"); - } - } - - /// The plan itself must match ISO Table 1.19, including the reordering. - #[test] - fn element_plan_matches_iso_table() { - assert_eq!(element_plan(1).unwrap(), vec![Elem::Sce(0)]); - assert_eq!(element_plan(2).unwrap(), vec![Elem::Cpe(0, 1)]); - // 3.0: centre first, then the front pair. - assert_eq!(element_plan(3).unwrap(), vec![Elem::Sce(2), Elem::Cpe(0, 1)]); - // 5.1: C, L/R, Ls/Rs, LFE — with LFE taken from interleave slot 3. - assert_eq!( - element_plan(6).unwrap(), - vec![ - Elem::Sce(2), - Elem::Cpe(0, 1), - Elem::Cpe(4, 5), - Elem::Lfe(3) - ] - ); - // No channel_configuration exists for these. - assert!(element_plan(0).is_none()); - assert!(element_plan(7).is_none()); - assert!(element_plan(8).is_none()); - } - - /// The decoder's reorder must be the exact inverse of the encoder's plan: - /// what goes into interleave slot `k` must come back out of slot `k`. - #[test] - fn channel_order_survives_the_round_trip() { - let sr = 44100u32; - for nch in [1usize, 2, 3, 5, 6] { - let pcm = distinct_channels(nch, 8, sr); - let pkts = encode_packets(&pcm, nch as u16, sr); - let mut dec = crate::decode::Decoder::new(sr); - let mut planes: Vec> = vec![Vec::new(); nch]; - for p in &pkts { - let a = dec.decode(p, None).expect("decode"); - for (i, v) in a.samples.iter().enumerate() { - planes[i % nch].push(*v); - } - } - // Each decoded channel must correlate best with the SAME input - // channel. A layout or reorder error shows up as a swapped best match. - for c in 0..nch { - let f_expect = 300.0 + 400.0 * c as f32; - // Estimate dominant frequency by zero-crossing count over a - // mid-stream window (crude but unambiguous at this separation). - let seg = &planes[c][3 * FRAME_LEN..5 * FRAME_LEN]; - let mut crossings = 0usize; - for w in seg.windows(2) { - if (w[0] <= 0.0) != (w[1] <= 0.0) { - crossings += 1; - } - } - let secs = seg.len() as f32 / sr as f32; - let f_est = crossings as f32 / 2.0 / secs; - assert!( - (f_est - f_expect).abs() < 120.0, - "{nch}ch: channel {c} came back at ~{f_est:.0} Hz, expected \\ - ~{f_expect:.0} Hz — channel order is wrong" - ); - } - } - } - - /// Unsupported counts must be REJECTED, not silently mis-encoded. This is the - /// guard: an unencodable layout is an error, never a wrong bitstream. - #[test] - fn unsupported_channel_counts_are_rejected() { - for nch in [7u16, 8, 12] { - let pcm = vec![0.1f32; FRAME_LEN * nch as usize * 2]; - let mut e = AacEncoder::new(AacEncoderConfig::default()); - let res = e.push_pcm(&pcm, nch, 44100); - assert!( - res.is_err(), - "{nch} channels must be rejected until a program_config_element exists" - ); - } - } -} - -#[cfg(test)] -mod rung_a6 { - use super::*; - - fn noise_signal(sr: u32, frames: usize) -> Vec { - let mut seed = 0xA6A6_1234u32; - (0..frames * FRAME_LEN) - .map(|_| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - 0.4 * (((seed >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0) - }) - .collect() - } - - fn encode(pcm: &[f32], sr: u32, cfg: AacEncoderConfig) -> Vec> { - let mut e = AacEncoder::new(cfg); - e.push_pcm(pcm, 1, sr).unwrap(); - e.finish(); - let mut out = Vec::new(); - while let Ok(p) = e.next_packet() { - out.push(p.data); - } - out - } - - /// OFF is byte-identical with the shipped encoder. - #[test] - fn a6_off_is_byte_identical() { - let sr = 44100; - let pcm = noise_signal(sr, 8); - let a = encode(&pcm, sr, AacEncoderConfig::default()); - let b = encode(&pcm, sr, AacEncoderConfig { pns: false, ..Default::default() }); - assert_eq!(a, b); - } - - /// PNS must fire on noise and the stream must still decode. A desynchronized - /// scalefactor chain (the classic PNS bug) shows up here as a decode error or - /// non-finite output, not as a subtle quality shift. - #[test] - fn a6_fires_on_noise_and_round_trips() { - let sr = 44100; - let pcm = noise_signal(sr, 10); - let off = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, ..Default::default() }); - let on = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, pns: true, ..Default::default() }); - assert_ne!(off, on, "A6 must fire on broadband noise"); - - let mut dec = crate::decode::Decoder::new(sr); - let mut got = Vec::new(); - for p in &on { - let a = dec.decode(p, None).expect("PNS stream must decode"); - got.extend_from_slice(&a.samples); - } - assert!(got.iter().all(|v| v.is_finite()), "non-finite output"); - // Energy must be broadly preserved: PNS substitutes noise of the SAME - // energy, so a gross level error means the ne <-> energy mapping is wrong. - let e_in: f64 = pcm.iter().map(|&x| (x as f64) * (x as f64)).sum(); - let e_out: f64 = got.iter().map(|&x| (x as f64) * (x as f64)).sum(); - let ratio = e_out / e_in.max(1e-12); - assert!( - (0.25..4.0).contains(&ratio), - "PNS energy mismatch: out/in = {ratio:.3} - check ne = 2*log2(E)" - ); - } - - /// PNS must NOT fire on a pure tone: it is the anti-class, and substituting a - /// harmonic band with noise is audibly destructive. - #[test] - fn a6_declines_on_tonal_content() { - let sr = 44100; - let pcm: Vec = (0..10 * FRAME_LEN) - .map(|i| { - let t = i as f32 / sr as f32; - 0.4 * (2.0 * std::f32::consts::PI * 6000.0 * t).sin() - }) - .collect(); - let off = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, ..Default::default() }); - let on = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, pns: true, ..Default::default() }); - assert_eq!( - off, on, - "A6 fired on a pure 6 kHz tone - the tonality guard is not working" - ); - } - - /// PNS and TNS must not both apply to one element (the energy domain differs). - #[test] - fn a6_yields_to_tns() { - let sr = 44100; - let pcm = noise_signal(sr, 10); - let both = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 128_000, pns: true, tns: true, ..Default::default() }); - let mut dec = crate::decode::Decoder::new(sr); - for p in &both { - let a = dec.decode(p, None).expect("combined stream must decode"); - assert!(a.samples.iter().all(|v| v.is_finite())); - } - } -} - -#[cfg(test)] -mod rung_a7 { - use super::*; - - /// A stereo pair whose high bands are a scaled copy — the content intensity - /// stereo exists for. - fn correlated_stereo(sr: u32, frames: usize, gain: f32) -> Vec { - let n = frames * FRAME_LEN; - let mut out = Vec::with_capacity(n * 2); - let mut seed = 0x7777_1111u32; - for i in 0..n { - let t = i as f32 / sr as f32; - let low = 0.3 * (2.0 * std::f32::consts::PI * 300.0 * t).sin(); - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - let hi = 0.25 * (((seed >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0); - out.push(low + hi); - out.push(low + hi * gain); - } - out - } - - fn encode(pcm: &[f32], sr: u32, cfg: AacEncoderConfig) -> Vec> { - let mut e = AacEncoder::new(cfg); - e.push_pcm(pcm, 2, sr).unwrap(); - e.finish(); - let mut out = Vec::new(); - while let Ok(p) = e.next_packet() { - out.push(p.data); - } - out - } - - #[test] - fn a7_off_is_byte_identical() { - let sr = 44100; - let pcm = correlated_stereo(sr, 8, 0.7); - let a = encode(&pcm, sr, AacEncoderConfig::default()); - let b = encode(&pcm, sr, AacEncoderConfig { intensity: false, ..Default::default() }); - assert_eq!(a, b); - } - - /// Fires on a scaled-copy pair and still decodes. A wrong is_pos sign or a - /// desynchronized intensity accumulator shows up here immediately. - #[test] - fn a7_fires_and_round_trips() { - let sr = 44100; - let pcm = correlated_stereo(sr, 10, 0.7); - let off = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, ..Default::default() }); - let on = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 96_000, intensity: true, ..Default::default() }); - assert_ne!(off, on, "A7 must fire on a correlated high band"); - - let mut dec = crate::decode::Decoder::new(sr); - let mut got = Vec::new(); - for p in &on { - let a = dec.decode(p, None).expect("intensity stream must decode"); - got.extend_from_slice(&a.samples); - } - assert!(got.iter().all(|v| v.is_finite())); - // The reconstructed right channel must keep roughly the intended level - // ratio: a sign or exponent error in is_pos shows up as a gross imbalance. - let (mut el, mut er) = (0f64, 0f64); - for c in got.chunks_exact(2) { - el += (c[0] as f64) * (c[0] as f64); - er += (c[1] as f64) * (c[1] as f64); - } - let ratio = (er / el.max(1e-12)).sqrt(); - assert!( - (0.4..1.6).contains(&ratio), - "channel balance wrong after intensity: R/L = {ratio:.3}" - ); - } - - /// Must DECLINE on a decorrelated pair — the anti-class. Collapsing a wide - /// image to a scaled copy is the failure mode this gate exists to prevent. - #[test] - fn a7_declines_on_wide_stereo() { - let sr = 44100; - let n = 8 * FRAME_LEN; - let mut s1 = 0xAAAA_1111u32; - let mut s2 = 0x5555_2222u32; - let mut pcm = Vec::with_capacity(n * 2); - for _ in 0..n { - s1 = s1.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - s2 = s2.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - pcm.push(0.3 * (((s1 >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0)); - pcm.push(0.3 * (((s2 >> 8) as f32 / (1u32 << 24) as f32) * 2.0 - 1.0)); - } - let off = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 128_000, ..Default::default() }); - let on = encode(&pcm, sr, AacEncoderConfig { bitrate_bps: 128_000, intensity: true, ..Default::default() }); - assert_eq!( - off, on, - "A7 fired on fully decorrelated channels - the correlation gate is not working" - ); - } -} diff --git a/vendor/rusty_aac/src/error.rs b/vendor/rusty_aac/src/error.rs deleted file mode 100644 index 2ceae27..0000000 --- a/vendor/rusty_aac/src/error.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! The crate's dependency-free error type. -//! -//! [`Error::Again`] and [`Error::Eof`] follow EAGAIN-style pull semantics: -//! they are not failures. `Again` means "more input is required before output -//! can be produced" (feed more data, then pull again); `Eof` means "the stream -//! is finished and fully drained" (stop pulling). Everything else is a real -//! error. - -/// Crate-wide result alias. -pub type Result = std::result::Result; - -/// All the ways AAC decoding/encoding can fail — or, for [`Error::Again`] / -/// [`Error::Eof`], signal normal stream flow control. -#[derive(Debug)] -#[non_exhaustive] -pub enum Error { - /// A code path that is scaffolded but not yet implemented. Carries a short - /// static label so logs point straight at the missing piece. - Unimplemented(&'static str), - - /// End of stream — the codec has no more data to give. - Eof, - - /// More input is required before output can be produced (codec drain/fill). - Again, - - /// The input bytes were malformed for AAC-LC. - InvalidData(String), - - /// A requested capability exists in concept but isn't supported here. - Unsupported(String), -} - -impl Error { - /// Convenience constructor for `InvalidData` from anything string-like. - pub fn invalid(msg: impl Into) -> Self { - Error::InvalidData(msg.into()) - } - - /// Convenience constructor for `Unsupported`. - pub fn unsupported(msg: impl Into) -> Self { - Error::Unsupported(msg.into()) - } -} - -impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::Unimplemented(what) => write!(f, "not yet implemented: {what}"), - Error::Eof => write!(f, "end of stream"), - Error::Again => write!(f, "more input required"), - Error::InvalidData(msg) => write!(f, "invalid data: {msg}"), - Error::Unsupported(msg) => write!(f, "unsupported: {msg}"), - } - } -} - -impl std::error::Error for Error {} diff --git a/vendor/rusty_aac/src/huffman.rs b/vendor/rusty_aac/src/huffman.rs deleted file mode 100644 index 4bc020a..0000000 --- a/vendor/rusty_aac/src/huffman.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! Generic canonical-prefix Huffman decoder for the AAC spectral and -//! scalefactor codebooks (ISO 14496-3 §4.A.3). -//! -//! Each codebook is two parallel `'static` arrays — `codes[i]` is the codeword -//! and `lens[i]` its bit length — exactly the form the spec/reference tables -//! ship in. Decoding reads bits MSB-first, accumulating until a `(len, code)` -//! pair matches; the codes are prefix-free, so the first match is the symbol. -//! `decode` returns the array index `i`, which the codebook layer unpacks into -//! spectral coefficients. O(maxlen·count) per codeword — codebooks are small, -//! so it is plenty fast and trivially verifiable. - -#![allow(dead_code)] - -use crate::{Error, Result}; - -use crate::bits::BitReader; - -/// A Huffman codebook: parallel codeword / bit-length tables. -pub struct HuffBook { - codes: &'static [u32], - lens: &'static [u8], - max_len: u8, -} - -impl HuffBook { - pub const fn new(codes: &'static [u32], lens: &'static [u8]) -> HuffBook { - let mut max = 0u8; - let mut i = 0; - while i < lens.len() { - if lens[i] > max { - max = lens[i]; - } - i += 1; - } - HuffBook { - codes, - lens, - max_len: max, - } - } - - pub fn count(&self) -> usize { - self.codes.len() - } - - /// The `(codeword, bit-length)` for symbol index `i` — the encoder side. - pub fn code(&self, i: usize) -> (u32, u8) { - (self.codes[i], self.lens[i]) - } - - /// Decode the next codeword, returning its symbol index. - pub fn decode(&self, r: &mut BitReader) -> Result { - let mut code = 0u32; - for len in 1..=self.max_len { - code = (code << 1) | r.read_bit()?; - for i in 0..self.codes.len() { - if self.lens[i] == len && self.codes[i] == code { - return Ok(i as u16); - } - } - } - Err(Error::invalid("aac: invalid Huffman codeword")) - } - - /// Kraft sum Σ 2^-len — 1.0 for a complete code, slightly less if incomplete. - #[cfg(test)] - pub fn kraft_sum(&self) -> f64 { - self.lens.iter().map(|&l| 2f64.powi(-(l as i32))).sum() - } - - /// True if no codeword is a prefix of another. - #[cfg(test)] - pub fn is_prefix_free(&self) -> bool { - for a in 0..self.codes.len() { - for b in (a + 1)..self.codes.len() { - let (la, ca) = (self.lens[a], self.codes[a]); - let (lb, cb) = (self.lens[b], self.codes[b]); - let (short_l, short_c, long_l, long_c) = if la <= lb { - (la, ca, lb, cb) - } else { - (lb, cb, la, ca) - }; - if long_c >> (long_l - short_l) == short_c { - return false; - } - } - } - true - } -} - -#[cfg(test)] -mod tests { - use super::*; - - // A tiny prefix-free book: index 0→"0", 1→"10", 2→"110", 3→"111". - static TEST_CODES: &[u32] = &[0b0, 0b10, 0b110, 0b111]; - static TEST_LENS: &[u8] = &[1, 2, 3, 3]; - - #[test] - fn decodes_prefix_free_sequence() { - let book = HuffBook::new(TEST_CODES, TEST_LENS); - // Stream 0 10 110 111 0 → indices 0 1 2 3 0 - // bits: 0 10 110 111 0 → 0101 1011 10.. = 0x5B 0x80 - let mut r = BitReader::new(&[0x5B, 0x80]); - let got: Vec = (0..5).map(|_| book.decode(&mut r).unwrap()).collect(); - assert_eq!(got, vec![0, 1, 2, 3, 0]); - } - - #[test] - fn structural_helpers() { - let book = HuffBook::new(TEST_CODES, TEST_LENS); - assert!((book.kraft_sum() - 1.0).abs() < 1e-12); - assert!(book.is_prefix_free()); - } -} diff --git a/vendor/rusty_aac/src/ics.rs b/vendor/rusty_aac/src/ics.rs deleted file mode 100644 index f261d63..0000000 --- a/vendor/rusty_aac/src/ics.rs +++ /dev/null @@ -1,175 +0,0 @@ -//! `ics_info` — per-channel window/grouping configuration (ISO 14496-3 -//! §4.4.2.1) and the derived short-window grouping. - -#![allow(dead_code)] - -use crate::{Error, Result}; - -use crate::bits::BitReader; -use crate::swb::swb_offsets; - -/// AAC window sequence (transform block structure). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum WindowSequence { - OnlyLong, - LongStart, - EightShort, - LongStop, -} - -impl WindowSequence { - fn from_bits(v: u32) -> WindowSequence { - match v { - 0 => WindowSequence::OnlyLong, - 1 => WindowSequence::LongStart, - 2 => WindowSequence::EightShort, - _ => WindowSequence::LongStop, - } - } - - pub fn is_short(self) -> bool { - self == WindowSequence::EightShort - } - - /// The 2-bit window-sequence code (the encode side of `from_bits`). - pub fn to_bits(self) -> u32 { - match self { - WindowSequence::OnlyLong => 0, - WindowSequence::LongStart => 1, - WindowSequence::EightShort => 2, - WindowSequence::LongStop => 3, - } - } -} - -/// Parsed `ics_info` plus the derived grouping for this channel. -#[derive(Debug, Clone)] -pub struct IcsInfo { - pub window_sequence: WindowSequence, - /// Window shape for this block: false = sine, true = KBD. - pub window_shape_kbd: bool, - pub max_sfb: u8, - /// Number of transform windows (8 for EIGHT_SHORT, else 1). - pub num_windows: usize, - /// Number of window groups. - pub num_window_groups: usize, - /// Windows per group (`num_window_groups` entries summing to `num_windows`). - pub window_group_length: Vec, - /// Number of scalefactor bands per window for this block type. - pub num_swb: usize, -} - -/// Parse `ics_info` from the bitstream for sampling-frequency index `fs_index`. -pub fn parse_ics_info(r: &mut BitReader, fs_index: u8) -> Result { - let _ics_reserved = r.read_bit()?; - let window_sequence = WindowSequence::from_bits(r.read_bits(2)?); - let window_shape_kbd = r.read_bool()?; - - let (max_sfb, scale_factor_grouping) = if window_sequence.is_short() { - let max_sfb = r.read_bits(4)? as u8; - let sfg = r.read_bits(7)?; - (max_sfb, Some(sfg)) - } else { - let max_sfb = r.read_bits(6)? as u8; - let predictor_data_present = r.read_bool()?; - if predictor_data_present { - // AAC-LC has no prediction; a set bit means a non-LC stream. - return Err(Error::unsupported( - "aac: predictor_data_present (non-LC profile) not supported", - )); - } - (max_sfb, None) - }; - - let (num_windows, num_window_groups, window_group_length) = match scale_factor_grouping { - Some(sfg) => { - // Each of the 7 grouping bits (MSB first) ties window i+1 to the - // current group (1) or starts a new one (0). - let mut groups = vec![1u8]; - for i in 0..7 { - if (sfg >> (6 - i)) & 1 == 1 { - *groups.last_mut().unwrap() += 1; - } else { - groups.push(1); - } - } - (8, groups.len(), groups) - } - None => (1, 1, vec![1u8]), - }; - - let num_swb = swb_offsets(!window_sequence.is_short(), fs_index).len() - 1; - - Ok(IcsInfo { - window_sequence, - window_shape_kbd, - max_sfb, - num_windows, - num_window_groups, - window_group_length, - num_swb, - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_only_long() { - // ics_reserved(0) ws(00=OnlyLong) shape(0) max_sfb(49=110001) pred(0) - // bits: 0 00 0 110001 0 → 0000 1100 010. = 0x0C 0x40 - let mut r = BitReader::new(&[0x0C, 0x40]); - let info = parse_ics_info(&mut r, 4).unwrap(); - assert_eq!(info.window_sequence, WindowSequence::OnlyLong); - assert!(!info.window_shape_kbd); - assert_eq!(info.max_sfb, 49); - assert_eq!(info.num_windows, 1); - assert_eq!(info.num_window_groups, 1); - assert_eq!(info.window_group_length, vec![1]); - assert_eq!(info.num_swb, 49); // 44.1 kHz long - } - - #[test] - fn parses_eight_short_all_grouped() { - // ics_reserved(0) ws(10=EightShort) shape(1=KBD) max_sfb(13=1101) - // sfg(1111111 → one group of 8) - // bits: 0 10 1 1101 1111111 → 0101 1101 1111 111. = 0x5D 0xFE - let mut r = BitReader::new(&[0x5D, 0xFE]); - let info = parse_ics_info(&mut r, 3).unwrap(); - assert_eq!(info.window_sequence, WindowSequence::EightShort); - assert!(info.window_shape_kbd); - assert_eq!(info.max_sfb, 13); - assert_eq!(info.num_windows, 8); - assert_eq!(info.num_window_groups, 1); - assert_eq!(info.window_group_length, vec![8]); - assert_eq!(info.num_swb, 14); // 48 kHz short - } - - #[test] - fn parses_eight_short_split_groups() { - // sfg = 0b0101010 → bits decide grouping: produces several groups. - // ics_reserved(0) ws(10) shape(0) max_sfb(0000) sfg(0101010) - // bits: 0 10 0 0000 0101010 → 0100 0000 0101 0100 = 0x40 0x54 - let mut r = BitReader::new(&[0x40, 0x54]); - let info = parse_ics_info(&mut r, 3).unwrap(); - assert_eq!(info.num_windows, 8); - // 0,1,0,1,0,1,0 grouping bits → groups: [1,2,2,2,1] (sum 8). - assert_eq!( - info.window_group_length - .iter() - .map(|&x| x as usize) - .sum::(), - 8 - ); - assert_eq!(info.num_window_groups, info.window_group_length.len()); - } - - #[test] - fn rejects_prediction() { - // OnlyLong with predictor_data_present=1 → unsupported (non-LC). - // 0 00 0 000000 1 → 0000 0000 0010 0000 = 0x00 0x20 - let mut r = BitReader::new(&[0x00, 0x20]); - assert!(parse_ics_info(&mut r, 4).is_err()); - } -} diff --git a/vendor/rusty_aac/src/latm.rs b/vendor/rusty_aac/src/latm.rs deleted file mode 100644 index eabfb34..0000000 --- a/vendor/rusty_aac/src/latm.rs +++ /dev/null @@ -1,463 +0,0 @@ -//! **LATM / LOAS** — the low-overhead transport (ISO 14496-3 §1.7). -//! -//! ADTS carries AAC in `.aac` files; MP4 carries it in `esds`. Broadcast and -//! MPEG-TS carry it in **LOAS** (Low Overhead Audio Stream), whose payload is a -//! **LATM** (Low Overhead Audio Transport Multiplex) `AudioMuxElement`. Without -//! it, an AAC decoder cannot read a TS stream at all — which matters here because -//! this workspace ships `rff-format-ts`. -//! -//! The layering, outermost first: -//! -//! ```text -//! AudioSyncStream syncword 0x2B7 (11b) + audioMuxLengthBytes (13b) -//! AudioMuxElement muxConfigPresent = 1 (the LOAS case) -//! useSameStreamMux (1b) 0 -> a StreamMuxConfig follows -//! StreamMuxConfig audioMuxVersion, framing flags, AudioSpecificConfig -//! PayloadLengthInfo the AU length, as a chain of 8-bit values -//! PayloadMux the raw_data_block bytes -//! ``` -//! -//! # Scope -//! -//! This implements the profile broadcast actually uses and that every encoder -//! emits: `audioMuxVersion = 0`, `allStreamsSameTimeFraming = 1`, -//! `numSubFrames = 0`, `numProgram = 0`, `numLayer = 0`, `frameLengthType = 0`. -//! Anything else is rejected with a clear error rather than mis-parsed — the -//! same policy `decode` applies to `gain_control_data`. Multiple programs and -//! layers are a genuine gap, not something silently mishandled. - -use crate::bits::BitReader; -use crate::encode::BitWriter; -use crate::{AudioSpecificConfig, Error, Result}; - -/// The 11-bit LOAS sync pattern. -const LOAS_SYNC: u32 = 0x2B7; -/// `AudioSyncStream` header size in bytes (11-bit sync + 13-bit length = 24 bits). -pub const LOAS_HEADER_LEN: usize = 3; - -/// One parsed LOAS frame. -#[derive(Debug, Clone)] -pub struct LoasFrame { - /// Stream parameters from the embedded `AudioSpecificConfig`. - pub config: AudioSpecificConfig, - /// The raw access unit (a `raw_data_block`), ready for `decode::Decoder`. - pub au: Vec, - /// Total bytes consumed, so a caller can walk a stream. - pub frame_length: usize, -} - -/// Does `data` start with a LOAS `audioSyncStream` header? -pub fn is_loas(data: &[u8]) -> bool { - data.len() >= LOAS_HEADER_LEN - && data[0] == 0x56 - && (data[1] & 0xE0) == 0xE0 -} - -/// Byte offset of the next LOAS syncword, for resynchronising a damaged stream. -pub fn find_sync(data: &[u8]) -> Option { - (0..data.len().saturating_sub(LOAS_HEADER_LEN)).find(|&i| is_loas(&data[i..])) -} - -/// Parse an `AudioSpecificConfig` from a **bit position** (LATM embeds it -/// unaligned, so the byte-oriented `parse_audio_specific_config` cannot be used). -/// -/// Returns the config and the number of bits it occupied — the caller needs the -/// length because `StreamMuxConfig` records it for `audioMuxVersion == 1`. -fn read_asc(r: &mut BitReader) -> Result<(AudioSpecificConfig, usize)> { - let start = r.bits_left(); - let mut object_type = r.read_bits(5)? as u8; - if object_type == 31 { - object_type = 32 + r.read_bits(6)? as u8; - } - let sf_index = r.read_bits(4)? as u8; - let sample_rate = if sf_index == 0x0F { - r.read_bits(24)? - } else { - crate::sample_rate_for_index(sf_index) - }; - if sample_rate == 0 { - return Err(Error::invalid("latm: unknown sample rate index")); - } - let channels = r.read_bits(4)? as u16; - // GASpecificConfig for AAC-LC: three flags, all zero for the plain case. - let frame_length_flag = r.read_bool()?; - if frame_length_flag { - return Err(Error::unsupported("latm: 960-sample frames not supported")); - } - if r.read_bool()? { - return Err(Error::unsupported("latm: core-coder delay not supported")); - } - let extension_flag = r.read_bool()?; - if extension_flag { - return Err(Error::unsupported("latm: AAC extension flag not supported")); - } - Ok(( - AudioSpecificConfig { - object_type, - sample_rate, - channels, - }, - start - r.bits_left(), - )) -} - -/// Parse `StreamMuxConfig`, returning the embedded stream parameters. -fn read_stream_mux_config(r: &mut BitReader) -> Result { - let audio_mux_version = r.read_bool()?; - let audio_mux_version_a = if audio_mux_version { r.read_bool()? } else { false }; - if audio_mux_version_a { - return Err(Error::unsupported("latm: audioMuxVersionA not supported")); - } - if audio_mux_version { - // taraBufferFullness, an escaped value we do not consume correctly for - // any stream we would then decode — refuse rather than desynchronise. - return Err(Error::unsupported("latm: audioMuxVersion 1 not supported")); - } - if !r.read_bool()? { - return Err(Error::unsupported( - "latm: allStreamsSameTimeFraming = 0 not supported", - )); - } - let num_sub_frames = r.read_bits(6)?; - let num_program = r.read_bits(4)?; - let num_layer = r.read_bits(3)?; - if num_sub_frames != 0 || num_program != 0 || num_layer != 0 { - return Err(Error::unsupported( - "latm: multiple subframes/programs/layers not supported", - )); - } - let (cfg, _bits) = read_asc(r)?; - let frame_length_type = r.read_bits(3)?; - match frame_length_type { - 0 => { - let _latm_buffer_fullness = r.read_bits(8)?; - } - _ => { - return Err(Error::unsupported( - "latm: only frameLengthType 0 (variable, byte-counted) is supported", - )) - } - } - let other_data_present = r.read_bool()?; - if other_data_present { - // otherDataLenBits, escaped in 8-bit chunks. - let mut more = true; - while more { - let _ = r.read_bits(8)?; - more = r.read_bool()?; - } - } - if r.read_bool()? { - let _crc = r.read_bits(8)?; // crcCheckSum - } - Ok(cfg) -} - -/// Parse one LOAS frame starting at `data[0]`. -/// -/// `muxConfigPresent` is 1 by definition inside an `audioSyncStream`, so a -/// `StreamMuxConfig` is expected unless `useSameStreamMux` says to reuse the -/// previous one — which this function cannot do, since it is stateless. Callers -/// walking a stream should use [`LatmReader`], which carries that state. -pub fn parse_loas_frame(data: &[u8]) -> Result { - LatmReader::new().parse(data) -} - -/// A stateful LOAS reader. -/// -/// Real streams send the `StreamMuxConfig` on the first frame and then set -/// `useSameStreamMux = 1` for a long run of frames afterwards — that is the whole -/// point of "low overhead". A stateless parser therefore fails on the *majority* -/// of frames in any real capture, which is why this type exists. -#[derive(Debug, Default, Clone)] -pub struct LatmReader { - config: Option, -} - -impl LatmReader { - pub fn new() -> LatmReader { - LatmReader::default() - } - - /// The most recently seen stream configuration, if any. - pub fn config(&self) -> Option { - self.config - } - - /// Parse one LOAS frame, remembering its `StreamMuxConfig` for later frames. - pub fn parse(&mut self, data: &[u8]) -> Result { - if !is_loas(data) { - return Err(Error::invalid("latm: no audioSyncStream syncword")); - } - let mut r = BitReader::new(data); - let sync = r.read_bits(11)?; - debug_assert_eq!(sync, LOAS_SYNC); - let mux_len = r.read_bits(13)? as usize; - let frame_length = LOAS_HEADER_LEN + mux_len; - if data.len() < frame_length { - return Err(Error::Again); - } - - // AudioMuxElement(muxConfigPresent = 1) - let use_same = r.read_bool()?; - let cfg = if use_same { - self.config - .ok_or_else(|| Error::invalid("latm: useSameStreamMux before any config"))? - } else { - let c = read_stream_mux_config(&mut r)?; - self.config = Some(c); - c - }; - - // PayloadLengthInfo for frameLengthType 0: 8-bit values, 255 continues. - let mut au_len = 0usize; - loop { - let v = r.read_bits(8)? as usize; - au_len += v; - if v != 255 { - break; - } - } - - // PayloadMux — au_len bytes, still bit-aligned to the reader position. - let mut au = Vec::with_capacity(au_len); - for _ in 0..au_len { - au.push(r.read_bits(8)? as u8); - } - - Ok(LoasFrame { - config: cfg, - au, - frame_length, - }) - } -} - -/// Serialize one LOAS frame carrying `au`, with a full `StreamMuxConfig`. -/// -/// Every frame gets its own config (`useSameStreamMux = 0`). That costs ~3 bytes -/// per frame versus the minimum, and buys random access: a receiver can start -/// decoding at any frame, which is what broadcast actually needs. -pub fn write_loas_frame(cfg: &AudioSpecificConfig, au: &[u8]) -> Vec { - let mut w = BitWriter::new(); - // --- AudioMuxElement(muxConfigPresent = 1) --- - w.write_bool(false); // useSameStreamMux = 0 -> StreamMuxConfig follows - - // --- StreamMuxConfig --- - w.write_bool(false); // audioMuxVersion = 0 - w.write_bool(true); // allStreamsSameTimeFraming = 1 - w.write(0, 6); // numSubFrames = 0 - w.write(0, 4); // numProgram = 0 - w.write(0, 3); // numLayer = 0 - - // --- AudioSpecificConfig, bit-packed (NOT byte aligned here) --- - if cfg.object_type >= 31 { - w.write(31, 5); - w.write((cfg.object_type - 32) as u32, 6); - } else { - w.write(cfg.object_type as u32, 5); - } - match crate::sf_index_for_rate(cfg.sample_rate) { - Some(i) => w.write(i as u32, 4), - None => { - w.write(0x0F, 4); - w.write(cfg.sample_rate, 24); - } - } - w.write(cfg.channels as u32, 4); - // GASpecificConfig: frameLengthFlag, dependsOnCoreCoder, extensionFlag. - w.write(0, 3); - - w.write(0, 3); // frameLengthType = 0 - w.write(0xFF, 8); // latmBufferFullness = 255 (VBR / "don't care") - w.write_bool(false); // otherDataPresent - w.write_bool(false); // crcCheckPresent - - // --- PayloadLengthInfo: 255-escaped byte count --- - let mut remaining = au.len(); - while remaining >= 255 { - w.write(255, 8); - remaining -= 255; - } - w.write(remaining as u32, 8); - - // --- PayloadMux --- - for &b in au { - w.write(b as u32, 8); - } - - let body = w.into_bytes(); - - // --- audioSyncStream wrapper --- - let mut out = Vec::with_capacity(LOAS_HEADER_LEN + body.len()); - let hdr = (LOAS_SYNC << 13) | (body.len() as u32 & 0x1FFF); - out.push((hdr >> 16) as u8); - out.push((hdr >> 8) as u8); - out.push(hdr as u8); - out.extend_from_slice(&body); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - fn cfg() -> AudioSpecificConfig { - AudioSpecificConfig { - object_type: 2, - sample_rate: 44100, - channels: 2, - } - } - - /// Writer -> parser round-trip, the basic contract. - #[test] - fn loas_round_trips() { - let au: Vec = (0..200u32).map(|i| (i * 7 + 3) as u8).collect(); - let frame = write_loas_frame(&cfg(), &au); - assert!(is_loas(&frame), "writer must emit a valid syncword"); - let got = parse_loas_frame(&frame).expect("parse"); - assert_eq!(got.au, au, "payload must survive"); - assert_eq!(got.config.sample_rate, 44100); - assert_eq!(got.config.channels, 2); - assert_eq!(got.config.object_type, 2); - assert_eq!(got.frame_length, frame.len()); - } - - /// The 255-escape in PayloadLengthInfo must handle lengths either side of the - /// boundary — an off-by-one there truncates or over-reads every large frame. - #[test] - fn payload_length_escape_is_exact() { - for len in [0usize, 1, 254, 255, 256, 509, 510, 511, 1000] { - let au: Vec = (0..len).map(|i| (i % 251) as u8).collect(); - let frame = write_loas_frame(&cfg(), &au); - let got = parse_loas_frame(&frame).unwrap_or_else(|e| panic!("len {len}: {e}")); - assert_eq!(got.au.len(), len, "length {len} mis-coded"); - assert_eq!(got.au, au, "length {len} payload corrupted"); - } - } - - /// A real stream sets `useSameStreamMux` after the first frame; a stateless - /// parser fails on those, a `LatmReader` must not. - #[test] - fn reader_carries_config_across_frames() { - let au = vec![0xAAu8; 40]; - let first = write_loas_frame(&cfg(), &au); - - // Hand-build a second frame with useSameStreamMux = 1. - let mut w = BitWriter::new(); - w.write_bool(true); // useSameStreamMux - w.write(au.len() as u32, 8); // PayloadLengthInfo (< 255) - for &b in &au { - w.write(b as u32, 8); - } - let body = w.into_bytes(); - let hdr = (LOAS_SYNC << 13) | (body.len() as u32 & 0x1FFF); - let mut second = vec![(hdr >> 16) as u8, (hdr >> 8) as u8, hdr as u8]; - second.extend_from_slice(&body); - - let mut rd = LatmReader::new(); - let a = rd.parse(&first).expect("first frame"); - assert_eq!(a.au, au); - let b = rd.parse(&second).expect("second frame must reuse the config"); - assert_eq!(b.au, au); - assert_eq!(b.config.sample_rate, 44100); - - // A fresh reader must REFUSE the config-less frame rather than guess. - assert!(LatmReader::new().parse(&second).is_err()); - } - - /// Sync detection and resynchronisation. - #[test] - fn finds_sync_after_garbage() { - let au = vec![0x5Au8; 32]; - let frame = write_loas_frame(&cfg(), &au); - let mut stream = vec![0x00, 0xFF, 0x12, 0x34]; - let offset = stream.len(); - stream.extend_from_slice(&frame); - assert_eq!(find_sync(&stream), Some(offset)); - let got = parse_loas_frame(&stream[offset..]).unwrap(); - assert_eq!(got.au, au); - } - - /// A truncated frame must ask for more data, not mis-parse. - #[test] - fn truncated_frame_returns_again() { - let au = vec![0x11u8; 300]; - let frame = write_loas_frame(&cfg(), &au); - let cut = &frame[..frame.len() - 10]; - assert!(matches!(parse_loas_frame(cut), Err(Error::Again))); - } - - /// Unsupported mux shapes are refused with a clear error, never mis-decoded. - #[test] - fn unsupported_mux_shapes_are_refused() { - // numLayer != 0 - let mut w = BitWriter::new(); - w.write_bool(false); // useSameStreamMux - w.write_bool(false); // audioMuxVersion - w.write_bool(true); // allStreamsSameTimeFraming - w.write(0, 6); // numSubFrames - w.write(0, 4); // numProgram - w.write(1, 3); // numLayer = 1 <-- unsupported - let body = w.into_bytes(); - let hdr = (LOAS_SYNC << 13) | (body.len() as u32 & 0x1FFF); - let mut frame = vec![(hdr >> 16) as u8, (hdr >> 8) as u8, hdr as u8]; - frame.extend_from_slice(&body); - assert!(parse_loas_frame(&frame).is_err()); - } - - /// **End to end**: real AAC through LOAS and back out to PCM. The unit tests - /// above prove the framing; this proves the framing carries a decodable - /// stream, which is the only claim that matters for MPEG-TS carriage. - #[test] - fn real_aac_survives_loas_carriage() { - use crate::{AacEncoder, AacEncoderConfig}; - let sr = 44100u32; - let n = 10 * 1024; - let pcm: Vec = (0..n * 2) - .map(|i| { - let t = (i / 2) as f32 / sr as f32; - 0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin() - }) - .collect(); - - let mut enc = AacEncoder::new(AacEncoderConfig::default()); - enc.push_pcm(&pcm, 2, sr).unwrap(); - enc.finish(); - - let cfg = AudioSpecificConfig { - object_type: 2, - sample_rate: sr, - channels: 2, - }; - - // Encode -> LOAS - let mut stream = Vec::new(); - let mut n_frames = 0usize; - while let Ok(p) = enc.next_packet() { - stream.extend_from_slice(&write_loas_frame(&cfg, &p.data)); - n_frames += 1; - } - assert!(n_frames > 5, "need several frames to exercise the reader"); - - // LOAS -> decode - let mut rd = LatmReader::new(); - // The transport supplies the config out of band, exactly as an MPEG-TS - // demuxer would hand it to the decoder. - let mut dec = crate::AacDecoder::with_config(cfg); - let mut pos = 0usize; - let mut decoded = 0usize; - let mut parsed = 0usize; - while pos + LOAS_HEADER_LEN < stream.len() { - let f = rd.parse(&stream[pos..]).expect("LOAS frame"); - assert_eq!(f.config, cfg, "config must survive the transport"); - let audio = dec.decode(&f.au, None).expect("AU must decode"); - decoded += audio.frames(); - pos += f.frame_length; - parsed += 1; - } - assert_eq!(parsed, n_frames, "every frame must be recovered"); - assert!(decoded >= n, "decoded {decoded} of {n} samples"); - } -} diff --git a/vendor/rusty_aac/src/lib.rs b/vendor/rusty_aac/src/lib.rs deleted file mode 100644 index 24caff4..0000000 --- a/vendor/rusty_aac/src/lib.rs +++ /dev/null @@ -1,413 +0,0 @@ -//! Pure-Rust **AAC-LC decoder + encoder**, no C and no FFI. -//! -//! Extracted from (and the engine of) the -//! [`remade_ffmpeg_rs`](https://github.com/Remade-With-Rust/remade_ffmpeg_rs) -//! project. The crate has **zero dependencies**. -//! -//! - **Decoder**: complete AAC-LC — long/short/transition windows with grouped -//! scalefactors, all spectral Huffman codebooks, M/S and intensity stereo, -//! PNS, TNS — verified against FFmpeg (bit-exact on deterministic features). -//! Entry point: [`AacDecoder`] (handles ADTS framing and raw MP4 access -//! units alike) or the lower-level [`decode::Decoder`]. -//! - **Encoder**: psychoacoustic Bark-scale masking model, two-phase bitrate -//! rate loop, transient-driven block switching, per-SFB M/S stereo, and a -//! frame-parallel `encode_stream` (~450× realtime). Entry point: -//! [`AacEncoder`] with [`AacEncoderConfig`]. -//! - **Framing & config**: [`AudioSpecificConfig`] (the MP4 `esds` payload) -//! and [`AdtsHeader`] (the `.aac` elementary-stream header) parsers plus -//! their serializers ([`write_audio_specific_config`], [`write_adts_header`], -//! [`audio_specific_config_bytes`]). -//! -//! The `simd` feature (default) enables runtime-detected AVX2 kernels; -//! `--no-default-features` gives a 100%-safe scalar build. `simd-avx512` adds -//! an opt-in AVX-512 tier. - -mod bits; -mod codebook; -pub mod decode; -mod dsp; -pub mod encode; -mod error; -mod huffman; -mod ics; -/// LATM/LOAS transport (ISO 14496-3 §1.7) — the MPEG-TS / broadcast carriage -/// format, alongside ADTS (`.aac`) and MP4 `esds`. -pub mod latm; -/// The quality lab (feature `lab`): deterministic corpus, the NMR metric, and the -/// bitrate-ladder runner. This is the verdict instrument for the Great Gate -/// campaign — see `docs/codec-aac-great-gate.md`. -#[cfg(feature = "lab")] -pub mod lab; -/// HE-AAC (SBR / Parametric Stereo) signalling and capability reporting — the -/// broadcast and low-bitrate-streaming configuration. See the module docs for -/// exactly which parts are implemented. -pub mod sbr; -mod swb; -mod tables; - -pub use bits::BitReader; -pub use encode::{ - audio_specific_config_bytes, write_adts_header, write_audio_specific_config, AacEncoder, - AacEncoderConfig, EncodedPacket, WindowShape, -}; -pub use error::{Error, Result}; - -/// AAC sample-rate table, indexed by `samplingFrequencyIndex` (ISO 14496-3). -pub const SAMPLE_RATES: [u32; 13] = [ - 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350, -]; - -/// Map a 4-bit sampling-frequency index to a rate (0 for the reserved/escape -/// values 13-15, which require an explicit 24-bit rate). -pub fn sample_rate_for_index(idx: u8) -> u32 { - SAMPLE_RATES.get(idx as usize).copied().unwrap_or(0) -} - -/// Map a sampling rate to its 4-bit index, or None if non-standard (the encoder -/// then uses the 0x0F + explicit-24-bit-rate escape). -pub fn sf_index_for_rate(rate: u32) -> Option { - SAMPLE_RATES - .iter() - .position(|&r| r == rate) - .map(|i| i as u8) -} - -// --------------------------------------------------------------------------- -// AudioSpecificConfig — the MP4 `esds` DecoderSpecificInfo (raw AAC config). -// --------------------------------------------------------------------------- - -/// Parsed `AudioSpecificConfig` (ISO 14496-3 §1.6.2.1). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct AudioSpecificConfig { - /// Audio Object Type (2 = AAC-LC, the only one we target). - pub object_type: u8, - pub sample_rate: u32, - /// Channel configuration (1 = mono, 2 = stereo, …). - pub channels: u16, -} - -/// Parse an `AudioSpecificConfig` from its raw bytes (the `esds`/`stsd` config). -pub fn parse_audio_specific_config(data: &[u8]) -> Result { - let mut r = BitReader::new(data); - let object_type = read_object_type(&mut r)?; - let sf_index = r.read_bits(4)? as u8; - let sample_rate = if sf_index == 0x0F { - r.read_bits(24)? - } else { - sample_rate_for_index(sf_index) - }; - let channels = r.read_bits(4)? as u16; - if sample_rate == 0 { - return Err(Error::invalid("aac: invalid sampling frequency in config")); - } - Ok(AudioSpecificConfig { - object_type, - sample_rate, - channels, - }) -} - -/// Read the (possibly escaped) 5-bit Audio Object Type. -fn read_object_type(r: &mut BitReader) -> Result { - let ot = r.read_bits(5)? as u8; - if ot == 31 { - Ok((32 + r.read_bits(6)?) as u8) - } else { - Ok(ot) - } -} - -// --------------------------------------------------------------------------- -// ADTS — the `.aac` elementary-stream frame header. -// --------------------------------------------------------------------------- - -/// A parsed ADTS frame header (ISO 14496-3 §1.A.2.2.1). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct AdtsHeader { - /// Audio Object Type (profile + 1). - pub object_type: u8, - pub sample_rate: u32, - pub channels: u16, - /// Total frame length including this header. - pub frame_length: usize, - /// Header size in bytes (7 without CRC, 9 with). - pub header_len: usize, -} - -/// True if `data` begins with an ADTS syncword (0xFFF, layer 00). -pub fn is_adts(data: &[u8]) -> bool { - data.len() >= 2 && data[0] == 0xFF && (data[1] & 0xF6) == 0xF0 -} - -/// Parse an ADTS header from the start of `data`. -pub fn parse_adts(data: &[u8]) -> Result { - if !is_adts(data) || data.len() < 7 { - return Err(Error::invalid("aac: not an ADTS frame")); - } - let mut r = BitReader::new(data); - r.skip(12)?; // syncword - r.skip(1)?; // MPEG version - r.skip(2)?; // layer (00) - let protection_absent = r.read_bool()?; - let profile = r.read_bits(2)? as u8; // object_type - 1 - let sf_index = r.read_bits(4)? as u8; - r.skip(1)?; // private - let channel_config = r.read_bits(3)? as u16; - r.skip(4)?; // original/home/copyright id+start - let frame_length = r.read_bits(13)? as usize; - // remaining: buffer_fullness(11) + num_raw_data_blocks(2) — not needed here. - let sample_rate = sample_rate_for_index(sf_index); - if sample_rate == 0 || frame_length < 7 { - return Err(Error::invalid("aac: invalid ADTS header")); - } - Ok(AdtsHeader { - object_type: profile + 1, - sample_rate, - channels: channel_config, - frame_length, - header_len: if protection_absent { 7 } else { 9 }, - }) -} - -// --------------------------------------------------------------------------- -// Decoded PCM — the decoder's native output. -// --------------------------------------------------------------------------- - -/// One decoded frame of PCM: interleaved `f32` samples in [-1, 1]. -#[derive(Debug, Clone)] -pub struct DecodedAudio { - pub sample_rate: u32, - pub channels: u16, - /// Interleaved samples (`samples.len() = frames × channels`). - pub samples: Vec, - /// The presentation timestamp handed to [`AacDecoder::decode`], if any. - pub pts: Option, -} - -impl DecodedAudio { - /// Number of PCM frames (samples per channel). - pub fn frames(&self) -> usize { - self.samples.len() / self.channels.max(1) as usize - } -} - -// --------------------------------------------------------------------------- -// Decoder — stream-level: ADTS stripping + lazy core init. -// --------------------------------------------------------------------------- - -/// Stream-level AAC-LC decoder: accepts either ADTS frames (`.aac` elementary -/// streams — the config is read from the header) or bare raw access units -/// (MP4 — configure via [`AacDecoder::with_config`] from the `esds` -/// [`AudioSpecificConfig`]). -#[derive(Default)] -pub struct AacDecoder { - config: Option, - decoder: Option, - /// HE-AAC parameters, when built via [`AacDecoder::with_config_bytes`]. - sbr: Option, -} - -impl AacDecoder { - /// A decoder that learns its parameters from the stream (ADTS headers). - pub fn new() -> AacDecoder { - AacDecoder::default() - } - - /// A decoder pre-configured from an out-of-band [`AudioSpecificConfig`] - /// (the MP4 `esds` payload) — required for bare raw access units. - pub fn with_config(cfg: AudioSpecificConfig) -> AacDecoder { - AacDecoder { - config: Some(cfg), - decoder: None, - sbr: None, - } - } - - /// A decoder configured from the **raw** `AudioSpecificConfig` bytes. - /// - /// Prefer this over [`with_config`](Self::with_config) whenever the raw bytes - /// are available (they always are — `esds`, `StreamMuxConfig`), because HE-AAC - /// signalling lives in fields the plain [`AudioSpecificConfig`] does not - /// carry. An HE-AAC stream configured through the plain path reports its - /// **core** rate, and a player that believes it plays the audio at half - /// speed. - pub fn with_config_bytes(data: &[u8]) -> Result { - let sbr = sbr::parse_sbr_config(data)?; - let mut cfg = parse_audio_specific_config(data)?; - // The core decodes at the core rate whatever the config's first field - // said; for hierarchical HE-AAC that field was the extension rate. - if sbr.sbr_present { - cfg.sample_rate = sbr.core_sample_rate; - cfg.object_type = sbr.core_object_type; - } - Ok(AacDecoder { - config: Some(cfg), - decoder: None, - sbr: Some(sbr), - }) - } - - /// HE-AAC parameters, when the decoder was built from raw config bytes. - pub fn sbr_config(&self) -> Option { - self.sbr - } - - /// How much of this stream can actually be reconstructed. - /// - /// [`SbrSupport::CoreOnly`](sbr::SbrSupport::CoreOnly) means the output is - /// real audio, correct in rate and channels, but band-limited to the core's - /// Nyquist because the SBR high band is not reconstructed. - pub fn sbr_support(&self) -> sbr::SbrSupport { - match self.sbr { - Some(s) => s.support(), - None => sbr::SbrSupport::NotPresent, - } - } - - /// The stream's **output** sample rate. - /// - /// For HE-AAC this is twice the rate the `raw_data_block`s are coded at. - /// Returns `None` until the configuration is known. - pub fn output_sample_rate(&self) -> Option { - match self.sbr { - Some(s) if s.sbr_present => Some(s.output_sample_rate), - _ => self.config.map(|c| c.sample_rate), - } - } - - /// Lazily build the stateful decoder once rate/channels are known. - fn ensure_decoder(&mut self) -> Result<&mut decode::Decoder> { - if self.decoder.is_none() { - let cfg = self - .config - .ok_or_else(|| Error::invalid("aac: stream parameters unknown"))?; - self.decoder = Some(decode::Decoder::new(cfg.sample_rate)); - } - Ok(self.decoder.as_mut().unwrap()) - } - - /// Decode one packet (an ADTS frame or a bare raw access unit) into PCM. - /// - /// ADTS framing, if present, is stripped (and configures the decoder on - /// first use). Returns [`Error::Again`] for an empty packet (nothing to - /// decode — feed the next one). - pub fn decode(&mut self, packet: &[u8], pts: Option) -> Result { - // Strip ADTS framing if present; MP4 delivers bare access units. - let mut data = packet; - if is_adts(data) { - let header = parse_adts(data)?; - if self.config.is_none() { - self.config = Some(AudioSpecificConfig { - object_type: header.object_type, - sample_rate: header.sample_rate, - channels: header.channels, - }); - } - data = data - .get(header.header_len..header.frame_length.min(data.len())) - .unwrap_or(&[]); - } - if data.is_empty() { - return Err(Error::Again); - } - self.ensure_decoder()?.decode(data, pts) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn asc_stereo_44100_aac_lc() { - // object_type=2 (00010), sf_index=4 (0100)=44100, channels=2 (0010). - // 00010 0100 0010 → 0001 0010 0001 0000 = 0x12 0x10 (trailing pad). - let cfg = parse_audio_specific_config(&[0x12, 0x10]).unwrap(); - assert_eq!(cfg.object_type, 2); - assert_eq!(cfg.sample_rate, 44_100); - assert_eq!(cfg.channels, 2); - } - - #[test] - fn asc_mono_48000() { - // object_type=2 (00010), sf_index=3 (0011)=48000, channels=1 (0001). - // 00010 0011 0001 → 0001 0001 1000 1... = 0x11 0x88. - let cfg = parse_audio_specific_config(&[0x11, 0x88]).unwrap(); - assert_eq!(cfg.sample_rate, 48_000); - assert_eq!(cfg.channels, 1); - } - - #[test] - fn adts_header_parses() { - // 7-byte ADTS header (no CRC): sync 0xFFF, MPEG-4, layer 0, - // protection_absent=1, profile 1 (AAC-LC), sf_index 4 (44100), - // channel_config 2, frame_length 100. Layout verified bit-by-bit. - let h = [0xFFu8, 0xF1, 0x50, 0x80, 0x0C, 0x9F, 0xFC]; - let hdr = parse_adts(&h).unwrap(); - assert_eq!(hdr.object_type, 2); // profile 1 + 1 - assert_eq!(hdr.sample_rate, 44_100); - assert_eq!(hdr.channels, 2); - assert_eq!(hdr.frame_length, 100); - assert_eq!(hdr.header_len, 7); - } - - #[test] - fn is_adts_detects_syncword() { - assert!(is_adts(&[0xFF, 0xF1, 0x00])); - assert!(is_adts(&[0xFF, 0xF0, 0x00])); - assert!(!is_adts(&[0xFF, 0x00])); - assert!(!is_adts(&[0x00, 0xF1])); - } - - #[test] - fn sample_rate_table() { - assert_eq!(sample_rate_for_index(3), 48_000); - assert_eq!(sample_rate_for_index(4), 44_100); - assert_eq!(sample_rate_for_index(8), 16_000); - assert_eq!(sample_rate_for_index(15), 0); // escape value - } - - /// The stream-level decoder learns its config from ADTS and decodes to - /// interleaved PCM (encoder round-trip; the full-pipeline gates live in - /// `encode`'s tests). - #[test] - fn adts_stream_decodes_via_stream_decoder() { - let sr = 44100u32; - let n = 4096usize; - let pcm: Vec = (0..n) - .map(|i| { - ((i as f64 * 2.0 * std::f64::consts::PI * 440.0 / sr as f64).sin() * 0.5) as f32 - }) - .collect(); - let mut enc = AacEncoder::new(AacEncoderConfig::default()); - enc.push_pcm(&pcm, 1, sr).unwrap(); - enc.finish(); - let mut adts = Vec::new(); - while let Ok(p) = enc.next_packet() { - let hdr = AdtsHeader { - object_type: 2, - sample_rate: sr, - channels: 1, - frame_length: 7 + p.data.len(), - header_len: 7, - }; - adts.extend_from_slice(&write_adts_header(&hdr)); - adts.extend_from_slice(&p.data); - } - - let mut dec = AacDecoder::new(); - let mut decoded = 0usize; - let mut pos = 0usize; - while pos + 7 <= adts.len() { - let hdr = parse_adts(&adts[pos..]).unwrap(); - let out = dec - .decode(&adts[pos..pos + hdr.frame_length], None) - .unwrap(); - assert_eq!(out.sample_rate, sr); - assert_eq!(out.channels, 1); - decoded += out.frames(); - pos += hdr.frame_length; - } - assert!(decoded >= n, "decoded fewer samples than encoded"); - } -} diff --git a/vendor/rusty_aac/src/sbr.rs b/vendor/rusty_aac/src/sbr.rs deleted file mode 100644 index 65258d5..0000000 --- a/vendor/rusty_aac/src/sbr.rs +++ /dev/null @@ -1,405 +0,0 @@ -//! **HE-AAC (SBR / PS)** — signalling, detection, and honest capability -//! reporting. -//! -//! HE-AAC v1 wraps an AAC-LC core with **SBR** (Spectral Band Replication): the -//! core codes the lower half of the spectrum at half the output rate, and SBR -//! reconstructs the top half from it plus a small parameter stream. HE-AAC v2 -//! adds **PS** (Parametric Stereo), coding a mono core plus stereo parameters. -//! -//! This is what broadcast and low-bitrate streaming actually use, so a decoder -//! that mishandles it mishandles the majority of real AAC in the wild. -//! -//! # What is implemented here, and what is not -//! -//! **Implemented, exactly:** the signalling. Both forms — *explicit hierarchical* -//! (`audioObjectType` 5 or 29) and *explicit backward-compatible* (the `0x2B7` -//! sync extension after the `GASpecificConfig`) — plus detection of SBR payload -//! in the `fill_element`, and the **output sample rate**, which for HE-AAC is -//! twice the core rate. -//! -//! **NOT implemented:** the SBR reconstruction itself. See [`SbrSupport`]. The -//! blocker is not design effort — it is that the tool is defined by large -//! normative tables (the 640-tap QMF prototype filter, ISO/IEC 14496-3 -//! Table 4.A.87, and the SBR envelope/noise Huffman codebooks). Those must be -//! transcribed from the specification or a reference implementation. Writing -//! *approximations* of them would produce a decoder that is subtly wrong -//! everywhere while appearing to work, which is strictly worse than not having -//! it — the same reason `decode` refuses `gain_control_data` rather than -//! guessing at it. -//! -//! # Why the signalling alone is worth having -//! -//! Without it an HE-AAC stream is not merely "missing its high band" — it is -//! **silently played at the wrong speed**. The config announces a 24 kHz core for -//! 48 kHz output; a decoder that reports 24 kHz hands the player half-rate audio. -//! With this module the core decodes correctly, the caller learns the true output -//! rate, and [`SbrSupport`] says plainly that the high band is absent instead of -//! pretending otherwise. - -use crate::bits::BitReader; -use crate::{Error, Result}; - -/// `audioObjectType` values that name an SBR-bearing configuration. -pub const AOT_SBR: u8 = 5; -/// AAC-LC — the core object type SBR wraps. -pub const AOT_AAC_LC: u8 = 2; -/// HE-AAC v2 (SBR + Parametric Stereo). -pub const AOT_PS: u8 = 29; -/// ER-BSAC, the one object type that carries `extensionChannelConfiguration`. -const AOT_ER_BSAC: u8 = 22; - -/// `syncExtensionType` marking backward-compatible SBR signalling. -const SYNC_EXT_SBR: u32 = 0x2B7; -/// `syncExtensionType` marking backward-compatible PS signalling. -const SYNC_EXT_PS: u32 = 0x548; - -/// `extension_type` values inside a `fill_element` payload. -const EXT_SBR_DATA: u32 = 13; -const EXT_SBR_DATA_CRC: u32 = 14; - -/// How much of an SBR stream this build can actually reconstruct. -/// -/// Returned rather than inferred so callers never have to guess, and so the -/// limitation is visible at the API surface instead of buried in a doc comment. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SbrSupport { - /// No SBR in this stream; plain AAC-LC decoding is complete and exact. - NotPresent, - /// SBR is present. The **core is decoded correctly** and the output sample - /// rate is reported correctly, but the replicated high band is not - /// reconstructed — the result is band-limited to the core's Nyquist. - /// - /// This is the standard "core-only" fallback, and it is audio rather than - /// silence or an error. It is not conformant HE-AAC decoding. - CoreOnly, -} - -/// HE-AAC parameters recovered from an `AudioSpecificConfig`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct SbrConfig { - /// SBR is signalled in the config. - pub sbr_present: bool, - /// Parametric Stereo is signalled (HE-AAC v2). - pub ps_present: bool, - /// The **core** AAC sample rate — what the `raw_data_block`s are coded at. - pub core_sample_rate: u32, - /// The **output** sample rate after SBR, normally `2 x core_sample_rate`. - pub output_sample_rate: u32, - /// The core object type beneath the extension (2 for HE-AAC over AAC-LC). - pub core_object_type: u8, -} - -impl SbrConfig { - /// What this build can do with the stream. - pub fn support(&self) -> SbrSupport { - if self.sbr_present { - SbrSupport::CoreOnly - } else { - SbrSupport::NotPresent - } - } -} - -/// Read a (possibly escaped) 5-bit `audioObjectType`. -fn read_aot(r: &mut BitReader) -> Result { - let ot = r.read_bits(5)? as u8; - if ot == 31 { - Ok((32 + r.read_bits(6)?) as u8) - } else { - Ok(ot) - } -} - -/// Read a `samplingFrequencyIndex`, honouring the 0x0F escape. -fn read_sampling_frequency(r: &mut BitReader) -> Result { - let idx = r.read_bits(4)? as u8; - let rate = if idx == 0x0F { - r.read_bits(24)? - } else { - crate::sample_rate_for_index(idx) - }; - if rate == 0 { - return Err(Error::invalid("sbr: reserved sampling frequency index")); - } - Ok(rate) -} - -/// Parse an `AudioSpecificConfig` for HE-AAC signalling. -/// -/// Handles both forms the standard defines, because real streams use both: -/// -/// * **Explicit hierarchical** — `audioObjectType` is 5 (SBR) or 29 (PS), and the -/// extension rate and true core object type follow immediately. A legacy AAC-LC -/// decoder cannot read these at all. -/// * **Explicit backward-compatible** — `audioObjectType` is 2 (AAC-LC), and a -/// `0x2B7` sync extension *after* the `GASpecificConfig` announces SBR. Legacy -/// decoders skip the extension and decode the core, which is precisely the -/// point. -/// -/// A stream with neither yields `sbr_present = false`. -pub fn parse_sbr_config(data: &[u8]) -> Result { - let mut r = BitReader::new(data); - let mut aot = read_aot(&mut r)?; - let core_rate_first = read_sampling_frequency(&mut r)?; - let _channels = r.read_bits(4)?; - - let mut cfg = SbrConfig { - core_sample_rate: core_rate_first, - output_sample_rate: core_rate_first, - core_object_type: aot, - ..Default::default() - }; - - let hierarchical = aot == AOT_SBR || aot == AOT_PS; - if hierarchical { - cfg.sbr_present = true; - cfg.ps_present = aot == AOT_PS; - // In this form the rate read above is the EXTENSION (output) rate, and - // the core rate follows the inner object type. Getting these the wrong - // way round is the classic half-speed/double-speed HE-AAC bug. - cfg.output_sample_rate = core_rate_first; - aot = read_aot(&mut r)?; - cfg.core_object_type = aot; - if aot == AOT_ER_BSAC { - let _ext_channels = r.read_bits(4)?; - } - // The core rate is not restated; for every real HE-AAC stream it is half - // the extension rate. - cfg.core_sample_rate = core_rate_first / 2; - } - - // GASpecificConfig (AAC-LC): three flags. - if aot == AOT_AAC_LC { - let frame_length_flag = r.read_bool()?; - if frame_length_flag { - return Err(Error::unsupported("sbr: 960-sample frames not supported")); - } - if r.read_bool()? { - return Err(Error::unsupported("sbr: core-coder delay not supported")); - } - let _extension_flag = r.read_bool()?; - } - - // Backward-compatible signalling: only meaningful when the hierarchical form - // was NOT used. - if !hierarchical && r.bits_left() >= 16 { - let sync = r.read_bits(11)?; - if sync == SYNC_EXT_SBR { - let ext_aot = read_aot(&mut r)?; - if ext_aot == AOT_SBR { - let sbr_present = r.read_bool()?; - if sbr_present { - cfg.sbr_present = true; - cfg.output_sample_rate = read_sampling_frequency(&mut r)?; - if r.bits_left() >= 12 { - let sync2 = r.read_bits(11)?; - if sync2 == SYNC_EXT_PS { - cfg.ps_present = r.read_bool()?; - } - } - } - } - } - } - - // A stream signalling SBR but no explicit output rate implies doubling. - if cfg.sbr_present && cfg.output_sample_rate == cfg.core_sample_rate { - cfg.output_sample_rate = cfg.core_sample_rate * 2; - } - Ok(cfg) -} - -/// Does this `fill_element` payload carry SBR data? -/// -/// `payload` is the fill payload **after** the count field, and its first 4 bits -/// are the `extension_type`. Used for *implicit* SBR signalling, where nothing in -/// the config says SBR but the fill elements carry it anyway — a shape MPEG-TS -/// broadcast genuinely produces. -pub fn fil_payload_is_sbr(payload: &[u8]) -> bool { - if payload.is_empty() { - return false; - } - let ext = (payload[0] >> 4) as u32; - ext == EXT_SBR_DATA || ext == EXT_SBR_DATA_CRC -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::encode::BitWriter; - - /// Plain AAC-LC: no SBR, rates equal. - #[test] - fn plain_aac_lc_has_no_sbr() { - // AOT 2, sfIndex 4 (44100), 2 channels, GASpecificConfig zeros. - let cfg = crate::audio_specific_config_bytes(44100, 2); - let s = parse_sbr_config(&cfg).unwrap(); - assert!(!s.sbr_present); - assert!(!s.ps_present); - assert_eq!(s.core_sample_rate, 44100); - assert_eq!(s.output_sample_rate, 44100); - assert_eq!(s.support(), SbrSupport::NotPresent); - } - - /// **Explicit hierarchical HE-AAC v1.** AOT 5, extension rate 44100, core - /// AOT 2 -> core runs at 22050. This is the case that silently plays at half - /// speed if the two rates are swapped. - #[test] - fn explicit_hierarchical_he_aac_v1() { - let mut w = BitWriter::new(); - w.write(AOT_SBR as u32, 5); - w.write(4, 4); // extension sfIndex = 44100 - w.write(2, 4); // channels - w.write(AOT_AAC_LC as u32, 5); // core object type - w.write(0, 3); // GASpecificConfig - let bytes = w.into_bytes(); - - let s = parse_sbr_config(&bytes).unwrap(); - assert!(s.sbr_present, "AOT 5 must signal SBR"); - assert!(!s.ps_present); - assert_eq!(s.output_sample_rate, 44100, "extension rate is the OUTPUT rate"); - assert_eq!(s.core_sample_rate, 22050, "core runs at half"); - assert_eq!(s.core_object_type, AOT_AAC_LC); - assert_eq!(s.support(), SbrSupport::CoreOnly); - } - - /// **Explicit hierarchical HE-AAC v2** — AOT 29 also implies PS. - #[test] - fn explicit_hierarchical_he_aac_v2() { - let mut w = BitWriter::new(); - w.write(AOT_PS as u32, 5); - w.write(3, 4); // 48000 output - w.write(2, 4); - w.write(AOT_AAC_LC as u32, 5); - w.write(0, 3); - let s = parse_sbr_config(&w.into_bytes()).unwrap(); - assert!(s.sbr_present && s.ps_present, "AOT 29 implies SBR + PS"); - assert_eq!(s.output_sample_rate, 48000); - assert_eq!(s.core_sample_rate, 24000); - } - - /// **Explicit backward-compatible signalling** — the form legacy decoders can - /// still read. AOT 2 up front, then the 0x2B7 sync extension. - #[test] - fn backward_compatible_signalling() { - let mut w = BitWriter::new(); - w.write(AOT_AAC_LC as u32, 5); - w.write(6, 4); // core sfIndex = 24000 - w.write(2, 4); - w.write(0, 3); // GASpecificConfig - w.write(SYNC_EXT_SBR, 11); - w.write(AOT_SBR as u32, 5); - w.write_bool(true); // sbrPresentFlag - w.write(3, 4); // extension sfIndex = 48000 - let s = parse_sbr_config(&w.into_bytes()).unwrap(); - assert!(s.sbr_present); - assert!(!s.ps_present); - assert_eq!(s.core_sample_rate, 24000); - assert_eq!(s.output_sample_rate, 48000); - } - - /// Backward-compatible PS signalling stacks a second sync extension. - #[test] - fn backward_compatible_ps_signalling() { - let mut w = BitWriter::new(); - w.write(AOT_AAC_LC as u32, 5); - w.write(6, 4); // 24000 core - w.write(2, 4); - w.write(0, 3); - w.write(SYNC_EXT_SBR, 11); - w.write(AOT_SBR as u32, 5); - w.write_bool(true); - w.write(3, 4); // 48000 - w.write(SYNC_EXT_PS, 11); - w.write_bool(true); // psPresentFlag - let s = parse_sbr_config(&w.into_bytes()).unwrap(); - assert!(s.sbr_present && s.ps_present); - assert_eq!(s.output_sample_rate, 48000); - } - - /// SBR signalled without an explicit extension rate implies doubling. - #[test] - fn sbr_without_explicit_rate_doubles() { - let mut w = BitWriter::new(); - w.write(AOT_AAC_LC as u32, 5); - w.write(6, 4); // 24000 - w.write(1, 4); - w.write(0, 3); - w.write(SYNC_EXT_SBR, 11); - w.write(AOT_SBR as u32, 5); - w.write_bool(false); // sbrPresentFlag = 0 - let s = parse_sbr_config(&w.into_bytes()).unwrap(); - assert!(!s.sbr_present, "an explicit 0 must not turn SBR on"); - assert_eq!(s.output_sample_rate, 24000); - } - - /// Fill-element SBR payload detection, for implicit signalling. - #[test] - fn detects_sbr_fill_payload() { - assert!(fil_payload_is_sbr(&[0xD0])); // EXT_SBR_DATA = 13 - assert!(fil_payload_is_sbr(&[0xE5])); // EXT_SBR_DATA_CRC = 14 - assert!(!fil_payload_is_sbr(&[0x10])); // EXT_FILL_DATA - assert!(!fil_payload_is_sbr(&[0x00])); - assert!(!fil_payload_is_sbr(&[])); - } - - /// **The integration that matters.** A decoder built from raw HE-AAC config - /// bytes must decode the CORE correctly and report the DOUBLED output rate. - /// Built from the plain `AudioSpecificConfig` path it reports the core rate, - /// and a player believing that runs the audio at half speed — which is the - /// bug this module exists to prevent. - #[test] - fn decoder_reports_he_aac_output_rate() { - // Explicit hierarchical HE-AAC v1: 44100 output, 22050 core. - let mut w = BitWriter::new(); - w.write(AOT_SBR as u32, 5); - w.write(4, 4); // extension sfIndex = 44100 - w.write(1, 4); // mono - w.write(AOT_AAC_LC as u32, 5); - w.write(0, 3); - let asc = w.into_bytes(); - - let dec = crate::AacDecoder::with_config_bytes(&asc).expect("config"); - assert_eq!( - dec.output_sample_rate(), - Some(44100), - "HE-AAC must report the DOUBLED output rate" - ); - assert_eq!(dec.sbr_support(), SbrSupport::CoreOnly); - let s = dec.sbr_config().expect("sbr config"); - assert_eq!(s.core_sample_rate, 22050, "core decodes at half rate"); - - // Plain AAC-LC through the same path is unaffected. - let plain = crate::audio_specific_config_bytes(48000, 2); - let d2 = crate::AacDecoder::with_config_bytes(&plain).expect("config"); - assert_eq!(d2.output_sample_rate(), Some(48000)); - assert_eq!(d2.sbr_support(), SbrSupport::NotPresent); - } - - /// A real AAC-LC stream still round-trips through the new config path — the - /// HE-AAC work must not disturb the overwhelmingly common case. - #[test] - fn plain_aac_still_decodes_through_the_new_path() { - use crate::{AacEncoder, AacEncoderConfig}; - let sr = 44100u32; - let n = 6 * 1024; - let pcm: Vec = (0..n) - .map(|i| { - let t = i as f32 / sr as f32; - 0.3 * (2.0 * std::f32::consts::PI * 440.0 * t).sin() - }) - .collect(); - let mut enc = AacEncoder::new(AacEncoderConfig::default()); - enc.push_pcm(&pcm, 1, sr).unwrap(); - enc.finish(); - - let asc = crate::audio_specific_config_bytes(sr, 1); - let mut dec = crate::AacDecoder::with_config_bytes(&asc).expect("config"); - let mut got = 0usize; - while let Ok(p) = enc.next_packet() { - got += dec.decode(&p.data, None).expect("decode").frames(); - } - assert!(got >= n, "decoded {got} of {n}"); - assert_eq!(dec.sbr_support(), SbrSupport::NotPresent); - } -} diff --git a/vendor/rusty_aac/src/swb.rs b/vendor/rusty_aac/src/swb.rs deleted file mode 100644 index badb500..0000000 --- a/vendor/rusty_aac/src/swb.rs +++ /dev/null @@ -1,129 +0,0 @@ -//! Scalefactor-band (SWB) offset tables — ISO 14496-3 Annex 4.A. -//! -//! Each table lists the spectral-coefficient index where each scalefactor band -//! starts, ending with the transform's coefficient count (1024 for long -//! windows, 128 for one short window). `num_swb = table.len() - 1`. Tables are -//! shared across several sampling rates per the spec's grouping. - -#![allow(dead_code)] - -// ---- Long-window (1024) offsets ------------------------------------------ - -const LONG_96: &[u16] = &[ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 108, 120, 132, - 144, 156, 172, 188, 212, 240, 276, 320, 384, 448, 512, 576, 640, 704, 768, 832, 896, 960, 1024, -]; - -const LONG_64: &[u16] = &[ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 100, 112, 124, 140, - 156, 172, 192, 216, 240, 268, 304, 344, 384, 424, 464, 504, 544, 584, 624, 664, 704, 744, 784, - 824, 864, 904, 944, 984, 1024, -]; - -const LONG_48: &[u16] = &[ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160, - 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, - 736, 768, 800, 832, 864, 896, 928, 1024, -]; - -const LONG_32: &[u16] = &[ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 88, 96, 108, 120, 132, 144, 160, - 176, 196, 216, 240, 264, 292, 320, 352, 384, 416, 448, 480, 512, 544, 576, 608, 640, 672, 704, - 736, 768, 800, 832, 864, 896, 928, 960, 992, 1024, -]; - -const LONG_24: &[u16] = &[ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124, 136, - 148, 160, 172, 188, 204, 220, 240, 260, 284, 308, 336, 364, 396, 432, 468, 508, 552, 600, 652, - 704, 768, 832, 896, 960, 1024, -]; - -const LONG_16: &[u16] = &[ - 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 100, 112, 124, 136, 148, 160, 172, 184, 196, 212, - 228, 244, 260, 280, 300, 320, 344, 368, 396, 424, 456, 492, 532, 572, 616, 664, 716, 772, 832, - 896, 960, 1024, -]; - -const LONG_8: &[u16] = &[ - 0, 12, 24, 36, 48, 60, 72, 84, 96, 108, 120, 132, 144, 156, 172, 188, 204, 220, 236, 252, 268, - 288, 308, 328, 348, 372, 396, 420, 448, 476, 508, 544, 580, 620, 664, 712, 764, 820, 880, 944, - 1024, -]; - -// ---- Short-window (128) offsets ------------------------------------------ - -const SHORT_96: &[u16] = &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128]; -const SHORT_64: &[u16] = &[0, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 92, 128]; -const SHORT_48: &[u16] = &[0, 4, 8, 12, 16, 20, 28, 36, 44, 56, 68, 80, 96, 112, 128]; -const SHORT_24: &[u16] = &[ - 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 64, 76, 92, 108, 128, -]; -const SHORT_16: &[u16] = &[ - 0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 60, 72, 88, 108, 128, -]; -const SHORT_8: &[u16] = &[ - 0, 4, 8, 12, 16, 20, 24, 28, 36, 44, 52, 60, 72, 88, 108, 128, -]; - -/// SWB offset table for a window type and sampling-frequency index. Returns the -/// full offset array (ending in 1024 long / 128 short); `num_swb = len - 1`. -pub fn swb_offsets(long: bool, fs_index: u8) -> &'static [u16] { - if long { - match fs_index { - 0 | 1 => LONG_96, - 2 => LONG_64, - 3 | 4 => LONG_48, - 5 => LONG_32, - 6 | 7 => LONG_24, - 8 | 9 | 10 => LONG_16, - _ => LONG_8, - } - } else { - match fs_index { - 0 | 1 => SHORT_96, - 2 => SHORT_64, - 3 | 4 | 5 => SHORT_48, - 6 | 7 => SHORT_24, - 8 | 9 | 10 => SHORT_16, - _ => SHORT_8, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn check(table: &[u16], end: u16) { - assert_eq!(table[0], 0, "must start at 0"); - assert_eq!(*table.last().unwrap(), end, "must end at {end}"); - assert!( - table.windows(2).all(|w| w[1] > w[0]), - "offsets must be strictly increasing" - ); - } - - #[test] - fn all_long_tables_well_formed() { - for fs in 0u8..=12 { - check(swb_offsets(true, fs), 1024); - } - } - - #[test] - fn all_short_tables_well_formed() { - for fs in 0u8..=12 { - check(swb_offsets(false, fs), 128); - } - } - - #[test] - fn known_band_counts() { - // num_swb = len - 1, against the spec's documented counts. - assert_eq!(swb_offsets(true, 3).len() - 1, 49); // 48 kHz long - assert_eq!(swb_offsets(true, 5).len() - 1, 51); // 32 kHz long - assert_eq!(swb_offsets(true, 11).len() - 1, 40); // 8 kHz long - assert_eq!(swb_offsets(false, 3).len() - 1, 14); // 48 kHz short - assert_eq!(swb_offsets(false, 8).len() - 1, 15); // 16 kHz short - } -} diff --git a/vendor/rusty_aac/src/tables.rs b/vendor/rusty_aac/src/tables.rs deleted file mode 100644 index 9c5d2b4..0000000 --- a/vendor/rusty_aac/src/tables.rs +++ /dev/null @@ -1,296 +0,0 @@ -//! AAC spectral + scalefactor Huffman codebook tables (ISO 14496-3 Tables -//! 4.A.2–4.A.13 and the scalefactor codebook). -//! -//! These are fixed standard data — the exact codeword/length pairs every AAC -//! decoder must use. They were transcribed from the ISO reference values and -//! each is checked in-tree (`codebooks_are_structurally_valid`) for entry -//! count, prefix-freedom, and Kraft sum, so a corrupted table fails the build's -//! tests rather than silently mis-decoding. All twelve are complete prefix -//! codes (Kraft = 1). - -#![allow(dead_code)] - -use crate::huffman::HuffBook; - -static CODES1: &[u32] = &[ - 0x7f8, 0x1f1, 0x7fd, 0x3f5, 0x068, 0x3f0, 0x7f7, 0x1ec, 0x7f5, 0x3f1, 0x072, 0x3f4, 0x074, - 0x011, 0x076, 0x1eb, 0x06c, 0x3f6, 0x7fc, 0x1e1, 0x7f1, 0x1f0, 0x061, 0x1f6, 0x7f2, 0x1ea, - 0x7fb, 0x1f2, 0x069, 0x1ed, 0x077, 0x017, 0x06f, 0x1e6, 0x064, 0x1e5, 0x067, 0x015, 0x062, - 0x012, 0x000, 0x014, 0x065, 0x016, 0x06d, 0x1e9, 0x063, 0x1e4, 0x06b, 0x013, 0x071, 0x1e3, - 0x070, 0x1f3, 0x7fe, 0x1e7, 0x7f3, 0x1ef, 0x060, 0x1ee, 0x7f0, 0x1e2, 0x7fa, 0x3f3, 0x06a, - 0x1e8, 0x075, 0x010, 0x073, 0x1f4, 0x06e, 0x3f7, 0x7f6, 0x1e0, 0x7f9, 0x3f2, 0x066, 0x1f5, - 0x7ff, 0x1f7, 0x7f4, -]; -static BITS1: &[u8] = &[ - 11, 9, 11, 10, 7, 10, 11, 9, 11, 10, 7, 10, 7, 5, 7, 9, 7, 10, 11, 9, 11, 9, 7, 9, 11, 9, 11, - 9, 7, 9, 7, 5, 7, 9, 7, 9, 7, 5, 7, 5, 1, 5, 7, 5, 7, 9, 7, 9, 7, 5, 7, 9, 7, 9, 11, 9, 11, 9, - 7, 9, 11, 9, 11, 10, 7, 9, 7, 5, 7, 9, 7, 10, 11, 9, 11, 10, 7, 9, 11, 9, 11, -]; - -static CODES2: &[u32] = &[ - 0x1f3, 0x06f, 0x1fd, 0x0eb, 0x023, 0x0ea, 0x1f7, 0x0e8, 0x1fa, 0x0f2, 0x02d, 0x070, 0x020, - 0x006, 0x02b, 0x06e, 0x028, 0x0e9, 0x1f9, 0x066, 0x0f8, 0x0e7, 0x01b, 0x0f1, 0x1f4, 0x06b, - 0x1f5, 0x0ec, 0x02a, 0x06c, 0x02c, 0x00a, 0x027, 0x067, 0x01a, 0x0f5, 0x024, 0x008, 0x01f, - 0x009, 0x000, 0x007, 0x01d, 0x00b, 0x030, 0x0ef, 0x01c, 0x064, 0x01e, 0x00c, 0x029, 0x0f3, - 0x02f, 0x0f0, 0x1fc, 0x071, 0x1f2, 0x0f4, 0x021, 0x0e6, 0x0f7, 0x068, 0x1f8, 0x0ee, 0x022, - 0x065, 0x031, 0x002, 0x026, 0x0ed, 0x025, 0x06a, 0x1fb, 0x072, 0x1fe, 0x069, 0x02e, 0x0f6, - 0x1ff, 0x06d, 0x1f6, -]; -static BITS2: &[u8] = &[ - 9, 7, 9, 8, 6, 8, 9, 8, 9, 8, 6, 7, 6, 5, 6, 7, 6, 8, 9, 7, 8, 8, 6, 8, 9, 7, 9, 8, 6, 7, 6, 5, - 6, 7, 6, 8, 6, 5, 6, 5, 3, 5, 6, 5, 6, 8, 6, 7, 6, 5, 6, 8, 6, 8, 9, 7, 9, 8, 6, 8, 8, 7, 9, 8, - 6, 7, 6, 4, 6, 8, 6, 7, 9, 7, 9, 7, 6, 8, 9, 7, 9, -]; - -static CODES3: &[u32] = &[ - 0x0000, 0x0009, 0x00ef, 0x000b, 0x0019, 0x00f0, 0x01eb, 0x01e6, 0x03f2, 0x000a, 0x0035, 0x01ef, - 0x0034, 0x0037, 0x01e9, 0x01ed, 0x01e7, 0x03f3, 0x01ee, 0x03ed, 0x1ffa, 0x01ec, 0x01f2, 0x07f9, - 0x07f8, 0x03f8, 0x0ff8, 0x0008, 0x0038, 0x03f6, 0x0036, 0x0075, 0x03f1, 0x03eb, 0x03ec, 0x0ff4, - 0x0018, 0x0076, 0x07f4, 0x0039, 0x0074, 0x03ef, 0x01f3, 0x01f4, 0x07f6, 0x01e8, 0x03ea, 0x1ffc, - 0x00f2, 0x01f1, 0x0ffb, 0x03f5, 0x07f3, 0x0ffc, 0x00ee, 0x03f7, 0x7ffe, 0x01f0, 0x07f5, 0x7ffd, - 0x1ffb, 0x3ffa, 0xffff, 0x00f1, 0x03f0, 0x3ffc, 0x01ea, 0x03ee, 0x3ffb, 0x0ff6, 0x0ffa, 0x7ffc, - 0x07f2, 0x0ff5, 0xfffe, 0x03f4, 0x07f7, 0x7ffb, 0x0ff7, 0x0ff9, 0x7ffa, -]; -static BITS3: &[u8] = &[ - 1, 4, 8, 4, 5, 8, 9, 9, 10, 4, 6, 9, 6, 6, 9, 9, 9, 10, 9, 10, 13, 9, 9, 11, 11, 10, 12, 4, 6, - 10, 6, 7, 10, 10, 10, 12, 5, 7, 11, 6, 7, 10, 9, 9, 11, 9, 10, 13, 8, 9, 12, 10, 11, 12, 8, 10, - 15, 9, 11, 15, 13, 14, 16, 8, 10, 14, 9, 10, 14, 12, 12, 15, 11, 12, 16, 10, 11, 15, 12, 12, - 15, -]; - -static CODES4: &[u32] = &[ - 0x007, 0x016, 0x0f6, 0x018, 0x008, 0x0ef, 0x1ef, 0x0f3, 0x7f8, 0x019, 0x017, 0x0ed, 0x015, - 0x001, 0x0e2, 0x0f0, 0x070, 0x3f0, 0x1ee, 0x0f1, 0x7fa, 0x0ee, 0x0e4, 0x3f2, 0x7f6, 0x3ef, - 0x7fd, 0x005, 0x014, 0x0f2, 0x009, 0x004, 0x0e5, 0x0f4, 0x0e8, 0x3f4, 0x006, 0x002, 0x0e7, - 0x003, 0x000, 0x06b, 0x0e3, 0x069, 0x1f3, 0x0eb, 0x0e6, 0x3f6, 0x06e, 0x06a, 0x1f4, 0x3ec, - 0x1f0, 0x3f9, 0x0f5, 0x0ec, 0x7fb, 0x0ea, 0x06f, 0x3f7, 0x7f9, 0x3f3, 0xfff, 0x0e9, 0x06d, - 0x3f8, 0x06c, 0x068, 0x1f5, 0x3ee, 0x1f2, 0x7f4, 0x7f7, 0x3f1, 0xffe, 0x3ed, 0x1f1, 0x7f5, - 0x7fe, 0x3f5, 0x7fc, -]; -static BITS4: &[u8] = &[ - 4, 5, 8, 5, 4, 8, 9, 8, 11, 5, 5, 8, 5, 4, 8, 8, 7, 10, 9, 8, 11, 8, 8, 10, 11, 10, 11, 4, 5, - 8, 4, 4, 8, 8, 8, 10, 4, 4, 8, 4, 4, 7, 8, 7, 9, 8, 8, 10, 7, 7, 9, 10, 9, 10, 8, 8, 11, 8, 7, - 10, 11, 10, 12, 8, 7, 10, 7, 7, 9, 10, 9, 11, 11, 10, 12, 10, 9, 11, 11, 10, 11, -]; - -static CODES5: &[u32] = &[ - 0x1fff, 0x0ff7, 0x07f4, 0x07e8, 0x03f1, 0x07ee, 0x07f9, 0x0ff8, 0x1ffd, 0x0ffd, 0x07f1, 0x03e8, - 0x01e8, 0x00f0, 0x01ec, 0x03ee, 0x07f2, 0x0ffa, 0x0ff4, 0x03ef, 0x01f2, 0x00e8, 0x0070, 0x00ec, - 0x01f0, 0x03ea, 0x07f3, 0x07eb, 0x01eb, 0x00ea, 0x001a, 0x0008, 0x0019, 0x00ee, 0x01ef, 0x07ed, - 0x03f0, 0x00f2, 0x0073, 0x000b, 0x0000, 0x000a, 0x0071, 0x00f3, 0x07e9, 0x07ef, 0x01ee, 0x00ef, - 0x0018, 0x0009, 0x001b, 0x00eb, 0x01e9, 0x07ec, 0x07f6, 0x03eb, 0x01f3, 0x00ed, 0x0072, 0x00e9, - 0x01f1, 0x03ed, 0x07f7, 0x0ff6, 0x07f0, 0x03e9, 0x01ed, 0x00f1, 0x01ea, 0x03ec, 0x07f8, 0x0ff9, - 0x1ffc, 0x0ffc, 0x0ff5, 0x07ea, 0x03f3, 0x03f2, 0x07f5, 0x0ffb, 0x1ffe, -]; -static BITS5: &[u8] = &[ - 13, 12, 11, 11, 10, 11, 11, 12, 13, 12, 11, 10, 9, 8, 9, 10, 11, 12, 12, 10, 9, 8, 7, 8, 9, 10, - 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 10, 8, 7, 4, 1, 4, 7, 8, 11, 11, 9, 8, 5, 4, 5, 8, 9, 11, 11, - 10, 9, 8, 7, 8, 9, 10, 11, 12, 11, 10, 9, 8, 9, 10, 11, 12, 13, 12, 12, 11, 10, 10, 11, 12, 13, -]; - -static CODES6: &[u32] = &[ - 0x7fe, 0x3fd, 0x1f1, 0x1eb, 0x1f4, 0x1ea, 0x1f0, 0x3fc, 0x7fd, 0x3f6, 0x1e5, 0x0ea, 0x06c, - 0x071, 0x068, 0x0f0, 0x1e6, 0x3f7, 0x1f3, 0x0ef, 0x032, 0x027, 0x028, 0x026, 0x031, 0x0eb, - 0x1f7, 0x1e8, 0x06f, 0x02e, 0x008, 0x004, 0x006, 0x029, 0x06b, 0x1ee, 0x1ef, 0x072, 0x02d, - 0x002, 0x000, 0x003, 0x02f, 0x073, 0x1fa, 0x1e7, 0x06e, 0x02b, 0x007, 0x001, 0x005, 0x02c, - 0x06d, 0x1ec, 0x1f9, 0x0ee, 0x030, 0x024, 0x02a, 0x025, 0x033, 0x0ec, 0x1f2, 0x3f8, 0x1e4, - 0x0ed, 0x06a, 0x070, 0x069, 0x074, 0x0f1, 0x3fa, 0x7ff, 0x3f9, 0x1f6, 0x1ed, 0x1f8, 0x1e9, - 0x1f5, 0x3fb, 0x7fc, -]; -static BITS6: &[u8] = &[ - 11, 10, 9, 9, 9, 9, 9, 10, 11, 10, 9, 8, 7, 7, 7, 8, 9, 10, 9, 8, 6, 6, 6, 6, 6, 8, 9, 9, 7, 6, - 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 7, 6, 4, 4, 4, 6, 7, 9, 9, 8, 6, 6, 6, 6, 6, 8, - 9, 10, 9, 8, 7, 7, 7, 7, 8, 10, 11, 10, 9, 9, 9, 9, 9, 10, 11, -]; - -static CODES7: &[u32] = &[ - 0x000, 0x005, 0x037, 0x074, 0x0f2, 0x1eb, 0x3ed, 0x7f7, 0x004, 0x00c, 0x035, 0x071, 0x0ec, - 0x0ee, 0x1ee, 0x1f5, 0x036, 0x034, 0x072, 0x0ea, 0x0f1, 0x1e9, 0x1f3, 0x3f5, 0x073, 0x070, - 0x0eb, 0x0f0, 0x1f1, 0x1f0, 0x3ec, 0x3fa, 0x0f3, 0x0ed, 0x1e8, 0x1ef, 0x3ef, 0x3f1, 0x3f9, - 0x7fb, 0x1ed, 0x0ef, 0x1ea, 0x1f2, 0x3f3, 0x3f8, 0x7f9, 0x7fc, 0x3ee, 0x1ec, 0x1f4, 0x3f4, - 0x3f7, 0x7f8, 0xffd, 0xffe, 0x7f6, 0x3f0, 0x3f2, 0x3f6, 0x7fa, 0x7fd, 0xffc, 0xfff, -]; -static BITS7: &[u8] = &[ - 1, 3, 6, 7, 8, 9, 10, 11, 3, 4, 6, 7, 8, 8, 9, 9, 6, 6, 7, 8, 8, 9, 9, 10, 7, 7, 8, 8, 9, 9, - 10, 10, 8, 8, 9, 9, 10, 10, 10, 11, 9, 8, 9, 9, 10, 10, 11, 11, 10, 9, 9, 10, 10, 11, 12, 12, - 11, 10, 10, 10, 11, 11, 12, 12, -]; - -static CODES8: &[u32] = &[ - 0x00e, 0x005, 0x010, 0x030, 0x06f, 0x0f1, 0x1fa, 0x3fe, 0x003, 0x000, 0x004, 0x012, 0x02c, - 0x06a, 0x075, 0x0f8, 0x00f, 0x002, 0x006, 0x014, 0x02e, 0x069, 0x072, 0x0f5, 0x02f, 0x011, - 0x013, 0x02a, 0x032, 0x06c, 0x0ec, 0x0fa, 0x071, 0x02b, 0x02d, 0x031, 0x06d, 0x070, 0x0f2, - 0x1f9, 0x0ef, 0x068, 0x033, 0x06b, 0x06e, 0x0ee, 0x0f9, 0x3fc, 0x1f8, 0x074, 0x073, 0x0ed, - 0x0f0, 0x0f6, 0x1f6, 0x1fd, 0x3fd, 0x0f3, 0x0f4, 0x0f7, 0x1f7, 0x1fb, 0x1fc, 0x3ff, -]; -static BITS8: &[u8] = &[ - 5, 4, 5, 6, 7, 8, 9, 10, 4, 3, 4, 5, 6, 7, 7, 8, 5, 4, 4, 5, 6, 7, 7, 8, 6, 5, 5, 6, 6, 7, 8, - 8, 7, 6, 6, 6, 7, 7, 8, 9, 8, 7, 6, 7, 7, 8, 8, 10, 9, 7, 7, 8, 8, 8, 9, 9, 10, 8, 8, 8, 9, 9, - 9, 10, -]; - -static CODES9: &[u32] = &[ - 0x0000, 0x0005, 0x0037, 0x00e7, 0x01de, 0x03ce, 0x03d9, 0x07c8, 0x07cd, 0x0fc8, 0x0fdd, 0x1fe4, - 0x1fec, 0x0004, 0x000c, 0x0035, 0x0072, 0x00ea, 0x00ed, 0x01e2, 0x03d1, 0x03d3, 0x03e0, 0x07d8, - 0x0fcf, 0x0fd5, 0x0036, 0x0034, 0x0071, 0x00e8, 0x00ec, 0x01e1, 0x03cf, 0x03dd, 0x03db, 0x07d0, - 0x0fc7, 0x0fd4, 0x0fe4, 0x00e6, 0x0070, 0x00e9, 0x01dd, 0x01e3, 0x03d2, 0x03dc, 0x07cc, 0x07ca, - 0x07de, 0x0fd8, 0x0fea, 0x1fdb, 0x01df, 0x00eb, 0x01dc, 0x01e6, 0x03d5, 0x03de, 0x07cb, 0x07dd, - 0x07dc, 0x0fcd, 0x0fe2, 0x0fe7, 0x1fe1, 0x03d0, 0x01e0, 0x01e4, 0x03d6, 0x07c5, 0x07d1, 0x07db, - 0x0fd2, 0x07e0, 0x0fd9, 0x0feb, 0x1fe3, 0x1fe9, 0x07c4, 0x01e5, 0x03d7, 0x07c6, 0x07cf, 0x07da, - 0x0fcb, 0x0fda, 0x0fe3, 0x0fe9, 0x1fe6, 0x1ff3, 0x1ff7, 0x07d3, 0x03d8, 0x03e1, 0x07d4, 0x07d9, - 0x0fd3, 0x0fde, 0x1fdd, 0x1fd9, 0x1fe2, 0x1fea, 0x1ff1, 0x1ff6, 0x07d2, 0x03d4, 0x03da, 0x07c7, - 0x07d7, 0x07e2, 0x0fce, 0x0fdb, 0x1fd8, 0x1fee, 0x3ff0, 0x1ff4, 0x3ff2, 0x07e1, 0x03df, 0x07c9, - 0x07d6, 0x0fca, 0x0fd0, 0x0fe5, 0x0fe6, 0x1feb, 0x1fef, 0x3ff3, 0x3ff4, 0x3ff5, 0x0fe0, 0x07ce, - 0x07d5, 0x0fc6, 0x0fd1, 0x0fe1, 0x1fe0, 0x1fe8, 0x1ff0, 0x3ff1, 0x3ff8, 0x3ff6, 0x7ffc, 0x0fe8, - 0x07df, 0x0fc9, 0x0fd7, 0x0fdc, 0x1fdc, 0x1fdf, 0x1fed, 0x1ff5, 0x3ff9, 0x3ffb, 0x7ffd, 0x7ffe, - 0x1fe7, 0x0fcc, 0x0fd6, 0x0fdf, 0x1fde, 0x1fda, 0x1fe5, 0x1ff2, 0x3ffa, 0x3ff7, 0x3ffc, 0x3ffd, - 0x7fff, -]; -static BITS9: &[u8] = &[ - 1, 3, 6, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 3, 4, 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 6, - 6, 7, 8, 8, 9, 10, 10, 10, 11, 12, 12, 12, 8, 7, 8, 9, 9, 10, 10, 11, 11, 11, 12, 12, 13, 9, 8, - 9, 9, 10, 10, 11, 11, 11, 12, 12, 12, 13, 10, 9, 9, 10, 11, 11, 11, 12, 11, 12, 12, 13, 13, 11, - 9, 10, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 11, 10, 10, 11, 11, 12, 12, 13, 13, 13, 13, 13, - 13, 11, 10, 10, 11, 11, 11, 12, 12, 13, 13, 14, 13, 14, 11, 10, 11, 11, 12, 12, 12, 12, 13, 13, - 14, 14, 14, 12, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15, 12, 11, 12, 12, 12, 13, 13, 13, - 13, 14, 14, 15, 15, 13, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, -]; - -static CODES10: &[u32] = &[ - 0x022, 0x008, 0x01d, 0x026, 0x05f, 0x0d3, 0x1cf, 0x3d0, 0x3d7, 0x3ed, 0x7f0, 0x7f6, 0xffd, - 0x007, 0x000, 0x001, 0x009, 0x020, 0x054, 0x060, 0x0d5, 0x0dc, 0x1d4, 0x3cd, 0x3de, 0x7e7, - 0x01c, 0x002, 0x006, 0x00c, 0x01e, 0x028, 0x05b, 0x0cd, 0x0d9, 0x1ce, 0x1dc, 0x3d9, 0x3f1, - 0x025, 0x00b, 0x00a, 0x00d, 0x024, 0x057, 0x061, 0x0cc, 0x0dd, 0x1cc, 0x1de, 0x3d3, 0x3e7, - 0x05d, 0x021, 0x01f, 0x023, 0x027, 0x059, 0x064, 0x0d8, 0x0df, 0x1d2, 0x1e2, 0x3dd, 0x3ee, - 0x0d1, 0x055, 0x029, 0x056, 0x058, 0x062, 0x0ce, 0x0e0, 0x0e2, 0x1da, 0x3d4, 0x3e3, 0x7eb, - 0x1c9, 0x05e, 0x05a, 0x05c, 0x063, 0x0ca, 0x0da, 0x1c7, 0x1ca, 0x1e0, 0x3db, 0x3e8, 0x7ec, - 0x1e3, 0x0d2, 0x0cb, 0x0d0, 0x0d7, 0x0db, 0x1c6, 0x1d5, 0x1d8, 0x3ca, 0x3da, 0x7ea, 0x7f1, - 0x1e1, 0x0d4, 0x0cf, 0x0d6, 0x0de, 0x0e1, 0x1d0, 0x1d6, 0x3d1, 0x3d5, 0x3f2, 0x7ee, 0x7fb, - 0x3e9, 0x1cd, 0x1c8, 0x1cb, 0x1d1, 0x1d7, 0x1df, 0x3cf, 0x3e0, 0x3ef, 0x7e6, 0x7f8, 0xffa, - 0x3eb, 0x1dd, 0x1d3, 0x1d9, 0x1db, 0x3d2, 0x3cc, 0x3dc, 0x3ea, 0x7ed, 0x7f3, 0x7f9, 0xff9, - 0x7f2, 0x3ce, 0x1e4, 0x3cb, 0x3d8, 0x3d6, 0x3e2, 0x3e5, 0x7e8, 0x7f4, 0x7f5, 0x7f7, 0xffb, - 0x7fa, 0x3ec, 0x3df, 0x3e1, 0x3e4, 0x3e6, 0x3f0, 0x7e9, 0x7ef, 0xff8, 0xffe, 0xffc, 0xfff, -]; -static BITS10: &[u8] = &[ - 6, 5, 6, 6, 7, 8, 9, 10, 10, 10, 11, 11, 12, 5, 4, 4, 5, 6, 7, 7, 8, 8, 9, 10, 10, 11, 6, 4, 5, - 5, 6, 6, 7, 8, 8, 9, 9, 10, 10, 6, 5, 5, 5, 6, 7, 7, 8, 8, 9, 9, 10, 10, 7, 6, 6, 6, 6, 7, 7, - 8, 8, 9, 9, 10, 10, 8, 7, 6, 7, 7, 7, 8, 8, 8, 9, 10, 10, 11, 9, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, - 10, 11, 9, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 9, 8, 8, 8, 8, 8, 9, 9, 10, 10, 10, 11, 11, - 10, 9, 9, 9, 9, 9, 9, 10, 10, 10, 11, 11, 12, 10, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 12, - 11, 10, 9, 10, 10, 10, 10, 10, 11, 11, 11, 11, 12, 11, 10, 10, 10, 10, 10, 10, 11, 11, 12, 12, - 12, 12, -]; - -static CODES11: &[u32] = &[ - 0x000, 0x006, 0x019, 0x03d, 0x09c, 0x0c6, 0x1a7, 0x390, 0x3c2, 0x3df, 0x7e6, 0x7f3, 0xffb, - 0x7ec, 0xffa, 0xffe, 0x38e, 0x005, 0x001, 0x008, 0x014, 0x037, 0x042, 0x092, 0x0af, 0x191, - 0x1a5, 0x1b5, 0x39e, 0x3c0, 0x3a2, 0x3cd, 0x7d6, 0x0ae, 0x017, 0x007, 0x009, 0x018, 0x039, - 0x040, 0x08e, 0x0a3, 0x0b8, 0x199, 0x1ac, 0x1c1, 0x3b1, 0x396, 0x3be, 0x3ca, 0x09d, 0x03c, - 0x015, 0x016, 0x01a, 0x03b, 0x044, 0x091, 0x0a5, 0x0be, 0x196, 0x1ae, 0x1b9, 0x3a1, 0x391, - 0x3a5, 0x3d5, 0x094, 0x09a, 0x036, 0x038, 0x03a, 0x041, 0x08c, 0x09b, 0x0b0, 0x0c3, 0x19e, - 0x1ab, 0x1bc, 0x39f, 0x38f, 0x3a9, 0x3cf, 0x093, 0x0bf, 0x03e, 0x03f, 0x043, 0x045, 0x09e, - 0x0a7, 0x0b9, 0x194, 0x1a2, 0x1ba, 0x1c3, 0x3a6, 0x3a7, 0x3bb, 0x3d4, 0x09f, 0x1a0, 0x08f, - 0x08d, 0x090, 0x098, 0x0a6, 0x0b6, 0x0c4, 0x19f, 0x1af, 0x1bf, 0x399, 0x3bf, 0x3b4, 0x3c9, - 0x3e7, 0x0a8, 0x1b6, 0x0ab, 0x0a4, 0x0aa, 0x0b2, 0x0c2, 0x0c5, 0x198, 0x1a4, 0x1b8, 0x38c, - 0x3a4, 0x3c4, 0x3c6, 0x3dd, 0x3e8, 0x0ad, 0x3af, 0x192, 0x0bd, 0x0bc, 0x18e, 0x197, 0x19a, - 0x1a3, 0x1b1, 0x38d, 0x398, 0x3b7, 0x3d3, 0x3d1, 0x3db, 0x7dd, 0x0b4, 0x3de, 0x1a9, 0x19b, - 0x19c, 0x1a1, 0x1aa, 0x1ad, 0x1b3, 0x38b, 0x3b2, 0x3b8, 0x3ce, 0x3e1, 0x3e0, 0x7d2, 0x7e5, - 0x0b7, 0x7e3, 0x1bb, 0x1a8, 0x1a6, 0x1b0, 0x1b2, 0x1b7, 0x39b, 0x39a, 0x3ba, 0x3b5, 0x3d6, - 0x7d7, 0x3e4, 0x7d8, 0x7ea, 0x0ba, 0x7e8, 0x3a0, 0x1bd, 0x1b4, 0x38a, 0x1c4, 0x392, 0x3aa, - 0x3b0, 0x3bc, 0x3d7, 0x7d4, 0x7dc, 0x7db, 0x7d5, 0x7f0, 0x0c1, 0x7fb, 0x3c8, 0x3a3, 0x395, - 0x39d, 0x3ac, 0x3ae, 0x3c5, 0x3d8, 0x3e2, 0x3e6, 0x7e4, 0x7e7, 0x7e0, 0x7e9, 0x7f7, 0x190, - 0x7f2, 0x393, 0x1be, 0x1c0, 0x394, 0x397, 0x3ad, 0x3c3, 0x3c1, 0x3d2, 0x7da, 0x7d9, 0x7df, - 0x7eb, 0x7f4, 0x7fa, 0x195, 0x7f8, 0x3bd, 0x39c, 0x3ab, 0x3a8, 0x3b3, 0x3b9, 0x3d0, 0x3e3, - 0x3e5, 0x7e2, 0x7de, 0x7ed, 0x7f1, 0x7f9, 0x7fc, 0x193, 0xffd, 0x3dc, 0x3b6, 0x3c7, 0x3cc, - 0x3cb, 0x3d9, 0x3da, 0x7d3, 0x7e1, 0x7ee, 0x7ef, 0x7f5, 0x7f6, 0xffc, 0xfff, 0x19d, 0x1c2, - 0x0b5, 0x0a1, 0x096, 0x097, 0x095, 0x099, 0x0a0, 0x0a2, 0x0ac, 0x0a9, 0x0b1, 0x0b3, 0x0bb, - 0x0c0, 0x18f, 0x004, -]; -static BITS11: &[u8] = &[ - 4, 5, 6, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, 11, 12, 12, 10, 5, 4, 5, 6, 7, 7, 8, 8, 9, 9, 9, - 10, 10, 10, 10, 11, 8, 6, 5, 5, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 7, 6, 6, 6, 7, 7, - 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 8, 8, - 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, - 10, 10, 10, 8, 9, 8, 8, 8, 8, 8, 8, 9, 9, 9, 10, 10, 10, 10, 10, 10, 8, 10, 9, 8, 8, 9, 9, 9, - 9, 9, 10, 10, 10, 10, 10, 10, 11, 8, 10, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, - 8, 11, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 11, 10, 11, 11, 8, 11, 10, 9, 9, 10, 9, 10, 10, - 10, 10, 10, 11, 11, 11, 11, 11, 8, 11, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, - 11, 9, 11, 10, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 11, 10, 10, 10, 10, 10, - 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 9, 12, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, - 11, 12, 12, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 5, -]; - -static SF_CODES: &[u32] = &[ - 0x3ffe8, 0x3ffe6, 0x3ffe7, 0x3ffe5, 0x7fff5, 0x7fff1, 0x7ffed, 0x7fff6, 0x7ffee, 0x7ffef, - 0x7fff0, 0x7fffc, 0x7fffd, 0x7ffff, 0x7fffe, 0x7fff7, 0x7fff8, 0x7fffb, 0x7fff9, 0x3ffe4, - 0x7fffa, 0x3ffe3, 0x1ffef, 0x1fff0, 0x0fff5, 0x1ffee, 0x0fff2, 0x0fff3, 0x0fff4, 0x0fff1, - 0x07ff6, 0x07ff7, 0x03ff9, 0x03ff5, 0x03ff7, 0x03ff3, 0x03ff6, 0x03ff2, 0x01ff7, 0x01ff5, - 0x00ff9, 0x00ff7, 0x00ff6, 0x007f9, 0x00ff4, 0x007f8, 0x003f9, 0x003f7, 0x003f5, 0x001f8, - 0x001f7, 0x000fa, 0x000f8, 0x000f6, 0x00079, 0x0003a, 0x00038, 0x0001a, 0x0000b, 0x00004, - 0x00000, 0x0000a, 0x0000c, 0x0001b, 0x00039, 0x0003b, 0x00078, 0x0007a, 0x000f7, 0x000f9, - 0x001f6, 0x001f9, 0x003f4, 0x003f6, 0x003f8, 0x007f5, 0x007f4, 0x007f6, 0x007f7, 0x00ff5, - 0x00ff8, 0x01ff4, 0x01ff6, 0x01ff8, 0x03ff8, 0x03ff4, 0x0fff0, 0x07ff4, 0x0fff6, 0x07ff5, - 0x3ffe2, 0x7ffd9, 0x7ffda, 0x7ffdb, 0x7ffdc, 0x7ffdd, 0x7ffde, 0x7ffd8, 0x7ffd2, 0x7ffd3, - 0x7ffd4, 0x7ffd5, 0x7ffd6, 0x7fff2, 0x7ffdf, 0x7ffe7, 0x7ffe8, 0x7ffe9, 0x7ffea, 0x7ffeb, - 0x7ffe6, 0x7ffe0, 0x7ffe1, 0x7ffe2, 0x7ffe3, 0x7ffe4, 0x7ffe5, 0x7ffd7, 0x7ffec, 0x7fff4, - 0x7fff3, -]; -static SF_BITS: &[u8] = &[ - 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 18, 19, 18, 17, 17, - 16, 17, 16, 16, 16, 16, 15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 12, 12, 12, 11, 12, 11, 10, 10, - 10, 9, 9, 8, 8, 8, 7, 6, 6, 5, 4, 3, 1, 4, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, - 11, 11, 12, 12, 13, 13, 13, 14, 14, 16, 15, 16, 15, 18, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, - 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, -]; - -/// Spectral Huffman codebooks indexed by codebook number 0..=11. Index 0 is the -/// ZERO codebook (never decoded), represented by an empty book. -pub static SPECTRAL_BOOKS: [HuffBook; 12] = [ - HuffBook::new(&[], &[]), - HuffBook::new(CODES1, BITS1), - HuffBook::new(CODES2, BITS2), - HuffBook::new(CODES3, BITS3), - HuffBook::new(CODES4, BITS4), - HuffBook::new(CODES5, BITS5), - HuffBook::new(CODES6, BITS6), - HuffBook::new(CODES7, BITS7), - HuffBook::new(CODES8, BITS8), - HuffBook::new(CODES9, BITS9), - HuffBook::new(CODES10, BITS10), - HuffBook::new(CODES11, BITS11), -]; - -/// The scalefactor codebook (differential scalefactor Huffman). -pub static SCALEFACTOR_BOOK: HuffBook = HuffBook::new(SF_CODES, SF_BITS); - -/// Spectral codebook for codebook number `cb` (1..=11). -pub fn spectral_book(cb: u8) -> &'static HuffBook { - &SPECTRAL_BOOKS[cb as usize] -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn codebooks_are_structurally_valid() { - // Expected entry counts per spectral codebook (dim and value range). - let expected = [81, 81, 81, 81, 81, 81, 64, 64, 169, 169, 289]; - for (i, &count) in expected.iter().enumerate() { - let book = &SPECTRAL_BOOKS[i + 1]; - assert_eq!(book.count(), count, "cb{} count", i + 1); - assert!(book.is_prefix_free(), "cb{} prefix-free", i + 1); - // The 11 spectral books are complete codes. - assert!( - (book.kraft_sum() - 1.0).abs() < 1e-9, - "cb{} kraft = {}", - i + 1, - book.kraft_sum() - ); - } - // Scalefactor book: 121 entries, prefix-free, complete code. - assert_eq!(SCALEFACTOR_BOOK.count(), 121); - assert!(SCALEFACTOR_BOOK.is_prefix_free()); - assert!((SCALEFACTOR_BOOK.kraft_sum() - 1.0).abs() < 1e-9); - } -}