# rusty_aac
[](https://github.com/remade-with-rust)
[](https://www.mata.network)
[](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.**
<details>
<summary><b>How this was measured</b> (click to expand)</summary>
- **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).
</details>
### What changed in 0.5.0
Two measured wins shipped, four candidate tools **measured and rejected**. Δ is
`ours − ffmpeg`; positive = we sound better.
| **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×)
| 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
| 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<f32> = 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<f32> = (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
| `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).