pcm

package
v0.7.3 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: LGPL-2.1 Imports: 9 Imported by: 0 modules, 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.

Documentation

Overview

Package pcm is the high-level PCM streaming API for go-aac: interleaved little-endian integer PCM in, an AAC-LC ADTS stream out via io.Writer (Encoder), or raw access units out through a callback for muxing into MP4 (FrameEncoder). It also decodes AAC-LC back to PCM (Decoder).

It is shaped exactly like go-flac's pcm package and go-opus' oggopus package, so a consumer can switch between the three encoders with the same call shape. The package name deliberately collides with go-flac/pcm; import it with an alias:

import aacpcm "github.com/Mag1cFall/go-aac/pcm"

Encoding

NewEncoder accepts any io.Writer and a Config. ADTS frames each access unit individually, so no io.WriteSeeker is ever needed and Close performs no finalization beyond draining:

enc, err := aacpcm.NewEncoder(f, aacpcm.Config{
    SampleRate: 48000,
    BitDepth:   16,
    Channels:   1,
    Bitrate:    96000,
})

Write accepts arbitrary chunk sizes: bytes that do not complete an inter-channel sample or a 1024-sample frame are buffered internally, so io.Copy works with any buffer size, including ones not divisible by the sample stride. The int-to-float conversion, 1024-sample framing, encoder priming and final-frame padding all happen internally.

Reuse and one-shot encoding

Encoder.Reset rebinds an existing encoder to a new sink and Config, reusing all internal buffers (about 650 KiB), so a producer that encodes many independent clips can pool encoders. EncodeInterleaved is the one-shot helper for a complete in-memory buffer; it draws from an internal pool and is safe for concurrent use:

err := aacpcm.EncodeInterleaved(w, cfg, pcmBytes)

Muxing into MP4

A caller putting AAC-LC into MP4 or fragmented MP4 (CMAF) needs the opposite of ADTS: raw access units, with their boundaries reported out of band. FrameEncoder is that path, and it is the same pipeline as Encoder, so the access units are byte-identical to the ADTS stream's payloads:

fe, err := aacpcm.NewFrameEncoder(cfg)
emit := func(au []byte, samples int) error {
    segment = append(segment, au...) // au is borrowed; copy or append
    return nil
}
err = fe.EncodeInterleaved(pcm, emit)
err = fe.Flush(emit) // drains the priming frame; without it the tail is lost

FrameEncoder.AudioSpecificConfig is the esds DecoderSpecificInfo, valid before any audio is encoded so an init segment can be built up front, and FrameEncoder.Delay is the priming count for the edit list media_time. Both it and the per-unit samples count are PCM samples per channel, so a muxer whose track timescale is not the sample rate (the usual choice for audio) scales them into media-timescale ticks first. The emit callback has the same shape as go-flac's pcm.FrameEncoder, so a muxer's per-unit path is shared between the two codecs; the lifecycle differs, since AAC-LC needs a Flush to drain the priming frame where the FLAC frame encoder is one-shot.

Note the two spellings of EncodeInterleaved: the package-level function is the one-shot ADTS helper below, while FrameEncoder.EncodeInterleaved is the streaming raw-access-unit method used here.

Every access unit decodes to aac.FrameSize samples, which is what a trun sample_duration carries once converted to the track timescale. That is also why sample-accurate trimming needs one number the encoder does not have: the caller feeding the PCM tracks the true input sample count and gives it to the muxer as the edit list segment duration, since the reported per-unit count cannot distinguish the padding in a short final frame.

Gapless playback

ADTS cannot signal the encoder delay (aac.EncoderDelay priming samples) or the final-frame padding, so decoders emit roughly aac.EncoderDelay extra leading samples and up to 1023 trailing ones. Every AAC-in-ADTS stream in the world behaves this way; players compensate or ignore it. Compute clip durations from the source PCM, not from decoded AAC length. Sample-accurate trimming needs a container with an edit list: use FrameEncoder with an MP4 muxer such as go-m4a.

Decoding

NewDecoder wraps an io.Reader and decodes an AAC-LC stream to interleaved little-endian S16 PCM. It mirrors go-flac's pcm.Decoder: NewDecoder, Info, Read (io.Reader), WriteTo (io.WriterTo) and Reset for pooling.

d, err := aacpcm.NewDecoder(r)
if err != nil {
    // classify with errors.Is against aacpcm.ErrCorruptStream or aacpcm.ErrUnsupported
}
info := d.Info() // SampleRate, Channels, Profile
_, err = io.Copy(w, d)

ADTS is the default: the framer locates the 0xFFF syncword, resyncs past leading or mid-stream garbage, reads each frame by its ADTS length and reconstructs it. Info is valid immediately after NewDecoder, which peeks the first header. Raw access units described by an AudioSpecificConfig are opt in through WithRawStream; raw carries no syncword, so the units are length-prefixed (2-byte big-endian, a go-aac framing convention).

The S16 output is the decoder's native S32P samples shifted right by 16, which is byte-identical to "ffmpeg -c:a aac_fixed -f s16le" under bitexact, including Apple afconvert LC streams. Malformed input never panics: the API is recover-free and returns wrapped ErrCorruptStream or ErrUnsupported sentinels (testable with errors.Is). A truncated final frame delivers every complete frame and then reports ErrCorruptStream. A mid-stream sample-rate or channel change is reported as ErrUnsupported after the first configuration's frames, because a single interleaved s16le stream cannot signal the change (the C decoder re-initializes instead, which a future segmented API could match). A pooled Decoder decodes at zero allocations per frame in steady state.

Concurrency

An Encoder is not safe for concurrent use; use one per goroutine, and the same holds for a FrameEncoder and a Decoder. The package-level EncodeInterleaved function is safe for concurrent use.

SIMD kernels

Encoding here runs through the same kernels as the aac package, so the SIMD kernels the default build links reach the encoders here as well, and a -tags noasm build routes them through the scalar path instead (decoding is unaffected). Output is byte-identical either way; aac.SIMDEnabled reports which set was compiled in.

Index

Examples

Constants

View Source
const DefaultMaxDecodedBytes = 1 << 30

DefaultMaxDecodedBytes is the ceiling DecodeInterleaved applies to its output. The one-shot helpers hold the whole decode in memory, so they stop here rather than let a long or crafted stream drive an unbounded allocation. It is 1 GiB, about 101 minutes of 48 kHz stereo S16.

A caller decoding a stream it did not produce, or one legitimately longer than this, should use NewDecoder and stream the audio instead, which bounds memory to a single reusable buffer regardless of length.

Variables

View Source
var (
	// ErrCorruptStream reports malformed input: a missing syncword with no
	// resync, a bad header field, an overread, or a truncated frame.
	ErrCorruptStream = errors.New("go-aac/pcm: corrupt stream")
	// ErrUnsupported reports well-formed input outside the AAC-LC mono/stereo
	// scope (non-LC object types, channel configs > 2, SBR/PS, 960-sample
	// frames, mid-stream config changes).
	ErrUnsupported = errors.New("go-aac/pcm: unsupported stream")
	// ErrUnsupportedSBR reports HE-AAC (AAC-LC + SBR), signalled in the ASC or
	// a leading fill element. It wraps ErrUnsupported, and ErrUnsupportedPS
	// wraps it in turn, so errors.Is(err, ErrUnsupportedSBR) catches the whole
	// HE-AAC family (SBR and SBR+PS); test it to hand the stream to an external
	// decoder deliberately.
	ErrUnsupportedSBR = fmt.Errorf("%w: SBR (HE-AAC)", ErrUnsupported)
	// ErrUnsupportedPS reports HE-AACv2 (AAC-LC + SBR + PS). Because PS implies
	// SBR it wraps ErrUnsupportedSBR (and thus ErrUnsupported); test
	// ErrUnsupportedPS to distinguish HE-AACv2 from plain HE-AAC. PS is
	// detected only from ASC signalling; an ADTS HE-AACv2 stream surfaces as
	// ErrUnsupportedSBR.
	ErrUnsupportedPS = fmt.Errorf("%w + PS (HE-AACv2)", ErrUnsupportedSBR)
)

Sentinel decode errors, testable with errors.Is. They wrap the internal dec sentinels so a caller can branch on class without importing internal packages.

View Source
var ErrDecodeLimit = errors.New("go-aac/pcm: decoded size limit exceeded")

ErrDecodeLimit reports that a one-shot decode was stopped because its output would exceed the byte ceiling in effect. Test for it with errors.Is. See DefaultMaxDecodedBytes for why the limit exists.

Functions

func EncodeInterleaved

func EncodeInterleaved(w io.Writer, cfg Config, pcm []byte) error

EncodeInterleaved encodes a complete interleaved little-endian PCM buffer to an ADTS stream on w in a single call, centralizing the NewEncoder/Write/Close sequence. It draws an Encoder from an internal sync.Pool, so repeated calls are allocation-light, and it is safe for concurrent use.

Unlike Write, the one-shot buffer must hold a whole number of inter-channel samples for cfg; a trailing partial sample is an error before any sink write (go-flac semantics).

Example

ExampleEncodeInterleaved encodes a complete in-memory PCM buffer in one call, the BirdNET-Go pattern. The import is aliased because the package name deliberately matches go-flac's pcm package.

package main

import (
	"bytes"
	"fmt"
	"log"

	aacpcm "github.com/Mag1cFall/go-aac/pcm"
)

// countADTSFrames walks the self-framing ADTS stream by its 13-bit frame
// length fields.
func countADTSFrames(stream []byte) int {
	n := 0
	for len(stream) >= 7 {
		if stream[0] != 0xFF || stream[1]&0xF0 != 0xF0 {
			return -1
		}
		frameLen := int(stream[3]&0x03)<<11 | int(stream[4])<<3 | int(stream[5])>>5
		if frameLen < 7 || frameLen > len(stream) {
			return -1
		}
		stream = stream[frameLen:]
		n++
	}
	return n
}

func main() {
	// One second of silent 16-bit mono PCM at 48 kHz.
	pcm := make([]byte, 48000*2)

	var buf bytes.Buffer
	err := aacpcm.EncodeInterleaved(&buf, aacpcm.Config{
		SampleRate: 48000,
		BitDepth:   16,
		Channels:   1,
		Bitrate:    96000,
	}, pcm)
	if err != nil {
		log.Fatal(err)
	}
	// 47 input frames (the last one padded) plus one frame covering the
	// encoder delay.
	fmt.Println(countADTSFrames(buf.Bytes()), "ADTS frames")
}
Output:
48 ADTS frames

Types

type ASCInfo

type ASCInfo struct {
	ObjectType int
	SampleRate int
	Channels   int
	SBR, PS    bool
}

ASCInfo describes an MPEG-4 AudioSpecificConfig: the audio object type, the sample rate in Hz, the channel count, and whether SBR or PS is signalled.

func ParseASC

func ParseASC(asc []byte) (ASCInfo, error)

ParseASC parses an AudioSpecificConfig for a probe or codec-support decision before decoding, so a consumer can name the exact codec in an "unsupported" message instead of failing at the first frame. For AAC-LC it returns the object type, sample rate and channel count with a nil error. For a configuration this decoder cannot handle it returns a typed error, testable with errors.Is: ErrUnsupportedSBR for HE-AAC, ErrUnsupportedPS for HE-AACv2, and ErrUnsupported for a non-LC object type, a channel config above two, a PCE-configured stream (channel config zero), or 960-sample frames; malformed or truncated input returns ErrCorruptStream. On an ErrUnsupported result the returned ASCInfo is populated on a best-effort basis, so a caller may inspect the object type and the SBR/PS flags of a rejected config. On ErrCorruptStream it is the zero value, because a truncated header parses only overread garbage (an empty buffer would otherwise report sample-rate index 0, 96 kHz).

Example

ExampleParseASC probes an AudioSpecificConfig before decoding, so an unsupported codec is named up front instead of failing at the first frame.

package main

import (
	"errors"
	"fmt"
	"log"

	aacpcm "github.com/Mag1cFall/go-aac/pcm"
)

func main() {
	// A stereo AAC-LC config (an MP4 esds DecoderSpecificInfo).
	info, err := aacpcm.ParseASC([]byte{0x12, 0x10})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("AAC-LC=%v, %d Hz, %d ch, SBR=%v PS=%v\n",
		info.ObjectType == 2, info.SampleRate, info.Channels, info.SBR, info.PS)

	// HE-AAC (SBR) surfaces as a typed error the caller can branch on.
	if _, err := aacpcm.ParseASC([]byte{0x2b, 0x92, 0x08, 0x00}); errors.Is(err, aacpcm.ErrUnsupportedSBR) {
		fmt.Println("second stream is HE-AAC, unsupported")
	}
}
Output:
AAC-LC=true, 44100 Hz, 2 ch, SBR=false PS=false
second stream is HE-AAC, unsupported

type Config

type Config struct {
	// SampleRate is the input sample rate in Hz: 44100 or 48000 in v1.
	// Required; there is no zero default.
	SampleRate int
	// BitDepth is the input PCM bit depth: 16, 24 or 32 (signed integer,
	// little-endian, interleaved). Required; there is no zero default.
	BitDepth int
	// Channels is 1 or 2. Required; there is no zero default.
	Channels int

	// Bitrate is the ABR target in bits per second for the whole stream
	// (all channels), e.g. 128000. Zero selects aac.DefaultBitrate.
	// Targets above the AAC buffer model ceiling (6144
	// bits per channel per 1024-sample frame) are clamped, exactly as the
	// C encoder clamps them; negative targets are rejected.
	Bitrate int

	// Cutoff, when > 0, overrides the automatic coding bandwidth in Hz
	// (FFmpeg -cutoff equivalent). It must not exceed SampleRate/2. Leave
	// it 0 for the tuned rate-dependent default.
	Cutoff int

	// Coder selects the quantizer search strategy. The zero value is
	// aac.CoderNMR, the noise-to-mask-ratio scalefactor trellis and
	// upstream's default at the pin.
	//
	// The alternatives are not simply "faster and cheaper": aac.CoderFast
	// is the fastest on any material, but aac.CoderTwoLoop is faster than
	// aac.CoderNMR only on broadband material and is several times slower
	// on tonal material. The coders also code to slightly different
	// bandwidths when Cutoff is 0. See aac.Coder for the measurements.
	Coder aac.Coder
}

Config controls encoder output. It is a flat struct mirroring go-flac's pcm.Config and go-opus' oggopus.Config: every field's zero value is documented, so a literal with only SampleRate, BitDepth and Channels set is a complete, valid configuration.

type Decoder

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

Decoder decodes an AAC-LC stream into interleaved little-endian S16 PCM. It implements io.Reader and io.WriterTo, mirroring go-flac's pcm.Decoder shape (NewDecoder, Info, Read, WriteTo, Reset).

A Decoder is not safe for concurrent use.

func NewDecoder

func NewDecoder(r io.Reader, opts ...Option) (*Decoder, error)

NewDecoder reads enough of r to establish the stream configuration and returns a Decoder with Info populated. For ADTS input it resyncs past any leading garbage to the first valid frame header. A nil reader, a stream with no decodable frame, or an unsupported configuration returns an error.

func (*Decoder) Info

func (d *Decoder) Info() Info

Info returns the stream configuration. Valid after NewDecoder or Reset.

func (*Decoder) Read

func (d *Decoder) Read(p []byte) (int, error)

Read fills p with interleaved little-endian S16 PCM. It returns (0, io.EOF) at a clean stream end and returns any latched terminal error on every later call.

func (*Decoder) Reset

func (d *Decoder) Reset(r io.Reader, opts ...Option) error

Reset rebinds the Decoder to a new source and reconfigures it, reusing the internal buffers and the internal decoder's allocations so a consumer that decodes many clips can pool decoders with zero per-stream allocation after warm-up.

func (*Decoder) WriteTo

func (d *Decoder) WriteTo(w io.Writer) (int64, error)

WriteTo drains all decoded PCM into w. It implements io.WriterTo so io.Copy(w, decoder) streams the whole decode with one call.

type Encoder

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

Encoder streams interleaved little-endian integer PCM (as []byte) to an AAC-LC ADTS stream on an io.Writer. It is shaped exactly like go-flac's pcm.Encoder and go-opus' oggopus.Encoder: a flat Config, NewEncoder(w, cfg), Reset(w, cfg) for pooling, Write/Close, and a one-shot EncodeInterleaved.

ADTS is self-framing (one 7-byte header per 1024-sample frame), so the Encoder is correct on a plain io.Writer with no seeking, no length known up front and no finalization step; Close only drains buffered samples. A caller muxing into MP4 instead of writing a stream wants the raw access units: use FrameEncoder, which Encoder is built on.

An Encoder is not safe for concurrent use, and must not be copied after first use: a copy shares the codec state and the scratch buffers with the original.

func NewEncoder

func NewEncoder(w io.Writer, cfg Config) (*Encoder, error)

NewEncoder validates cfg and returns an Encoder writing an ADTS stream to w. Unlike go-flac, no io.WriteSeeker is ever needed: ADTS has no stream-level header to patch. A config error returns immediately, before a byte is written.

Example

ExampleNewEncoder streams PCM of unknown length to any io.Writer; no seeking and no finalization beyond Close are ever needed.

package main

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"log"

	aacpcm "github.com/Mag1cFall/go-aac/pcm"
)

// countADTSFrames walks the self-framing ADTS stream by its 13-bit frame
// length fields.
func countADTSFrames(stream []byte) int {
	n := 0
	for len(stream) >= 7 {
		if stream[0] != 0xFF || stream[1]&0xF0 != 0xF0 {
			return -1
		}
		frameLen := int(stream[3]&0x03)<<11 | int(stream[4])<<3 | int(stream[5])>>5
		if frameLen < 7 || frameLen > len(stream) {
			return -1
		}
		stream = stream[frameLen:]
		n++
	}
	return n
}

func main() {
	var out bytes.Buffer
	enc, err := aacpcm.NewEncoder(&out, aacpcm.Config{
		SampleRate: 48000,
		BitDepth:   16,
		Channels:   2,
		Bitrate:    128000,
	})
	if err != nil {
		log.Fatal(err)
	}
	chunk := make([]byte, 4096) // any chunk size works, even odd ones
	for i := range 100 {
		binary.LittleEndian.PutUint16(chunk, uint16(i)) // not real audio
		if _, err := enc.Write(chunk); err != nil {
			log.Fatal(err)
		}
	}
	if err := enc.Close(); err != nil {
		log.Fatal(err)
	}
	fmt.Println(countADTSFrames(out.Bytes()), "ADTS frames")
}
Output:
101 ADTS frames

func (*Encoder) AudioSpecificConfig

func (e *Encoder) AudioSpecificConfig() []byte

AudioSpecificConfig returns the MPEG-4 AudioSpecificConfig for this stream (2 bytes for AAC-LC), the decoder configuration an MP4/M4A muxing layer needs. Valid after NewEncoder or Reset. It returns a fresh copy on every call; callers may retain or mutate it freely.

func (*Encoder) Close

func (e *Encoder) Close() error

Close encodes the final partial frame (zero-padded to a whole frame by the encoder), drains the one-frame encoder delay and flushes the last access units. The stream needs no finalization beyond this: ADTS has no stream-level state. Close is idempotent; Write after Close returns ErrEncoderClosed. It errors if buffered trailing bytes are not a whole number of inter-channel samples.

func (*Encoder) Delay

func (e *Encoder) Delay() int

Delay reports the encoder priming delay in samples per channel, the leading samples a muxer trims. ADTS cannot signal it, so it matters only to a caller that also muxes the same audio into a container; see FrameEncoder.Delay.

func (*Encoder) Reset

func (e *Encoder) Reset(w io.Writer, cfg Config) error

Reset rebinds the Encoder to a new sink w and reconfigures it with cfg so one Encoder can encode many independent streams without re-allocating; this is the pooling path for the many-short-clips workload. It re-validates cfg, discards buffered input and resets all per-stream state. After a successful Reset the encoder is ready for Write/Close as if freshly constructed; on error it must not be used. Reset may be called on a closed encoder, which is the usual pooling pattern (Reset, Write, Close, repeat).

func (*Encoder) Stats

func (e *Encoder) Stats() aac.Stats

Stats returns a snapshot of encoder tool usage (frames, short blocks, PNS/MS/IS/TNS band counts, mean lambda), mirroring the report FFmpeg's encoder prints at uninit. Call it after Close for whole-stream numbers; Reset clears it.

func (*Encoder) Write

func (e *Encoder) Write(p []byte) (int, error)

Write consumes interleaved little-endian PCM in arbitrary chunk sizes, exactly like go-flac: bytes that do not yet complete an inter-channel sample or a 1024-sample frame are buffered until the next Write or Close, so io.Copy works with any buffer size (including ones not divisible by the sample stride, e.g. 32 KiB chunks of 24-bit stereo). The produced stream depends only on the byte sequence, never on how it was chunked. Write returns len(p) on success; on a mid-write sink error it returns the number of bytes of p that were durably consumed (io.Writer contract).

type FrameDecoder

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

FrameDecoder decodes AAC-LC access units one at a time to interleaved little-endian S16 PCM, for a caller driven by a push-style OnFrame(au []byte) callback rather than an io.Reader. It is the demuxing counterpart of FrameEncoder: where the reader Decoder pulls a framed stream through Read and WriteTo, FrameDecoder takes the discrete access units a transport (RTSP, HLS, a container demuxer) already carved out and returns the PCM for each, with no io.Pipe or reader goroutine in between.

Two stream shapes are supported. NewADTSDecoder consumes self-describing ADTS frames (a 7-byte header, 9 with CRC, plus payload). NewRawDecoder consumes bare access units described out of band by an AudioSpecificConfig, the raw-stream case where the ASC arrives separately (an MP4 esds box, an RTSP OnCodecUpdate). Both decode through the same internal path as the reader Decoder, so the PCM is byte-identical to what Decoder produces for the same access units.

A FrameDecoder is not safe for concurrent use, and must not be copied after first use: a copy shares the codec state and the scratch buffers with the original.

func NewADTSDecoder

func NewADTSDecoder() *FrameDecoder

NewADTSDecoder returns a FrameDecoder for a stream of self-describing ADTS access units. The configuration (sample rate, channel count) is learned from the first frame, so SampleRate and Channels report zero until the first DecodeFrame; a mid-stream configuration change is then rejected as ErrUnsupported.

func NewRawDecoder

func NewRawDecoder(asc []byte) (*FrameDecoder, error)

NewRawDecoder returns a FrameDecoder for raw access units described by asc, an MPEG-4 AudioSpecificConfig (the DecoderSpecificInfo of an MP4 esds box, or the config an RTSP/HLS session signals out of band). It parses asc up front, so an unsupported stream is reported here rather than at the first frame: it returns the typed ErrUnsupported, ErrUnsupportedSBR or ErrUnsupportedPS for a non-LC object type, a channel config above two, or HE-AAC (SBR/PS). asc is copied, so the caller may reuse or mutate the buffer afterwards.

Example

ExampleNewRawDecoder decodes raw AAC-LC access units one at a time, the push-style OnFrame(au) shape a network transport (RTSP, HLS) drives, where the AudioSpecificConfig arrives out of band. Here the units are produced by a FrameEncoder to keep the example self-contained; in a real ingest they come from the transport. Passing pcm[:0] reuses one buffer, so steady-state decode does not allocate.

package main

import (
	"bytes"
	"fmt"
	"log"

	aacpcm "github.com/Mag1cFall/go-aac/pcm"
)

func main() {
	cfg := aacpcm.Config{SampleRate: 48000, BitDepth: 16, Channels: 1, Bitrate: 96000}
	fe, err := aacpcm.NewFrameEncoder(cfg)
	if err != nil {
		log.Fatal(err)
	}
	asc := fe.AudioSpecificConfig() // delivered to the decoder out of band
	var aus [][]byte
	collect := func(au []byte, _ int) error {
		aus = append(aus, bytes.Clone(au))
		return nil
	}
	if err := fe.EncodeInterleaved(make([]byte, 48000*2), collect); err != nil {
		log.Fatal(err)
	}
	if err := fe.Flush(collect); err != nil {
		log.Fatal(err)
	}

	d, err := aacpcm.NewRawDecoder(asc)
	if err != nil {
		log.Fatal(err)
	}
	var pcm []byte
	total := 0
	for _, au := range aus { // the OnFrame(au) callback body
		var n int
		if pcm, n, err = d.DecodeFrame(pcm[:0], au); err != nil {
			log.Fatal(err)
		}
		total += n
	}
	fmt.Printf("%d Hz, %d ch, %d samples/ch decoded\n", d.SampleRate(), d.Channels(), total)
}
Output:
48000 Hz, 1 ch, 49152 samples/ch decoded

func (*FrameDecoder) Channels

func (d *FrameDecoder) Channels() int

Channels reports the channel count (1 or 2), or zero before it is known. As with SampleRate, a raw decoder knows it from construction and an ADTS decoder from the first decoded frame.

func (*FrameDecoder) DecodeFrame

func (d *FrameDecoder) DecodeFrame(dst, au []byte) (out []byte, samples int, err error)

DecodeFrame decodes one access unit and appends the interleaved little-endian S16 PCM to dst, returning the grown slice and the per-channel sample count (always aac.FrameSize, 1024, for AAC-LC). Passing dst[:0] of a reused buffer decodes in place: once dst has grown to a frame's worth of PCM (aac.FrameSize * channels * 2 bytes) no further call allocates on the common path, so a steady-state consumer decodes allocation-free.

au is read-only and not retained. On error the returned slice is dst unchanged and the sample count is zero, and a decode error is one of the package sentinels (ErrCorruptStream for malformed input, including an access unit that carries no audio; ErrUnsupported and its SBR/PS refinements for a valid stream outside the AAC-LC scope), testable with errors.Is. A decode error does not consume decoder state: the failed unit leaves the configuration, overlap-add and PNS state untouched, so a caller may skip a corrupt access unit and decode the next, or Reset for a clean session. Calling DecodeFrame on a zero-value or nil FrameDecoder (one not built by a constructor) instead returns a non-sentinel initialisation error, which does not match those sentinels via errors.Is.

func (*FrameDecoder) Reset

func (d *FrameDecoder) Reset() error

Reset re-arms the decoder for a fresh session, reusing the codec allocations so a consumer that decodes many sessions can pool decoders. An ADTS decoder is returned to its pre-first-frame state, ready to learn the configuration of the next stream (not necessarily the same one, since ADTS is self-describing); a raw decoder is reconfigured from the retained ASC, so it stays bound to that configuration. A raw Reset can only fail if the retained ASC is unsupported, which NewRawDecoder already rejected, so in practice it returns nil.

func (*FrameDecoder) SampleRate

func (d *FrameDecoder) SampleRate() int

SampleRate reports the stream sample rate in Hz, or zero before it is known. A raw decoder knows it from construction; an ADTS decoder learns it from the first decoded frame.

type FrameEncoder

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

FrameEncoder streams interleaved little-endian integer PCM (as []byte) to RAW AAC-LC access units, reporting each unit through a callback instead of writing a framed stream. It is the muxing counterpart of Encoder: where Encoder wraps every access unit in an ADTS header and writes it to an io.Writer, FrameEncoder hands the bare unit to the caller, who carries it in a container (an MP4 or fragmented-MP4 mp4a track, Matroska, and the like) that describes the boundaries out of band. AudioSpecificConfig supplies the esds DecoderSpecificInfo and Delay the edit-list priming count.

The emit callback has the same shape as go-flac's pcm.FrameEncoder, so a muxer's per-unit path is shared between the two codecs. The lifecycle differs: AAC-LC needs a Flush to drain the priming frame, where the FLAC frame encoder is one-shot.

FrameEncoder shares its whole implementation with Encoder: the same carry buffer, the same integer-to-float32 conversion, the same 1024-sample framing, priming and drain. The access units are therefore byte-identical to the payloads of the ADTS stream Encoder would write for the same input and Config.

A FrameEncoder is not safe for concurrent use, and must not be copied after first use: a copy shares the codec state and the scratch buffers with the original.

func NewFrameEncoder

func NewFrameEncoder(cfg Config) (*FrameEncoder, error)

NewFrameEncoder validates cfg and returns a FrameEncoder ready to encode. A config error returns immediately, before any state is built.

Example

ExampleNewFrameEncoder collects raw access units for a muxer instead of writing a framed stream: the shape a fragmented-MP4 (CMAF) segmenter consumes for live HLS. The access unit is borrowed, so the segment buffer appends it rather than retaining the slice.

package main

import (
	"fmt"
	"log"

	aacpcm "github.com/Mag1cFall/go-aac/pcm"
)

func main() {
	fe, err := aacpcm.NewFrameEncoder(aacpcm.Config{
		SampleRate: 48000,
		BitDepth:   16,
		Channels:   1,
		Bitrate:    96000,
	})
	if err != nil {
		log.Fatal(err)
	}

	// The init segment's esds DecoderSpecificInfo and the edit list priming
	// count are both available before any audio is encoded.
	asc := fe.AudioSpecificConfig()

	var segment []byte // one CMAF segment's mdat payload
	var sizes []int    // per-sample sizes for the trun box
	emit := func(au []byte, samples int) error {
		segment = append(segment, au...) // copy: au is only valid until this returns
		sizes = append(sizes, len(au))
		// samples is the decoded length in PCM samples per channel, always
		// 1024 for AAC-LC; scale it to the track timescale for trun.
		_ = samples
		return nil
	}

	pcm := make([]byte, 48000*2) // one second of silent 16-bit mono PCM
	if err := fe.EncodeInterleaved(pcm, emit); err != nil {
		log.Fatal(err)
	}
	if err := fe.Flush(emit); err != nil {
		log.Fatal(err)
	}

	// The encoded size is deliberately not printed: it tracks rate-control
	// decisions, and pinning it here would make this example churn on any
	// bitstream tweak. TestFrameEncoderGoldenAccessUnits is the bitstream anchor.
	fmt.Printf("ASC %x, delay %d samples, %d access units\n",
		asc, fe.Delay(), len(sizes))
}
Output:
ASC 1188, delay 1024 samples, 48 access units

func (*FrameEncoder) AudioSpecificConfig

func (e *FrameEncoder) AudioSpecificConfig() []byte

AudioSpecificConfig returns the MPEG-4 AudioSpecificConfig for this stream (2 bytes for AAC-LC), the DecoderSpecificInfo payload of an MP4 esds box. Valid immediately after NewFrameEncoder or a successful Reset, before any audio is encoded, so an init segment can be built up front; it is nil on a zero value or after a failed Reset, rather than describing the stream that Reset replaced. It returns a fresh copy on every call; callers may retain or mutate it freely.

func (*FrameEncoder) Delay

func (e *FrameEncoder) Delay() int

Delay reports the encoder priming delay in samples per channel: the leading samples a muxer trims, as an MP4 edit list media_time (scaled to the track timescale, which for audio is usually the sample rate) or an iTunSMPB priming field. It reads the delay from the underlying encoder, so a muxer holding a FrameEncoder never has to know the constant, and reports aac.EncoderDelay when there is no encoder to ask. Both branches return the same number today; the guard keeps aac.Encoder.Delay's freedom to dereference its receiver from becoming load-bearing here.

func (*FrameEncoder) EncodeInterleaved

func (e *FrameEncoder) EncodeInterleaved(pcm []byte, emit func(au []byte, samples int) error) error

EncodeInterleaved consumes interleaved little-endian PCM in arbitrary chunk sizes and calls emit once per complete access unit. Bytes that do not complete an inter-channel sample or a 1024-sample frame are buffered until the next call or Flush, so the emitted sequence depends only on the byte sequence, never on how it was chunked. It may be called any number of times; Flush ends the stream.

The au slice is BORROWED: it aliases an internal scratch buffer that the next emit overwrites, so a muxer copies it or appends it to its own segment buffer before returning. samples is the access unit's decoded length, always aac.FrameSize for AAC-LC including the zero-padded final frame; it carries no information about how much of that final frame was real input. It is passed for signature parity with go-flac's pcm.FrameEncoder, whose block sizes genuinely vary.

The encoder delays output by one frame (priming), so the first complete frame emits nothing; Flush drains it. An error from emit is returned unchanged and latched: no further access unit is emitted and every later call returns it until Reset.

func (*FrameEncoder) Flush

func (e *FrameEncoder) Flush(emit func(au []byte, samples int) error) error

Flush encodes the trailing partial frame (zero-padded to a whole frame by the encoder) and drains the one-frame encoder lookahead, so the final samples reach the caller. It ends the stream: Flush is idempotent and reports the same outcome on every later call, and EncodeInterleaved afterwards returns aac.ErrEncoderClosed. Reset re-arms the encoder for another stream.

A FrameEncoder that saw no input at all still flushes one all-silence access unit, so a muxed track is never empty. It errors if buffered trailing bytes are not a whole number of inter-channel samples, and reports aac.ErrEncoderClosed on a zero value or after a failed Reset. A nil emit callback is rejected without ending the stream, so the buffered tail survives for a Flush that supplies a real one.

func (*FrameEncoder) Reset

func (e *FrameEncoder) Reset(cfg Config) error

Reset rebinds the FrameEncoder to cfg so one encoder can encode many independent streams without re-allocating the roughly 650 KiB of codec state, and is the way to re-arm an encoder after a latched error or a Flush. It re-validates cfg, discards buffered input and resets all per-stream state. After a successful Reset the encoder is ready to encode as if freshly constructed; on error it is left unconfigured, and every method reports that until a later Reset succeeds.

func (*FrameEncoder) Stats

func (e *FrameEncoder) Stats() aac.Stats

Stats returns a snapshot of encoder tool usage (frames, short blocks, PNS/MS/IS/TNS band counts, mean lambda), mirroring the report FFmpeg's encoder prints at uninit. Call it after Flush for whole-stream numbers; Reset clears it.

type Info

type Info struct {
	SampleRate int    // Hz
	Channels   int    // 1 (mono) or 2 (stereo)
	Profile    string // always "AAC-LC" in v1
}

Info describes the decoded stream, populated at construction.

func DecodeInterleaved

func DecodeInterleaved(r io.Reader, opts ...Option) ([]byte, Info, error)

DecodeInterleaved reads an entire AAC-LC stream from r and returns the decoded interleaved little-endian S16 PCM together with the stream info. It is the one-shot mirror of EncodeInterleaved, and of the sibling one-shot decoders in the go-audio family (go-wav's, go-flac's and go-opus' pcm.DecodeInterleaved). The same options as NewDecoder apply, so WithRawStream decodes a raw stream plus its AudioSpecificConfig.

It stops at DefaultMaxDecodedBytes and returns a wrapped ErrDecodeLimit if the output would exceed it. For a different ceiling use DecodeInterleavedLimit; for a stream of unknown or unbounded length use NewDecoder, which streams the audio in memory proportional to a single buffer.

Like the streaming decoder, the output includes the roughly 1024 leading priming samples every AAC-in-ADTS stream carries; compute a clip's true duration from the source rather than from the decoded length.

func DecodeInterleavedLimit

func DecodeInterleavedLimit(r io.Reader, maxBytes int, opts ...Option) ([]byte, Info, error)

DecodeInterleavedLimit is DecodeInterleaved with a caller-chosen ceiling. maxBytes is the largest decoded output it will return; a decode that would exceed it stops and returns a wrapped ErrDecodeLimit. A maxBytes of zero or less removes the ceiling, which is only safe for a stream the caller produced or has otherwise bounded.

type Option

type Option func(*config)

Option configures a Decoder.

func WithRawStream

func WithRawStream(asc []byte) Option

WithRawStream configures the decoder for raw AAC access units described by the given AudioSpecificConfig instead of ADTS. Raw streams carry no syncword, so this explicit opt-in is required; without it NewDecoder treats the input as ADTS. The raw access units are length-prefixed (2-byte big-endian, the go-aac framing convention); see the package docs for the framing contract.

Jump to

Keyboard shortcuts

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