# 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, transient-driven block switching,
per-band M/S stereo, a two-phase bitrate rate loop, 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 — not estimated. **The honest summary: we are substantially faster, and on
quality we win at higher bitrates on mono music while losing at low bitrates,
on stereo, and on transient/speech content.**
<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*,
and differences up there are not resolvable.
- **Speed**: both encoders run as subprocesses with identical invocation shape
(so process launch is paid by both), best-of-5, ABBA-interleaved, on 24 s
clips where launch overhead is a small fraction of the run.
- **Corpus**: real CC0/Public-Domain music (piano, guitar, vocal; mono and
stereo) plus a synthetic suite covering content classes the real corpus does
not contain. Real and synthetic results 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>
### Speed — 4.2–6.5× faster (mean 5.3×)
| piano | **148× realtime** | 29× realtime | **5.2×** |
| guitar | **136× realtime** | 21× realtime | **6.5×** |
| vocal | **149× realtime** | 35× realtime | **4.2×** |
End-to-end through the CLI, including WAV read and MP4 muxing.
### Quality — PEAQ ODG by content band
Δ is `ours − ffmpeg`; **positive = we sound better**. Higher ODG is better.
**Real music, mono** — a clear crossover at ~110–120 kbps:
| piano (CC0) | −1.29 | −0.25 | **+0.28** | **+0.44** |
| guitar (PD) | −1.02 | −0.03 | **+0.65** | **+0.47** |
| vocal (PD) | −1.92 | −0.38 | **+0.39** | **+0.60** |
At 128 k and above we reach the harness ceiling on this content (ODG −0.05 to
+0.14 — i.e. transparent) while FFmpeg's native encoder sits around −0.3 to −0.6.
Below ~96 kbps the ordering reverses and FFmpeg is clearly better.
**Real music, stereo** — FFmpeg is better at every rate:
| piano stereo | −1.12 | −2.11 | −1.73 | −0.16 |
| guitar stereo | −0.55 | −1.34 | −1.32 | −0.28 |
**Synthetic content classes** (mean Δ over all four bitrates):
| tonal music | −0.03 | parity |
| mixed speech+music | −0.40 | behind |
| stereo (wide) | −0.43 | behind |
| quiet / wide-dynamic | −0.69 | behind |
| noisy speech | −0.89 | behind; parity at ≥128k |
| noise-like | −1.03 | behind; parity at ≥128k |
| percussive / transient | −1.77 | **well behind** |
| clean speech | −2.69 | **well behind** |
### What the numbers mean, honestly
- **We are not currently a better-sounding encoder than FFmpeg overall.** We are
better on mono music at 128 kbps and above, at parity on sustained tonal
content, and behind elsewhere — sometimes far behind.
- **Two rate caveats.** At the 64 k target we emit ~89% of FFmpeg's actual
bitrate, and at 192 k we emit ~107% of it. So neither extreme is a perfectly
clean like-for-like: some of the low-rate loss is us under-spending the
budget, and some of the high-rate win is us spending more.
- **The weak spots are known and specific**, not mysterious: transient/percussive
and speech content are exactly where our block-switching and bit-allocation
work is unfinished. The encoder currently has no bit reservoir, no VBR mode, no
absolute-threshold-of-hearing term, and its short blocks code with flat
scalefactors. These are tracked as named work items with measured per-class
evidence in
[`docs/codec-aac-great-gate.md`](https://github.com/Remade-With-Rust/remade_ffmpeg_rs/blob/main/docs/codec-aac-great-gate.md).
- **FFmpeg's native AAC encoder is not the strongest AAC encoder in existence**
(libfdk-aac generally beats it). It is the one available under a permissive
default build, and it is the comparison that was asked for.
---
## 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).