m4a

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT, MIT 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 m4a demuxes MPEG-4 Audio into access units for the audio decoder.

Index

Constants

View Source
const DefaultMaxBoxBuffer = 256 << 20

DefaultMaxBoxBuffer is the default ceiling, in bytes, on how much a single box body (moov, ftyp, or a fragment's moof) the reader will allocate and read for untrusted input. It bounds the memory a crafted file can drive the reader to allocate up front: every box length is already bounded by the stream length, but a sparse file can report a large stream length while backing almost none of it, so a body declared at several gigabytes would otherwise allocate that much before the (sparse, zero-filled) read succeeds. 256 MiB clears any realistic container by a wide margin (even a full day of AAC keeps its moov to a few tens of megabytes) while keeping a hostile allocation bounded. Override it per reader with WithMaxBoxBuffer, including WithMaxBoxBuffer(0) to lift the cap entirely.

Variables

View Source
var (
	// ErrCorrupt indicates malformed MP4 metadata or invalid sample extents.
	ErrCorrupt = errors.New("go-m4a: corrupt container")
	// ErrUnsupported indicates an MP4 feature this reader cannot demux.
	ErrUnsupported = errors.New("go-m4a: unsupported container")
	// ErrBoxTooLarge indicates that a box exceeds the configured read limit.
	ErrBoxTooLarge = errors.New("go-m4a: box body exceeds buffer limit")
	// ErrSampleLimit indicates that a track exceeds the decoder's sample budget.
	ErrSampleLimit = errors.New("go-m4a: sample count exceeds limit")
	// ErrOutOfRange indicates that the requested sample or time is outside the track.
	ErrOutOfRange = errors.New("go-m4a: seek position out of range")
)

Functions

This section is empty.

Types

type Info

type Info struct {
	// SampleRate is the audio sample rate in Hz, derived from the ASC and, when
	// the ASC does not carry an explicit rate, the mp4a AudioSampleEntry.
	SampleRate int

	// Channels is the channel count, normally 1 (mono) or 2 (stereo).
	Channels int

	// ASC is the MPEG-4 AudioSpecificConfig. Info returns a copy.
	ASC []byte

	// FrameCount is the number of access units (MP4 "samples") in the track.
	FrameCount int

	// EncoderDelay is the media tick presented first: the media_time of the first
	// non-empty edit in the edit list, or 0 if no edit applies. Leading
	// empty edits (media_time -1) do not zero it; they are StartOffset. It is the
	// number of leading decoded samples per channel to skip when the media
	// timescale equals the sample rate.
	EncoderDelay int64

	// Duration is the presented media length from the edit list window, excluding
	// any leading empty edit. Without an edit list it is the media length less
	// EncoderDelay, and a fragmented stream's
	// open-ended edit runs to the end of its fragments. Skipping EncoderDelay and
	// keeping Duration's worth of samples yields the presented audio, and
	// SeekTime accepts the times in [0, Duration), except that a time within half
	// a media tick of Duration rounds to the end and is refused. When SeekTime
	// reports ErrUnsupported for the edit list itself (several non-empty edits, a
	// trailing empty edit, a non-unit media rate, no non-empty edit, a media_time
	// below -1), Duration is the sum of the presented edits and that skip-and-keep
	// recipe does not reproduce the presentation.
	Duration time.Duration

	// StartOffset is the presentation time of the first presented sample: the
	// summed leading empty edits of the edit list. It is 0 for most files.
	StartOffset time.Duration

	// Brand is the ftyp major brand.
	Brand string
}

Info describes the selected MPEG-4 Audio track.

type Reader

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

Reader demuxes an progressive or fragmented MP4/M4A audio track into its access units, handling both a plain file (ftyp/moov/mdat) and a fragmented (CMAF) stream (an init segment followed by moof/mdat media segments). NewReader parses the moov metadata up front, and for a fragmented stream also lays out the samples the movie fragments carry; ReadFrameInto then returns each access unit in order from its computed (offset, size). Frames are read through a read-ahead window of up to 64 KiB, so a forward read seeks and reads once per window rather than once per access unit (a frame larger than half the window is read on its own), and the stream's bytes must not change after NewReader. NewReader itself reads box headers and small box bodies through a smaller window (openWindowSize) that it drops on return. The reader is not safe for concurrent use, and its frame methods share the same cursor.

func NewReader

func NewReader(r io.ReadSeeker, opts ...ReaderOption) (*Reader, error)

NewReader reads and parses the moov metadata from r and returns a Reader positioned at the first access unit. It locates moov whether it precedes or follows mdat, selects the first "soun" track carrying a supported sample entry (mp4a), and builds the sample geometry from the stsc/stsz/stco tables. When r is a fragmented (CMAF) stream (moof boxes present), it instead reads the init segment's sample entry and lays out the samples the movie fragments carry. It returns a wrapped ErrCorrupt for malformed input and a wrapped ErrUnsupported for well-formed input outside scope (no supported audio track, an unsupported codec, or an AAC object type that is not MPEG-4 Audio). A failure of the underlying reader is returned wrapped with its cause, and a stream that ends before the length its Seek from the end reported (a file cut short after that Seek) is a wrapped io.ErrUnexpectedEOF, not io.EOF.

Options tune the reader; WithMaxBoxBuffer sets how large a single box body may be before NewReader refuses it with a wrapped ErrBoxTooLarge, guarding against a sparse or truncated file that declares a body it does not physically back.

func (*Reader) Info

func (rd *Reader) Info() Info

Info returns a copy of the parsed track summary, including a fresh copy of the ASC so the caller cannot mutate the Reader's state.

func (*Reader) ReadFrameInto

func (rd *Reader) ReadFrameInto(dst []byte) (int, error)

ReadFrameInto reads the next access unit into dst and returns its length, advancing the cursor. The reader allocates its read-ahead window on the first frame read. If dst is too small, the method returns the required length and io.ErrShortBuffer without reading or advancing. It returns io.EOF at the end of the track and a different error for an unreadable frame.

func (*Reader) SeekSample

func (rd *Reader) SeekSample(sample int) error

SeekSample moves the running cursor to access unit sample (0-based, below Info().FrameCount) so that the next ReadFrameInto call returns that unit. It does no I/O: the position is computed from the sample tables already in memory, walking the chunk table to the chunk that holds the sample and summing the sizes before it within that chunk. Skipping ahead this way costs at most one seek and one window refill on the next read, and none when the target already lies in the read-ahead window, where reading through the skipped units transfers every byte in between. An index outside [0, Info().FrameCount) returns an error wrapping ErrOutOfRange and leaves the cursor unchanged.

It may be called at any point, including after the end of the stream. Start a new audio decoder after seeking because codec state does not carry across a jump.

func (*Reader) SeekTime

func (rd *Reader) SeekTime(d time.Duration) (sample int, skip int64, err error)

SeekTime moves the running cursor to the access unit that holds presentation time d, so the next ReadFrameInto call returns it, and reports how many decoded samples per channel to drop from the start of that unit's output to land exactly on d. It does no I/O: the unit comes from the timing table built at open (stts for a plain file, the trun durations for a fragmented stream) and the cursor move is SeekSample's.

Presentation time 0 is the first presented sample: media tick Info().EncoderDelay, the priming the edit list skips, after any leading empty edits (whose length is Info().StartOffset and is not part of the time axis). A seek to 0 selects the first sample a gapless player presents and SeekTime(d) selects the same sample as decoding from the start and dropping EncoderDelay plus d's worth of samples. d is rounded to the nearest media tick (halves up), so a time derived from a tick through a float or a truncated nanosecond count still lands on that tick's unit.

skip counts samples at Info().SampleRate. It equals the offset in media ticks whenever the media timescale equals the sample rate. Otherwise it is rescaled and rounded down. A unit with a zero duration is never returned.

The valid range is [0, Info().Duration): the window the edit list presents, the same one Info().Duration reports, so trailing padding is excluded. A d outside it, including the last half tick before the end, returns an error wrapping ErrOutOfRange with the cursor unchanged. A track with no sample timing, or whose edit list does not reduce to one presented window (more than one non-empty edit, a trailing empty edit, a non-unit media rate, no non-empty edit, a media_time below -1), returns an error wrapping ErrUnsupported for any d >= 0, also with the cursor unchanged; a negative d is always ErrOutOfRange. On any error the results are 0, 0.

SeekTime can be repeated or called after the end of the stream. For clean AAC output after a seek, start a new decoder a few access units earlier and discard the pre-roll as well as skip samples.

type ReaderOption

type ReaderOption func(*readerConfig)

ReaderOption configures a Reader at construction. Pass options to NewReader.

func WithMaxBoxBuffer

func WithMaxBoxBuffer(n int64) ReaderOption

WithMaxBoxBuffer sets the ceiling, in bytes, on how large a single box body may be before NewReader refuses it with a wrapped ErrBoxTooLarge. It applies uniformly to the moov and ftyp bodies and to each fragment's moof body. A value of 0 or less disables the cap, restoring the pre-limit behavior of allocating whatever length a box declares (still bounded by the stream length and, on a 32-bit build, by the addressable-slice ceiling). The default is DefaultMaxBoxBuffer.

func WithMaxSamples

func WithMaxSamples(n int64) ReaderOption

WithMaxSamples lowers the maximum number of access units indexed by the reader.

Directories

Path Synopsis
Package box parses ISO Base Media File Format boxes for the AAC demuxer.
Package box parses ISO Base Media File Format boxes for the AAC demuxer.

Jump to

Keyboard shortcuts

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