aac

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2026 License: Apache-2.0 Imports: 9 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

aac-go

Pure-Go AAC-LC (MPEG-4 Audio, ISO/IEC 14496-3) encoder and decoder. No cgo, no external binaries.

Supported features

Feature Decoder Encoder
AAC-LC profile (ADTS transport) ✅ ✅
Sample rates ✅ all 13 (8–96 kHz) ✅ 44.1 / 48 kHz
Channels ✅ mono (SCE), stereo (CPE) ✅ mono (SCE), stereo (CPE)
Long / short windows, block switching ✅ incl. "meaningless" transitions ✅ transient detection, 1-block lookahead
Window shapes ✅ sine and KBD ✅ sine
TNS (Temporal Noise Shaping) ✅ ⚙️ opt-in Config.EnableTNS¹
M/S stereo ✅ ❌
Intensity stereo ✅ ❌
PNS (Perceptual Noise Substitution) ✅ ❌
ADTS CRC headers ✅ (skipped, not verified) — (emits CRC-free)
PCE (program config element) ✅ parsed —
Rate control — VBR, Quality 0–1², 6144-bit/ch frame limit enforced
Streaming API (arbitrary chunk sizes) ✅ ✅

¹ Recommended for transient-dominant material only; degrades tonal content without a psychoacoustic model. ² Maps to a uniform quantization noise floor; reference decoders recover 55–82 dB SNR across the range on tonal material, strictly monotonic in both quality and size.

Not supported (explicit ErrUnsupported errors, never silent corruption):

Feature Notes
HE-AAC / HE-AACv2 (SBR, PS) Detected and rejected — decoding only the core band would sound lowpassed
Surround (>2 channels), LFE/CCE channel_configuration 1 and 2 only
MP4 / M4A / TS containers ADTS only; demux upstream
Pulse data, 960-sample frames, MAIN/SSR/LTP profiles Not part of the AAC-LC subset targeted here

Decoding is verified against streams from ffmpeg's native AAC encoder (each tool exercised in isolation and combined) and Apple's encoder: deterministic streams decode within 102–106 dB of the reference decoders; PNS streams match their RMS envelope (noise is decoder-local by design). The MDCT runs on an N/4 complex FFT (~5 µs per 2048-point transform) with a direct evaluation of the standard's formulas kept as the permanent test reference.

Installation

go get github.com/arabian9ts/aac-go

Usage

Encoding
import aac "github.com/arabian9ts/aac-go"

enc, err := aac.NewEncoder(aac.Config{
	SampleRate: 44100, // 44100 or 48000
	Channels:   2,     // 1 (mono) or 2 (stereo)
	Quality:    0.6,   // 0..1, VBR: bitrate/fidelity trade-off
})
if err != nil {
	return err
}

// Input is interleaved int16 PCM. Chunks may have any length; the
// encoder buffers internally and returns completed ADTS frames.
var adts []byte
for chunk := range pcmChunks {
	out, err := enc.Encode(chunk)
	if err != nil {
		return err
	}
	adts = append(adts, out...)
}

// Flush is required: it drains the encoder's lookahead and emits the
// final frames. The encoder is unusable afterwards.
tail, err := enc.Flush()
if err != nil {
	return err
}
adts = append(adts, tail...)
// adts is a playable .aac (ADTS) stream.
Decoding
dec, err := aac.NewDecoder()
if err != nil {
	return err
}

// Input may be sliced at arbitrary byte boundaries (e.g. network
// reads); partial frames are buffered until complete. Each call
// returns the PCM decoded so far, interleaved int16.
var pcm []int16
for chunk := range adtsChunks {
	out, err := dec.Decode(chunk)
	if err != nil {
		return err
	}
	pcm = append(pcm, out...)
}

// The stream format is detected from the first ADTS header.
sampleRate, channels := dec.SampleRate(), dec.Channels()
Error handling

Streams using features outside the supported subset (HE-AAC/SBR, surround, ...) fail with a wrapped aac.ErrUnsupported naming the feature — never silently wrong audio:

if _, err := dec.Decode(data); errors.Is(err, aac.ErrUnsupported) {
	// e.g. "AAC feature is not supported: HE-AAC/SBR extension ..."
}
Notes
  • The codec delay is aac.SamplesPerFrame (1024) samples: the decoded stream starts with 1024 samples of windowed lead-in per channel, and the tail is zero-padded to a frame boundary. Align by this offset when comparing against the source.
  • Encoder and decoder are not safe for concurrent use; use one instance per stream (instances are cheap).
  • A minimal 16-bit PCM WAV reader/writer ships as the github.com/arabian9ts/aac-go/wav subpackage for tooling and tests.
CLI
go run ./cmd/aacenc -quality 0.6 input.wav output.aac
go run ./cmd/aacdec output.aac roundtrip.wav

Testing

Three layers, each one command (CI runs exactly these — see .github/workflows/ci.yml, which is a thin wrapper any CI system can copy):

  1. go test ./... — hermetic; no external tools. Unit tests, synthetic roundtrips, and decoding of all committed real-world vectors (testdata/realworld: ffmpeg's encoder with each tool isolated, every sample rate, bitrate extremes, Apple's encoder, plus negative vectors that must fail with named errors) checked against committed RMS fingerprints. Runs in seconds.
  2. scripts/accept.sh — verification against a test oracle: an independent reference decoder used to judge correctness — ffmpeg by default, afconvert as an optional local macOS cross-check (ORACLE=afconvert). Both directions: our encoder's streams must be accepted with SNR gates, and our decoder must match the oracle's decode of the real-world vectors. The oracle is an external CLI invoked only during verification — the library itself has zero dependencies.
  3. go test -fuzz=FuzzDecode -fuzztime 60s . — time-boxed robustness exploration; found crashers are committed as regression seeds.

Test vectors are immutable once committed; scripts/genvectors.sh is the local curation tool that created them (generator versions recorded in its header) and is never run in CI.

License

Apache License 2.0 — see LICENSE.

AAC is a codec domain with a patent history. The Apache-2.0 license includes an express patent grant covering contributions to this project; it cannot and does not cover third-party patents. Evaluate your own patent position for commercial use.

Documentation

Overview

Package aac implements a streaming AAC-LC (ISO/IEC 14496-3) encoder and decoder in pure Go, producing and consuming ADTS streams.

See the README for the implemented subset and the extension seams: long windows only, mono SCE and stereo CPE, 44.1/48 kHz.

Index

Constants

View Source
const (
	// SamplesPerFrame is the AAC-LC frame length for a long window.
	SamplesPerFrame = 1024
)

Variables

View Source
var ErrEncoderFlushed = errors.New("AAC encoder has already been flushed")
View Source
var ErrUnsupported = errors.New("AAC feature is not supported")

ErrUnsupported reports a stream feature that is syntactically valid AAC but outside the currently implemented subset (see the README). The error message names the missing tool; extending support means implementing the tool, not changing callers.

Functions

This section is empty.

Types

type Config

type Config struct {
	SampleRate int
	Channels   int
	// Quality in [0, 1] trades bitrate for fidelity (VBR). It maps
	// linearly onto the encoder's uniform quantization noise floor.
	Quality float64
	// EnableTNS enables encoder-side Temporal Noise Shaping. It is opt-in and
	// best suited to transient-dominant material; it is not recommended for
	// tone-dominant material because this simple predictor can reduce its SNR
	// Decoding TNS is always enabled.
	EnableTNS bool
}

Config configures an AAC encoder.

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder incrementally decodes ADTS-framed AAC-LC data.

The stream format (sample rate, channel layout) is locked in by the first frame. Construct with NewDecoder.

func NewDecoder

func NewDecoder() (*Decoder, error)

NewDecoder returns an AAC streaming decoder. The format is detected from the first ADTS header seen by Decode.

func (*Decoder) Channels

func (d *Decoder) Channels() int

Channels returns the stream's channel count, or 0 before the first decoded frame.

func (*Decoder) Decode

func (d *Decoder) Decode(data []byte) ([]int16, error)

Decode consumes ADTS bytes and returns the PCM decoded so far. Input may be sliced arbitrarily: a partial trailing frame is buffered until the remaining bytes arrive (ISO/IEC 14496-3 §1.A.3 adts_frame).

func (*Decoder) SampleRate

func (d *Decoder) SampleRate() int

SampleRate returns the stream's sample rate in Hz, or 0 before the first decoded frame.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder buffers interleaved PCM and emits ADTS frames.

Each 1024-sample block is transformed together with the previous block (50% MDCT overlap). Block switching needs one block of lookahead — a frame becomes LONG_START only when the *next* frame is known to hold a transient — so a frame is emitted when the block after it arrives, and Flush drains the pipeline plus the final MDCT tail.

func NewEncoder

func NewEncoder(config Config) (*Encoder, error)

NewEncoder validates config and returns an AAC-LC streaming encoder.

func (*Encoder) Encode

func (e *Encoder) Encode(pcm []int16) ([]byte, error)

Encode consumes interleaved PCM of any length and returns the ADTS frames completed by this call, concatenated. Because of the one-block lookahead, the first frame is returned once the second block is complete.

func (*Encoder) Flush

func (e *Encoder) Flush() ([]byte, error)

Flush zero-pads a partial block, drains the lookahead pipeline, and appends one final frame covering the MDCT tail of the last block. Repeated calls, or Encode after Flush, return ErrEncoderFlushed.

Directories

Path Synopsis
Package adts builds and parses Audio Data Transport Stream headers.
Package adts builds and parses Audio Data Transport Stream headers.
cmd
aacdec command
Command aacdec decodes an ADTS .aac stream into a 16-bit PCM WAV file.
Command aacdec decodes an ADTS .aac stream into a 16-bit PCM WAV file.
aacenc command
Command aacenc encodes a 16-bit PCM WAV file into an ADTS .aac stream.
Command aacenc encodes a 16-bit PCM WAV file into an ADTS .aac stream.
internal
bits
Package bits implements the MSB-first bit I/O used by AAC syntax elements.
Package bits implements the MSB-first bit I/O used by AAC syntax elements.
coder
Package coder implements the quantization and entropy-coding layer shared by the AAC encoder and decoder: scalefactor and spectral Huffman codes (ISO/IEC 14496-3 §4.6.3) and the inverse quantizer (§4.6.2).
Package coder implements the quantization and entropy-coding layer shared by the AAC encoder and decoder: scalefactor and spectral Huffman codes (ISO/IEC 14496-3 §4.6.3) and the inverse quantizer (§4.6.2).
tables
Package tables contains data tables shared by the AAC codec stages.
Package tables contains data tables shared by the AAC codec stages.
transform
Package transform implements the modified discrete cosine transform pair used by AAC (ISO/IEC 14496-3 §4.6.11) together with the window functions applied around it.
Package transform implements the modified discrete cosine transform pair used by AAC (ISO/IEC 14496-3 §4.6.11) together with the window functions applied around it.
Package wav provides a minimal RIFF/WAVE reader and writer for 16-bit little-endian PCM.
Package wav provides a minimal RIFF/WAVE reader and writer for 16-bit little-endian PCM.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL