Repository navigation
Releases
v0.9.0
Info.EncoderDelay is now always a sample count, and is clamped to the media.
Info.EncoderDelay used to be the edit list media_time in media timescale ticks. Callers trim with it as a number of decoded samples, which is only right when the media timescale equals the sample rate, and a crafted version 1 elst could push it close to math.MaxInt64. The writer is unchanged and emits the same bytes as v0.8.0.
Changed
EncoderDelay is in samples. Info.EncoderDelay is the number of decoded samples per channel at Info.SampleRate to skip. When the media timescale differs from the sample rate, an edit list media_time is rescaled and rounded down, the same rounding SeekTime uses for its skip. The value is unchanged for every file whose media timescale equals the sample rate, which covers every file this package writes. The Opus pre-skip fallback is reported as written. (#91)
EncoderDelay is clamped to the media. An edit list media_time past the end of the media is clamped to the media length the sample table declares instead of being reported as written. A track that declares no media length (sample durations sum to zero and a zero mdhd duration) reports 0 for an edit list start. (#91)
Dependencies
The bridges now build against go-aac v0.7.2 and go-opus v1.4.0, and github.com/tphakala/simd moves to v1.16.0. Encoded output is unchanged. (#90)
Full changelog: v0.8.0...v0.9.0
v0.8.0
Read-ahead I/O for the reader, and read errors that keep their cause.
This release changes how the Reader talks to its source. Frame reads and NewReader's own box reads now go through small read-ahead windows, so a forward decode makes about one Seek and one Read per 64 KiB instead of one of each per access unit, and opening a long fragmented stream makes about half the calls it did. Read failures are also classified differently: an I/O error keeps its cause instead of being reported as ErrCorrupt, and a stream that ends early is io.ErrUnexpectedEOF, never io.EOF. The writer is unchanged and emits the same bytes as v0.7.0.
Changed
Read errors keep their cause. A frame read that fails in Reader.ReadFrame, Reader.ReadFrameInto or Reader.RawStream, and in the bridges that read through them, no longer reports ErrCorrupt. The underlying reader's error is wrapped with %w, so errors.Is and errors.As reach it (for example an *fs.PathError). Frame errors in the container itself, such as a zero length or an extent outside the stream, are still ErrCorrupt. Code that matched ErrCorrupt to catch I/O failures during frame reads should check for the cause instead. (#77, #82)
A stream that ends early is io.ErrUnexpectedEOF. No Reader read that runs out of bytes inside the stream length measured at open matches io.EOF, which callers take as the clean end of frames. This holds for frame reads and, new in this release, for NewReader's own reads: a file cut short after NewReader measured its length now fails with a wrapped io.ErrUnexpectedEOF, and the message ends in unexpected EOF instead of EOF. Through aacm4a.NewDecoder, go-aac reports a truncated stream as aacpcm.ErrCorruptStream with io.ErrUnexpectedEOF still in the chain; aacm4a.NewSeekableDecoder returns the wrapped io.ErrUnexpectedEOF. (#81, #86)
for {
au, err := rd.ReadFrame()
if errors.Is(err, io.EOF) {
break // every frame read
}
if errors.Is(err, io.ErrUnexpectedEOF) {
return fmt.Errorf("file shrank while reading: %w", err)
}
if err != nil {
return err // I/O cause, or ErrCorrupt for a malformed frame
}
use(au)
}Frame read-ahead window. Reader reads access units through a 64 KiB window instead of one Seek and one Read per access unit, and so do the aacm4a, opusm4a and flacm4a decoders. A forward decode of an 833 KiB AAC file of 1414 frames makes about 13 Seek and 13 Read calls instead of 1414 of each. Each Reader holds one buffer of up to 64 KiB, allocated on the first frame read; a frame larger than half the window is read on its own. An in-memory source such as a bytes.Reader pays one extra copy per frame. After SeekSample or SeekTime, the next read refills from the target unless it already lies in the window. (#80, #84)
Open-time read-ahead window. NewReader reads box headers, the ftyp and moov bodies and each moof body through a 4 KiB window that exists only while it runs. Opening a fragmented stream of 1800 segments makes about 3600 Seek and 3600 Read calls instead of about 7200 of each, and reads about 15 MB from the source instead of about 1 MB. A box body larger than 2 KiB, such as a large moov, is still read on its own. (#83, #85)
Dependencies
The bridges now build against go-aac v0.7.1, go-flac v1.4.0 and go-opus v1.3.0. github.com/tphakala/simd moves to v1.14.0. go.mod names only the Go minor version (go 1.27).
Full changelog: v0.7.0...v0.8.0
v0.7.0
Seekable AAC decoding, and reader options for the AAC bridge.
This release adds a seekable decoder to aacm4a that handles AAC pre-roll itself, so a caller can start decoding anywhere in a file and get output from the exact requested sample without decoding everything before it. aacm4a.NewDecoder also gains reader options. The root package and the writer are unchanged and emit the same bytes as v0.6.0.
Added
aacm4a.NewSeekableDecoder(r, opts...) returns an *aacm4a.Decoder that streams the same interleaved S16 PCM as NewDecoder and adds SeekSample and SeekTime. A seek positions the reader two access units early, restarts the AAC decoder, and on the next read decodes and drops the pre-roll and the in-frame skip, so output resumes exactly at the requested sample. SeekSample(i) starts output at access unit i; SeekTime(t) starts it at presentation time t, with the edit list and encoder priming already accounted for. Read, WriteTo and Info are also provided. Out-of-range seeks return m4a.ErrOutOfRange, and HE-AAC is rejected as with NewDecoder. (#75)
dec, info, err := aacm4a.NewSeekableDecoder(f, m4a.WithMaxBoxBuffer(64<<20))
if err != nil {
return err
}
if err := dec.SeekTime(90 * time.Second); err != nil {
return err
}
// dec.Read now returns S16 PCM starting exactly at 90 s.Trailing padding is not trimmed after a seek, matching NewDecoder; keep ceil(Duration*rate) - round(t*rate) samples per channel to stop at the presented end.
Changed
aacm4a.NewDecoder(r, opts ...m4a.ReaderOption) forwards reader options, for example m4a.WithMaxBoxBuffer, to the reader it builds. Existing calls compile unchanged and the return type is still *aacpcm.Decoder. (#75)
Known limitation
On a stream that uses perceptual noise substitution (PNS), the noise bands after a seek differ from a front-to-back decode of the same span, because the decoder's noise generator state cannot be recovered from a cold start. The sample position and length are still exact, and the difference is small (energy within about 0.1 dB in testing). Streams without PNS decode bit-exact against a linear decode. go-aac's own encoder uses PNS on noisy material, so expect this on files it produced.
Full changelog: v0.6.0...v0.7.0
go-m4a v0.6.0
Random access for the reader, and one consistent answer for where a track's audio starts and ends.
This release adds seeking to Reader: SeekSample jumps to an access unit by index and SeekTime jumps to a presentation time, both on plain and fragmented input. It also reworks how the reader interprets the edit list, so Info.EncoderDelay, Info.Duration, the new Info.StartOffset and the SeekTime bounds all come from one window resolved at open. Some files now report a different Duration; the cases are listed below. The writer is unchanged and emits the same bytes as v0.5.0.
Added
Reader.SeekSample(n) moves the read cursor to access unit n so the next ReadFrame, ReadFrameInto or RawStream read returns it. The position comes from the sample tables already in memory, so a jump costs one seek on the next read instead of one read per skipped unit, which matters on a network-backed source. An index outside [0, Info().FrameCount) returns the new ErrOutOfRange sentinel and leaves the cursor unchanged. By @vst93 (#69)
Reader.SeekTime(d) seeks to a presentation time and returns the access unit it landed on. Time 0 is the first presented sample, after the encoder priming. It finds the access unit holding that time from the stts or trun durations, moves the cursor there, and returns how many decoded samples per channel to drop from that unit for a sample-accurate start. A time before 0 or at or past the presented end returns ErrOutOfRange; a track with no sample timing, or an edit list that is not a single presented window, returns ErrUnsupported. (#71, #73)
sample, skip, err := rd.SeekTime(90 * time.Second)
if err != nil {
return err
}
// The cursor is at access unit `sample`. Recreate the decoder, decode from
// here and drop `skip` samples per channel from the first unit's output.Info.StartOffset reports the length of any leading empty edits, the presentation time of the first presented sample. It matches ffprobe's start_time and is 0 for most files. (#73)
Behavior changes
Info.Duration and Info.EncoderDelay come from one presented window. Before, the reader worked out the edit list in several places that did not always agree. They now share one resolver that parses the whole elst, with ffmpeg as the reference. For the same file, the reported values change in these cases (#73):
- A fragmented stream's
Durationno longer includes the encoder priming. 48 AAC frames at 48 kHz now report 1.002667 s instead of 1.024 s. - An Opus file without an edit list excludes the
dOpspre-skip fromDuration, as ffmpeg's decoder does. - A file without an edit list takes its length from the media itself instead of the rounded movie header duration, so a movie timescale that differs from the media timescale no longer matters.
- A leading empty edit becomes
StartOffset. It no longer zeroesEncoderDelayor stands in forDuration, andSeekTimenow supports these files. - An edit list with several non-empty edits reports their sum as
Duration.SeekTimereturnsErrUnsupportedfor it, and skippingEncoderDelayand keepingDurationdoes not reproduce such a presentation. - A plain file whose edit has
segment_duration0 presents nothing, as in ffmpeg. On a fragmented stream it still means "to the end". - A segment longer than the media is clipped to the media.
Durationis computed in integer arithmetic and rounds down to the nanosecond.
For files this package writes with the default settings, EncoderDelay and Duration are unchanged on the plain path. The fragmented path changes as described above.
An elst whose entry count overruns its body is rejected as ErrCorrupt. Such a file previously opened as long as its first entry was complete. (#73)
The ErrOutOfRange message is now "go-m4a: seek position out of range", since it covers seek times as well as sample indexes. Match it with errors.Is, not the string. (#71)
Requirements and dependencies
- Go 1.27 or newer is required. (#58)
aacm4abuilds against go-aac v0.7.0. (#59)- The indirect
simddependency is v1.11.0 andx/sysis v0.48.0. (#63)
Testing
A container integrity gate encodes a small corpus through each bridge and checks box layout, edit list trimming, sample-accurate decode and bit-exact FLAC against a pinned baseline, with ffmpeg cross-checks. In CI the ffmpeg interop tests now fail instead of skipping when ffmpeg is missing. New fixtures without an edit list, written by ffmpeg with a movie timescale that differs from the media timescale, pin Duration against ffprobe. The edit-list parser has its own fuzz target. (#67, #72, #73)
Migrating from v0.5.0
The changes are additive apart from the Duration values above. If you trim decoded PCM with EncoderDelay and Duration, check two things:
- If you read fragmented streams or Opus files without an edit list,
Durationnow excludes the priming. Drop any manual priming subtraction you added on top of it. - If you accept arbitrary input, call
SeekTime(or check its error) to tell whether the edit list is a single window. When it returnsErrUnsupportedfor the edit list, the skip-and-keep recipe does not apply.
Full changelog: v0.5.0...v0.6.0
go-m4a v0.5.0
Reader hardening for untrusted input, a fragmented-demux allocation cut, and a pinned HE-AAC contract.
This release is about reading input you did not write. NewReader gains a memory-budget ceiling on box-body allocation so a hostile or sparse file cannot drive a large heap allocation before its (zero-filled) read succeeds, the demuxer's HE-AAC error passthrough becomes a documented, test-pinned contract instead of an accident, and opening a fragmented stream allocates far less. The public API is additive: NewReader takes options now, source-compatible for every direct caller. One default changes runtime behavior, called out below.
Behavior change
NewReader now caps a single box body at 256 MiB by default. The reader allocates a box body to its declared length before reading it: readSection for moov and ftyp on the plain path, buildFragmentGeometry for each fragment's moof. Every length was already bounded by the stream length, but that is a logical bound, not a physical one. A sparse file can report a large stream length while backing almost none of it, so a body declared at several gigabytes drove a large allocation before the sparse read succeeded. NewReader(r, opts ...ReaderOption) now applies DefaultMaxBoxBuffer (256 MiB) to every caller, including the aacm4a, opusm4a and flacm4a bridges. A moov or moof body over the ceiling is rejected with the new ErrBoxTooLarge.
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. The cap is overridable per reader: WithMaxBoxBuffer(0) restores the exact pre-limit behavior, and a larger value raises the ceiling. The signature change is source-compatible for every direct caller, since the options are variadic. (#54)
Added
NewReader options: WithMaxBoxBuffer(n int) and the ReaderOption type. These set the per-box allocation ceiling described above. WithMaxBoxBuffer(0) disables the cap. (#54)
ErrBoxTooLarge, a standalone sentinel kept distinct from ErrCorrupt so a caller that set a strict limit can tell a memory-budget rejection from a malformed file. The guard sits below the existing 32-bit slice ceiling and is applied uniformly on the plain and fragmented paths. (#54)
A pinned HE-AAC contract. go-aac v0.6.0 added pcm.ErrUnsupportedSBR and pcm.ErrUnsupportedPS so a caller can tell an HE-AAC stream from any other unsupported input and route it to an external decoder. The container reader identifies the MPEG-4 Audio family from the esds object-type indication and does not verify the AAC profile, so an HE-AAC or HE-AACv2 track still reports CodecAACLC; aacm4a.NewDecoder is what rejects it, returning go-aac's typed sentinel unwrapped so errors.Is(err, pcm.ErrUnsupportedSBR) matches through the bridge. v0.4.0 noted this passthrough was accidental. It is now documented precisely on the Codec type, Info.Codec, NewDecoder and the README, and pinned with tests, so a later refactor that wrapped the error with %v instead of returning it would fail a test. (#52)
Performance
Opening a fragmented (CMAF) stream allocates far less. scanTopLevel reads each top-level box header into one reused buffer via Seek plus io.ReadFull instead of a fresh make per box, and buildFragmentGeometry carries one moof-body buffer grown to the largest fragment instead of allocating a fresh one per fragment. A comment at the reuse point pins the box.Trun records-aliasing invariant that makes the reuse sound: every Trun is created and fully consumed inside its fragment's walk, so nothing pointing into the buffer outlives the iteration. A body over 2 GiB is rejected as ErrCorrupt ahead of the make, so a 32-bit build cannot panic.
BenchmarkOpenFragmented, benchstat at n=10, p=0.000:
allocs/op 434 -> 34 -92%
B/op 111.6Ki -> 79.1Ki -29%
sec/op about -17.5%
Behavior is preserved for well-formed input. (#47, #48)
Internal
A new box.FindChild(payload, typ) consolidates the hand-rolled "walk the children, act on one FourCC" idiom at six single-child sites (parseEdts, minf to stbl, esds, dOps, dfLa, trafHeader). It walks the whole container so every child stays framing-checked even in a foreign traf whose body is otherwise skipped, and returns the first match. For well-formed single-instance input the behavior is identical to the per-callback walks it replaces; the only divergences are on malformed input (a duplicate target box, or a parse error masked by a later framing error), and both still reject as ErrCorrupt. The mvex/trex walk keeps its own loop because it aggregates one trex per track rather than finding a single child. (#47, #48)
Testing
New tests pin the box-buffer cap on both paths (TestMaxBoxBufferPlainPath, TestMaxBoxBufferFragmentedPath), asserting the ceiling is inclusive and that WithMaxBoxBuffer(0) disables it, and the HE-AAC contract (TestReaderLabelsHEAACAsAACLC, TestNewDecoderHEAACSentinels) by synthesizing SBR- and PS-signalled ASCs and asserting the typed sentinels pass through the bridge.
Two table-driven tests pin internal fragmented-demux guards that no existing test exercised. resolveBase is pinned so an explicit base_data_offset wins when a tfhd sets both base-data-offset-present and default-base-is-moof, an offset at the 1<<62 ceiling is accepted, and one above it is rejected as ErrCorrupt. addRun is pinned so a sample_count past the stream length is rejected as ErrCorrupt while a within-bound run is accepted. Both guards were previously invisible to the suite: swapping the resolveBase switch order, dropping its ceiling, or removing the addRun bound each left every test green. (#49)
Migrating from v0.4.0
The public API is purely additive. NewReader is now NewReader(r io.ReadSeeker, opts ...ReaderOption), which is source-compatible for every existing call. Two things to check:
// 1. The default 256 MiB box-body cap. A container whose moov or a moof
// body exceeds 256 MiB now returns a wrapped ErrBoxTooLarge. Raise or
// disable the ceiling if you read such input on purpose:
r, err := m4a.NewReader(f, m4a.WithMaxBoxBuffer(0)) // pre-v0.5.0 behavior
r, err := m4a.NewReader(f, m4a.WithMaxBoxBuffer(1<<30)) // 1 GiB ceiling
// 2. Distinguishing a memory-budget rejection from a malformed file:
if errors.Is(err, m4a.ErrBoxTooLarge) { /* over the cap */ }
if errors.Is(err, m4a.ErrCorrupt) { /* malformed */ }No dependency changes since v0.4.0. Requires Go 1.26, unchanged from v0.4.0.
go-m4a v0.4.0
A fragmented (CMAF) reader, multichannel and high-rate FLAC, Opus at its five source rates, and a streaming STREAMINFO contract.
The headline is symmetry: v0.3.0 could write fragmented MP4 but not read it. NewReader now auto-detects an initialization segment followed by moof/mdat media segments and demuxes it through the same API as a plain file, so a stream this package writes is a stream it can read back.
Two changes can break an existing caller, both narrow and both deliberate: the fragmented writer now rejects a deferred FLAC STREAMINFO at the constructor instead of writing a malformed init segment, and a FLAC track's rate and channel count are now read from STREAMINFO rather than the audio sample entry. Details below.
Breaking
The fragmented writer rejects a deferred FLAC STREAMINFO. InitSegment, NewFragmentWriter and FragmentWriter.Reset write the dfLa box up front and have no Close to defer to, so they cannot accept the placeholder that the plain Writer accepts. An empty block was already rejected; an all-zero 34-byte placeholder was not, and it produced a dfLa declaring rate 0 and 1 channel while the audio sample entry carried the configured rate and channel count. The two disagreed. Both deferred forms are now rejected by validateFragmentConfig through a shared isDeferredFLACStreamInfo predicate. This only rejects a config that previously produced malformed output, so it turns silent breakage into an explicit constructor error. The plain Writer is unchanged and still accepts the placeholder for its SetSTREAMINFO-at-Close path. (#39)
A FLAC track's Info.SampleRate and Info.Channels come from dfLa STREAMINFO, not the sample entry. For any file this package or another conforming muxer writes, the two agree and read-back is unchanged. They differ only for a foreign file that declared something else: a muxer may cap the sample-entry channelcount at 2 for a multichannel FLAC stream (the ISOBMFF legacy convention), and the 16.16 samplerate field cannot represent a rate above 65535 Hz at all. STREAMINFO is authoritative in both cases, and it matches the channel width and rate the decoder actually produces. (#4, #37)
Added
Fragmented (CMAF) demux in Reader. NewReader detects a moof-based stream and fills the same chunk-based sample geometry the plain path uses, so ReadFrame, ReadFrameInto and RawStream are unchanged and codec-generic across AAC-LC, Opus and FLAC. New internal/box parsers decode tfhd, tfdt, trex, tkhd and trun with full ISO/IEC 14496-12 flag handling. The walk resolves each run's base offset (base_data_offset or default-base-is-moof), maintains a running data cursor for a trun without data_offset, filters fragments to the selected audio track by track_ID so a muxed video traf is skipped, and resolves each sample's size and duration through the trun to tfhd default to trex default precedence. Info.Duration is recovered from the summed sample durations at the media timescale. Allocation is bounded to the input on every path: the per-record width times sample count is checked against the box body before anything is retained, and the running sample total is bounded against both the stream length and the platform int maximum, so a hostile sample_count cannot exhaust memory or panic on a 32-bit build. Previously fragmented input returned ErrUnsupported. (#41)
Writer.SetSTREAMINFO(streamInfo []byte), which supplies the 34-byte FLAC block late. m4a.NewWriter used to consume WriterConfig.STREAMINFO at construction while go-flac's StreamInfoBytes is only final after the whole encode, which forced flacm4a.EncodeInterleaved to buffer every frame of the clip in an arena. The dfLa box is not built until Close, so the writer never needed the block that early. validateFLACConfig now accepts an empty STREAMINFO at NewWriter as the deferred form, and Close requires a present 34-byte block for a FLAC track so a forgotten SetSTREAMINFO fails clearly. The bridge writes each frame straight from the go-flac callback. (#35)
FragmentWriter.Grow(samples, bytes int), a pure capacity hint for the cold path. FragmentWriter reaches zero allocations in steady state, but the first segment of every stream, and every Reset to a larger shape, paid the full growth chain from nil. Grow pre-reserves the sample, size and duration slices; it never changes the bytes a segment emits, clamps over-cap values to the per-segment caps, and panics on a negative argument. Reset now also releases an arena grown past a retention bound rather than pinning one pathological segment's peak for the life of a pool. (#13)
FLAC up to 8 channels. The shared writer channel guard is lower-bound-only and each per-codec validator enforces its own maximum, so FLAC accepts 1 to 8 (the RFC 9639 maximum) while AAC and Opus stay at 1 to 2. The whole write-read-decode path carries the true count, with 5.1 and 7.1 round trips in the suite. Opus surround stays out: the pinned go-opus exposes no multistream encoder or decoder, so a dOps with channel-mapping-family greater than 0 could not round-trip. That half of #5 is still open, blocked upstream. (#37)
FLAC sample rates above 65535 Hz, up to the 20-bit STREAMINFO maximum of 1048575 Hz. The 65535 ceiling was the 16.16 sample-entry field's limit applied to every codec; it moves into the per-codec validators, where it belongs. AAC still rejects 88200 and 96000 (table rates that do not fit, with no authoritative rate elsewhere) and Opus stays pinned to 48000. AppendFlacEntry writes a reduced power-of-two hint into the sample entry (96000 and 192000 to 48000, 88200 and 176400 to 44100), matching ffmpeg's MP4 muxer, while the true rate rides in STREAMINFO and the timescale. (#4)
Opus source rates other than 48 kHz. opusm4a.EncodeInterleaved accepts 8000, 12000, 16000, 24000 and 48000 Hz, frames the encoder input at sourceRate/50 samples per channel, flushes samplesPerChannel + enc.Lookahead(), records the true source rate in dOps InputSampleRate, keeps the container timescale at 48000 as Opus-in-ISOBMFF requires, and scales MediaLength into the 48 kHz domain. The 48 kHz path is byte-identical to v0.3.0. (#3)
Changed
Codec decode failures wrap m4a.ErrCorrupt. When go-flac or go-opus rejected the payload of a container the demuxer had already accepted, the bridges returned the raw codec error, so it did not wrap anything the caller could match. Such a file is corrupt at the codec layer, and those sites (including opus's defensive over-read guard) now wrap ErrCorrupt in the demuxer's style. (#32)
DecodeInterleaved returns nil for a track with no frames, where both bridges used to return a non-nil zero-length slice, so a caller checking pcm == nil or marshalling to JSON saw "" where it should see null. Only reachable from a foreign or crafted file, since the writer refuses to close a track with no frames. (#11)
A malformed box inside a foreign track fragment no longer fails Open. The demuxer now binds a traf to its track from the tfhd alone before parsing its runs, so a malformed trun or tfdt in a video traf is never decoded. This extracts one audio track; another track's internal framing is not its business to police. The reader's own arithmetic is guarded exactly as before: a traf still needs a parsable tfhd to bind at all, and every child box in every traf is still framing-checked. Two narrow error-precedence changes come with it, both tested: a traf that both lacks a base offset and carries a malformed tfdt or trun now reports the missing base (ErrUnsupported) where it reported the malformed box (ErrCorrupt), and among several runs the first geometry error wins where a later parse error used to. (#44)
Performance
flacm4a.EncodeInterleaved streams frames instead of buffering the clip: a 15-second clip falls from about 279 allocations and a few MB per encode to about 100 allocations and well under 1 MB. A pre-sized FragmentWriter cold segment drops from 28 allocations and 20 KB to 5 and 6 KB.
Opening a fragmented stream got cheaper twice over. scanTopLevel records each moof's extent from the header it has already parsed, so the geometry build no longer re-seeks and re-parses every moof header, and ParseTrun retains the record bytes with precomputed field offsets and decodes on demand instead of materializing a 24-byte struct per sample, which means it no longer allocates at all. Measured with BenchmarkOpenFragmented, interleaved against the base commit with benchstat at n=18:
sec/op 128.94µ -> 95.57µ -25.88% (p=0.000)
B/op 241.3Ki -> 111.6Ki -53.74% (p=0.000)
allocs/op 634.0 -> 434.0 -31.55% (p=0.000)
Every bound that guarded the old parser still guards the new one, and one now does double duty: recordWidth * SampleCount is still checked against the remaining box body before anything is retained, and passing that check is exactly what proves an accessor index stays in range, including on a 32-bit build where the product is compared as int64 first.
Internal
Writer.buildMoov and InitSegment each built the same trak/mdia/minf/stbl skeleton independently, so a box added to one path could silently describe the track differently from the other. They now share a moovSpec and one builder, with each caller supplying only what differs. Output is byte-identical on both paths across 16 codec and edit-list configurations. The soun track-selection loop, duplicated verbatim in the plain and fragmented paths, is shared for the same reason.
The reservation trim policy, which had become character-for-character identical in both bridges with the rule behind it documented nowhere, moves into a new leaf package internal/reservation that exports ShouldTrim, MaxRetainedSlack and MaxPCMReservation. The per-codec arithmetic genuinely differs a...
go-m4a v0.3.0
Bounded decoding, a fragmented (CMAF) writer, and a documented sample-rate contract.
This release contains one behaviour change that can break existing callers. flacm4a.DecodeInterleaved and opusm4a.DecodeInterleaved are now bounded: a stream decoding to more than 1 GiB returns an error instead of growing the buffer to fit. If you decode files longer than about 100 minutes of CD-quality stereo, see the migration note at the bottom.
Breaking
The accumulating decodes are bounded at m4a.DefaultMaxDecodedBytes (1 GiB). Both bridges used to loop until EOF appending every decoded frame into one buffer with nothing bounding the total. The decoded size of an audio file is not proportional to the file, so that was a memory-exhaustion surface for anything decoding input it did not produce: a FLAC constant subframe encodes a whole 65535-sample block in a handful of bytes, and a two-byte Opus packet of zero-length DTX frames decodes to 120 ms. Measured on fixtures now in the repo, a 1,812-byte crafted Opus file decodes to 4,608,000 bytes, a ratio of 2543:1.
It is not only an adversarial concern, which is why the default is generous rather than tight: sixty seconds of ordinary digital silence encodes to about 14 kB of FLAC and decodes back to 11.5 MB, a ratio of 831:1. A quiet field recording lands in the same place as a crafted one.
Exceeding the ceiling returns an error wrapping the new m4a.ErrDecodeLimit. The constant and the sentinel live in the core package so both bridges report the same error and one number governs both.
Added
DecodeStream(r, fn) in flacm4a and opusm4a, which hands each frame's PCM to a callback and accumulates nothing, so memory stays proportional to a single frame whatever the stream length. This is the shape to reach for with input you did not produce. The slice passed to the callback aliases a buffer the decoder reuses, so copy what you need to keep; an error from the callback stops the decode and comes back unchanged.
DecodeInterleavedLimit(r, maxBytes) in both bridges, which accumulates under a ceiling you choose. Zero or less means no limit, which restores the pre-v0.3.0 behaviour exactly.
A fragmented (CMAF) writer for live HLS and DASH: InitSegment builds the ftyp/moov initialization segment and FragmentWriter appends styp/moof/mdat media segments. It never seeks, so it can write straight into a byte slice or a socket, and it reuses its buffers, so a steady-state segment allocates nothing. Codec-generic like the rest of the writer, and validated against ffprobe.
m4a.DefaultMaxDecodedBytes and m4a.ErrDecodeLimit in the core package.
Performance
Both decode loops now read through Reader.ReadFrameInto into a buffer reused for the whole stream, grown geometrically only when a frame needs more room than any before it. Opus additionally packs into a reused byte buffer instead of growing its output two bytes at a time.
| benchmark | B/op | allocs/op |
|---|---|---|
| opus decode, mono | -82.4% | -92.7% (844 to 62) |
| opus decode, stereo | -82.4% | -92.9% (846 to 60) |
| flac decode, mono | -6.3% | -13.7% (1255 to 1083) |
| flac decode, stereo | -8.1% | -13.5% |
Decode time is unchanged within noise; the compiler confirms the new callback closures do not escape. DecodeStream allocates a constant amount regardless of stream length. The encode side also gained pre-sized buffers for the flacm4a PCM and frame slice and for the aacm4a ADTS output.
Documentation
The sample-rate contract is stated per codec, because it was never one rule. Four places disagreed about what the writer accepts. What it actually does: every codec is bounded by the AudioSampleEntry samplerate field, a 16.16 fixed-point value, so at most 65535 Hz; AAC-LC is additionally restricted to the eleven MPEG-4 sampling-frequency table rates that fit, 7350 through 64000, and must match the rate encoded in its ASC; Opus is pinned to 48000 by its encapsulation; FLAC has no rate table at all. Documented rather than narrowed, since restricting to 44100 and 48000 would have broken anyone on 32k, 24k or 16k for no correctness gain.
aacm4a now documents that it has no accumulating decode to bound, so a caller accumulating its streaming decoder's output owns that bound itself.
Testing
Seven fuzz targets now run bounded in CI, up from two: five new ones over the reservation arithmetic in both bridges, asserting that the result is a legal capacity, stays inside its ceiling whatever the file claims, stays inside a positive caller limit, and that a limit is a ceiling and never a floor. They need no fixtures and no codec, so they run at one to five million executions per second.
Round-trip coverage now spans every AAC rate the writer accepts rather than only 44.1 and 48 kHz, and the mp4a sample entry's samplerate field is asserted from the written bytes, which nothing in the repo had ever checked.
Two of the decode tests exist because mutation testing found the tests wrong rather than the code: changing DecodeInterleaved to delegate with no limit at all, which reverts the entire point of the bound, originally passed the whole suite in both packages.
Dependencies
Moved off untagged pseudo-versions onto tagged releases: go-aac v0.3.0, go-flac v0.4.3, go-opus v0.1.2. None of them changes what this package produces. aacm4a now uses go-aac's newly exported aac.DefaultBitrate instead of a local copy of the same value.
Migrating from v0.2.0
Only the two DecodeInterleaved functions changed behaviour, and only for streams decoding past 1 GiB (about 101 minutes of 44.1 kHz stereo 16-bit, 31 minutes of 24-bit 96 kHz, 15 minutes of 8-channel 24-bit). Three options:
// Keep the old unbounded behaviour, for input you produced or otherwise trust.
pcm, info, err := flacm4a.DecodeInterleavedLimit(r, 0)
// Or choose your own ceiling.
pcm, info, err := flacm4a.DecodeInterleavedLimit(r, 256<<20)
if errors.Is(err, m4a.ErrDecodeLimit) { /* longer than you allowed */ }
// Or decode without accumulating at all, which is what long or untrusted input wants.
info, err := flacm4a.DecodeStream(r, func(pcm []byte) error {
_, werr := w.Write(pcm) // pcm aliases a reused buffer: copy what outlives this call
return werr
})Everything else is additive. The reader, the writer, aacm4a, and both bridges' EncodeInterleaved are unchanged.
Full changelog: v0.2.0...v0.3.0
go-m4a v0.2.0
Opus and FLAC in MP4, alongside the existing AAC-LC support, via a codec-generic core (closes #1, #2).
What's new
- New
Codectype (CodecAACLC,CodecOpus,CodecFLAC) selects the track codec.CodecAACLCis the zero value, so existing AAC-LC writers are unchanged. The writer muxes Opus into anOpus/dOpssample entry and FLAC into anfLaC/dfLaentry; the reader demuxes both back. - New
opusm4aandflacm4abridge packages, mirroringaacm4a, wire go-opus and go-flac to the container. WriterConfiggainsCodecandCodecConfig;Info/TrackgainCodec,OpusPreSkip,OpusInputSampleRate, andSTREAMINFO. NewDefaultOpusPreSkipconstant.- Verified against ffmpeg- and afconvert-produced Opus and FLAC MP4s; new interop fixtures and fuzz coverage added.
Compatibility
Backward compatible with v0.1.x (additive API, no removals). Adds go-opus and go-flac module dependencies.
Full changelog: v0.1.1...v0.2.0