codec

package
v1.0.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 36 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

Audio codecs

audio.NewDecoder[T] pulls typed planar PCM from FLAC, MP3, RIFF/RF64/BW64 WAVE, AIFF/AIFC, ADTS AAC-LC, progressive or fragmented AAC-LC MP4, progressive ALAC MP4, and Matroska/WebM carrying PCM, FLAC, AAC, or Opus. AIFF, MP4, and Matroska use a seekable input. All decoding runs on the caller's goroutine. Import an individual format package, codec/all, or tracker/all to register the formats the application uses. AAC-LC in MP4 supports mono, stereo, and standard 5.1 (channel configuration 6). ADTS and mono or stereo MP4 AAC-LC return signed PCM with 16 valid bits. The 5.1 decoder returns float32 planes ordered front left, front right, center, LFE, back left, and back right. Its in-tree decoder uses BeatGlow PCM types. The source notice records its MIT decoder source and Apache-2.0 codebooks.

PCMFormat() returns an audio.Format with the sample rate, speaker order, and decoded encoding. ReadFrames fills caller-owned planes. NextBlock returns a read-only block that stays valid until the next read, seek, or close. Both advance the same decoder. The requested type T selects the output encoding. Integer PCM is right-justified. Floating-point output preserves headroom. The caller owns and closes the input. Seekable decoders can implement audio.FrameSeeker, while a known extent is available through audio.FrameCounter and audio.DurationSource.

Matroska can also carry AC-3 or E-AC-3. The Dolby decoder publishes planar float32 at the sample rate and speaker layout signaled by the first syncframe. E-AC-3 supports independent programs up to 5.1 at 32, 44.1, or 48 kHz, and 7.1 programs with a matching dependent rear pair or dependent replacement surrounds and rears. Other dependent layouts, reduced rates, and enhanced coupling return an unsupported-format error. See the Dolby source notice. Matroska TrueHD uses the same packet reader and returns signed 24-bit PCM in native speaker order, with fixture coverage from mono through 7.1. See the TrueHD source notice for the supported FBA syntax and synthetic fixture sources. Matroska DTS supports Core audio and single-band DTS-HD Master Audio. The lossless decoder handles independent and Core-dependent XLL channel sets, including frames spread across container packets. It decodes the channel-based bed of supported DTS:X streams. See the DTS source and fixture notes for lossless coding modes. The Core decoder also supports non-joint 6.1 XCh and 64-fold LFE interpolation. See the DTS Core fixture notes for the supported syntax. Supported track payloads use the MIT Matroska packet reader. PCM, FLAC, AAC, and single-stream Opus use the same packet path. Matroska AAC publishes planar float32. The decoder supports AAC-LC and HE-AAC v1/v2, including downsampled SBR and in-band parametric stereo on a declared stereo presentation. See the AAC source and fixture notes for the supported ASC and frame syntax. See the Opus source and fixture notes for supported Opus mappings and decoder provenance.

MOD (four-channel M.K.), XM, IT, S3M, STM, and MTM use stereo signed 16-bit PCM at 48 kHz by default. Pass audio.WithSampleRate(rate) to render a tracker at another rate or require a matching native file rate. Tracker decoding reads the module at open and renders one pass on demand. Its initial metadata includes the module title. Use the individual tracker packages to select a specific replay profile or repeat behavior.

XM supports FastTracker 2 XM 1.04 PCM with native effects and instrument envelopes. IT supports PCM sample and instrument modes, including note actions, envelopes and filter macros. The tracker packages expose optional FastTracker 2 and Impulse Tracker WAV replay settings. The verification guides describe the reference settings and comparison limits. XM verification and IT verification.

If a decoder cannot supply the requested rate directly, WithSampleRate resamples. Matching rates skip resampling. Converted frame counts, metadata positions, and seeks use the output rate. For seekable inputs, the converter calculates the native frame offset and reads the samples needed to restore filter history. Forward-only inputs remain forward-only.

The STM and MTM integration fixtures in testdata come from the STM generator and MTM generator.

Encoded format and metadata

codec.ReadSourceFormat inspects the encoded codec and native sample rate from the reader's current position. It restores a seekable reader's position. A nonseekable input can be consumed by up to 64 KiB. Header inspection works without decoder registration.

codec.ReadMetadata reads tags through an existing io.ReaderAt without changing the file position or decoding PCM. It returns a tag.Metadata snapshot. MP3 reads leading ID3v2 tags. FLAC reads Vorbis comments and picture blocks. WAVE reads RIFF INFO and embedded ID3, and AIFF reads native text and embedded ID3. Both chunk-based readers can report tags after the audio data. AAC and ALAC share the MP4 reader for file and selected-track metadata, including iTunes and keyed QuickTime tags and embedded covers. Matroska reads file and selected-track tags, album-level targets, and embedded image attachments. Use the tag keys for normalized lookups or Metadata.SourceTags for the original field names and values. Metadata.Artwork returns tag.Artwork descriptors. Call Artwork.Open to read the original encoded bytes through an independent reader. Close that reader after use. Keep file-backed inputs open until the artwork reader closes. When an older ID3 tag uses whole-tag unsynchronization, metadata scanning stops at the first image because the image bytes determine the positions of later frames. ID3v2.4 can skip the image using the frame size. An unsynchronized frame without a data length indicator reports a picture size of -1.

On forward-only inputs, decoders retain leading ID3 artwork and FLAC picture blocks as they pass through the stream. An artwork snapshot can be reopened after the decoder and stream close. Leading ID3 and WAVE tag buffering use a 16 MiB budget. FLAC artwork uses the decoder's 64 MiB metadata budget.

A decoder exposes an initial tag.Metadata snapshot via Metadata(). Call TakeMetadataUpdates() on the decoding goroutine to drain tag.Update values through the output already read. A successful seek replaces the pending updates with a snapshot at the new frame. Forward-only WAVE playback reports the tags before its audio data chunk.

For an HTTP body, pass the parsed ICY metadata interval and optional station name in audio.WithICY(interval, stationName). The decoder strips the metadata records as input arrives and delivers title changes at the following decoded block boundary. ICY positions are approximate. HTTP requests and input ownership stay with the caller. Progressive MP4 and Matroska still require a seekable source.

Benchmarks

We ran these benchmarks in BeatGlow Player before moving the codecs to BeatGlow Audio. We used Go 1.27.3, one scheduler thread, and seven runs per variant. The ARM64 host was an Apple M2 running macOS. The AMD64 host was an Intel N100 running Linux. Each result is the median for a five-second fixture held in memory. The benchmark target was 300 ms, or 250 ms for WAVE. The benchmark includes opening the reader and consuming the whole input. It excludes playback, disk and network I/O, and waveform rendering.

Reader and fixture ARM64 upstream to BeatGlow AMD64 upstream to BeatGlow Allocated bytes/op upstream to BeatGlow
FLAC v1.5.0, stereo 16-bit at 48 kHz 6.472 to 3.752 ms (42% lower) 8.810 to 6.565 ms (25% lower) 191,048 to 75,164
ALAC v1.0.0-rc3, stereo 16-bit at 48 kHz 8.587 to 7.199 ms (16% lower) 14.602 to 12.628 ms (14% lower) 173,992 to 98,088
MP3 v0.4.0, stereo at 44.1 kHz, 128 kb/s 8.845 to 8.527 ms (4% lower) 14.285 to 13.730 ms (4% lower) 126,505 to 65,712
MP3, mono at 22.05 kHz, 48 kb/s 3.926 to 3.795 ms (3% lower) 6.597 to 6.309 ms (4% lower) 119,145 to 65,712
WAVE v1.1.2, stereo 16-bit at 48 kHz 234 to 190 us (19% lower) 445 to 344 us (23% lower) 165,120 to 103,640
WAVE, 5.1 24-bit at 96 kHz 3.307 to 2.530 ms (23% lower) 6.674 to 4.850 ms (27% lower) 148,760 to 87,256
WAVE, stereo float32 at 48 kHz 496 to 429 us (14% lower) 1,011 to 756 us (25% lower) 132,360 to 70,872
M4A v0.8.0, progressive AAC-LC 11.90 to 11.77 us (1% lower) 23.06 to 23.32 us (1% higher) 81,504 to 81,464
M4A, fragmented AAC-LC 15.71 to 16.09 us (2% higher) 30.26 to 31.16 us (3% higher) 82,688 to 82,656

The FLAC, ALAC and AAC fixtures use seeded pink noise on one channel and an 881 Hz tone on the other. FLAC and ALAC baselines read upstream's packed PCM and consume the same signed samples as the BeatGlow planar callbacks. FLAC frame CRC checks are enabled in both variants. WAVE uses deterministic generated data. Its baseline deinterleaves upstream's packed output into reused planes before passing them to the same consumer.

The MP3 fixtures were encoded with libmp3lame from synthesized stereo tones and a 997 Hz mono sine. The upstream reader's float32 PCM and the BeatGlow callback matched sample-for-sample after normalization to signed 32-bit PCM. Both MP3 cases use five allocations per operation, down from twelve. The MP3 timing ranges overlap in repeated runs.

Both M4A readers fill a reused packet buffer and consume the same AAC access units without decoding them. The progressive reader saves two allocations per operation and the fragmented reader saves one. The timings are close to upstream.

Documentation

Overview

Package codec provides shared file-decoder support and reads tags and artwork.

Import the individual format packages to register native decoders with github.com/BeatGlow/audio, or import github.com/BeatGlow/audio/codec/all to register all built-in file codecs.

Index

Examples

Constants

View Source
const (
	CodecFLAC = "FLAC" // Free Lossless Audio Codec.
	CodecPCM  = "PCM"  // Uncompressed pulse-code modulation.
	CodecMP3  = "MP3"  // MPEG Audio Layer III.
	CodecAAC  = "AAC"  // Advanced Audio Coding.
	CodecALAC = "ALAC" // Apple Lossless Audio Codec.
)

Variables

This section is empty.

Functions

func ReadMetadata

func ReadMetadata(ctx context.Context, src io.ReaderAt, size int64) (tag.Metadata, error)

ReadMetadata reads tags and artwork descriptors without decoding PCM or changing the file position. The source remains caller-owned. Keep it open for any artwork readers obtained from the result. Malformed metadata can return the fields already collected alongside an error. A nil context returns audio.ErrNilContext.

Example
package main

import (
	"bytes"
	"context"
	"fmt"

	"github.com/BeatGlow/audio/codec"
	_ "github.com/BeatGlow/audio/codec/all"
)

func main() {
	// A minimal ID3 tag stands in for an open audio file.
	input := bytes.NewReader([]byte(
		"ID3\x03\x00\x00\x00\x00\x00\x14" +
			"TIT2\x00\x00\x00\x0a\x00\x00\x00Night Sky",
	))
	metadata, err := codec.ReadMetadata(context.Background(), input, input.Size())
	if err != nil {
		panic(err)
	}
	fmt.Println(metadata.Title())

}
Output:
Night Sky

func RegisterBuiltinFormat

func RegisterBuiltinFormat(name string)

RegisterBuiltinFormat installs a built-in file codec. Applications enable these codecs by importing their format packages. A name with no built-in codec panics.

Types

type SourceFormat

type SourceFormat struct {
	Codec        string
	SampleRateHz int
}

SourceFormat describes the codec and sample rate found in an audio header.

func ReadSourceFormat

func ReadSourceFormat(r io.Reader) SourceFormat

ReadSourceFormat reads the encoded codec and rate from r's current position. It leaves r open and restores the position of seekable inputs. A nonseekable input may be consumed by up to 64 KiB. Unrecognized or unreadable headers return a zero SourceFormat. No decoder imports are needed for this header inspection.

Directories

Path Synopsis
Package aac registers AAC in ADTS and MP4 with audio.
Package aac registers AAC in ADTS and MP4 with audio.
Package aiff registers AIFF and AIFC decoding with audio.
Package aiff registers AIFF and AIFC decoding with audio.
Package alac registers ALAC decoding with audio.
Package alac registers ALAC decoding with audio.
Package all registers all built-in file codecs with audio.
Package all registers all built-in file codecs with audio.
Package flac registers FLAC decoding with audio.
Package flac registers FLAC decoding with audio.
Package matroska registers Matroska and WebM audio decoding with audio.
Package matroska registers Matroska and WebM audio decoding with audio.
Package mp3 registers MP3 decoding with audio.
Package mp3 registers MP3 decoding with audio.
Package wave registers WAVE decoding with audio.
Package wave registers WAVE decoding with audio.

Jump to

Keyboard shortcuts

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