Documentation
¶
Overview ¶
Package mp3 implements an MPEG-1/2/2.5 Layer III (MP3) decoder and an MPEG-1 Layer III encoder, in pure Go without cgo.
The decoder is a port of minimp3 (CC0-1.0); see PROVENANCE.md. The encoder is an independent implementation derived from ISO/IEC 11172-3 and published literature (see PROVENANCE.md): a fixed-bitrate CBR encoder with a psychoacoustic model, a bit reservoir, per-frame M/S joint stereo, and attack-driven short blocks (block switching). Quality at a given bitrate still lags a fully tuned encoder like LAME; further tuning is planned and is measured against LAME with the tools/quality harness (see the README's "Quality measurement against LAME" section).
Index ¶
Examples ¶
Constants ¶
const DefaultBitrate = 128000
DefaultBitrate is the CBR target, in bits per second, selected when an EncoderConfig leaves Bitrate zero: 128 kb/s.
const EncoderDelay = enc.ChainDelay - standardDecoderDelay
EncoderDelay is this encoder's own algorithmic delay, in samples per channel, in the sense a LAME-style tag's "encoder delay" field uses: a stream this package produces carries TotalDelay leading samples of algorithmic delay once decoded, of which a standard MPEG-1 Layer III decoder contributes its own fixed standardDecoderDelay; EncoderDelay is the remainder, attributable to the encoder alone. See TotalDelay for the number that matters when trimming a decoded stream back to the original input.
const FrameSize = 1152
FrameSize is the number of samples per channel consumed by one Encoder.EncodeFrame call and covered by one encoded MP3 frame (MPEG-1 Layer III): 1152, fixed by the format.
const TotalDelay = enc.ChainDelay
TotalDelay is the total encoder-plus-standard-decoder algorithmic delay, in samples per channel, carried as leading samples in the decoded output of any stream this package produces. This encoder emits tagless CBR streams, with no LAME gapless tag for a downstream decoder to trim automatically, so a caller that wants to align decoded audio back to the original input must subtract TotalDelay itself (drop the first TotalDelay samples per channel after decoding). EncoderDelay (528) is the encoder-only LAME-tag split: TotalDelay - standardDecoderDelay.
Variables ¶
var ( // ErrCorruptStream is reserved for the Phase 2 streaming layer (package // pcm), which can distinguish a genuinely corrupt payload from a normal // resync-skippable frame across a whole stream. DecodeFrame does not // return it: at the single-frame granularity, a frame that is valid but // produces no samples looks identical to a corrupt one, so returning // this error here would be a guess. It exists now so Phase 2 code can // reference mp3.ErrCorruptStream, the same way go-flac's pcm package // imports flac.ErrCRCMismatch. ErrCorruptStream = errors.New("go-mp3: corrupt stream") // ErrUnsupported is returned by DecodeFrame when it recognizes a valid // frame header for a layer this decoder does not decode (Layer I or II; // this library decodes Layer III only). ErrUnsupported = errors.New("go-mp3: unsupported stream") )
Sentinel errors returned by this package's decoding functions.
var ( // ErrInvalidAudio is returned by EncodeFrame when a non-nil samples // argument contains a NaN or an Inf anywhere. It appends nothing new // to dst and poisons the Encoder: every later call, including a nil // drain call, also returns ErrInvalidAudio until Reset. ErrInvalidAudio = errors.New("go-mp3: invalid audio sample (NaN or Inf)") // ErrEncoderNotInitialized is returned by EncodeFrame on an Encoder that has // not been successfully initialized by NewEncoder or Reset. This // includes a zero-value Encoder and one whose only Reset call so far // returned an error; it does not include an already-initialized // Encoder whose later Reset call errors, since that leaves the prior // successful state untouched. ErrEncoderNotInitialized = errors.New("go-mp3: encoder not initialized") // ErrEncoderFinalized is returned by EncodeFrame when non-nil audio is // submitted after the stream has already been finalized: either a // short (final) frame was already submitted, or the encoder has // already drained. Reset starts a new stream. ErrEncoderFinalized = errors.New("go-mp3: encoder finalized; Reset to start a new stream") )
Sentinel errors returned by Encoder methods.
Functions ¶
This section is empty.
Types ¶
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder decodes MPEG-1/2/2.5 Layer III (MP3) audio frame by frame. It carries state between calls (bit reservoir, filterbank and overlap memory, and a cached header for fast resync), so frames from the same stream must be decoded in order with the same Decoder. A Decoder is not safe for concurrent use; use one per goroutine.
func (*Decoder) DecodeFrame ¶
DecodeFrame decodes the first MP3 frame found in data into pcm as interleaved float32 samples in [-1, 1] (up to 1152 samples per channel, so pcm must have room for 1152*Channels), and returns the number of samples decoded per channel along with the frame's FrameInfo.
A caller drives a stream by looping: decode, then advance its read position by info.FrameBytes, stopping once info.FrameBytes is 0 (or once the position reaches the end of the buffered data, whichever comes first: a search that finds nothing consumes the rest of data in one call, exactly like TestFullStreamMatchesOracle's loop in internal/dec). The return values combine as follows:
- n > 0: a Layer III frame was decoded; pcm[:n*info.Channels] holds the interleaved samples, and err is nil.
- n == 0, info.FrameBytes == 0: data was empty; there is nothing left to search. err is nil; this is the stream-end signal, not an error.
- n == 0, info.FrameBytes > 0, info.Layer == 0: no frame header was recognized anywhere in data, so it was all treated as skippable bytes (e.g. leading garbage, an ID3 tag, or trailing padding). This is normal, not an error; err is nil, and the caller advances by info.FrameBytes as usual (a streaming caller would instead append more data and retry, since nothing conclusive was found).
- n == 0, info.FrameBytes > 0, info.Layer == 3: a Layer III frame was found and consumed but produced no samples. This is normal during MP3 resync (e.g. right after a stream cut) and is not an error; err is nil. The caller still advances by info.FrameBytes.
- n == 0, info.FrameBytes > 0, info.Layer is 1 or 2: a valid Layer I or II frame was found and sized, but this decoder does not decode it. err is ErrUnsupported; the caller can still advance by info.FrameBytes to skip over it.
Example ¶
ExampleDecoder_DecodeFrame decodes an MP3 file frame by frame with the low-level Decoder and reports the stream's sample rate.
package main
import (
"errors"
"fmt"
"log"
"os"
mp3 "github.com/tphakala/go-mp3"
)
func main() {
data, err := os.ReadFile("testdata/fixtures/sine48m_128.mp3")
if err != nil {
log.Fatal(err)
}
d := mp3.NewDecoder()
pcm := make([]float32, 1152*2) // up to 1152 samples/channel, interleaved
var rate int
pos := 0
for pos < len(data) {
n, info, err := d.DecodeFrame(data[pos:], pcm)
if err != nil && !errors.Is(err, mp3.ErrUnsupported) {
log.Fatal(err)
}
if n > 0 && rate == 0 {
rate = info.SampleRate
}
if info.FrameBytes == 0 {
break // no more frames
}
pos += info.FrameBytes
}
fmt.Println("sample rate:", rate)
}
Output: sample rate: 48000
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder is a stateful CBR MPEG-1 Layer III encoder: a thin validated wrapper over an internal enc.Encoder. It validates configuration and frame shape up front so that the internal layer's two panic contracts (a length mismatch, and any non-nil call after a drain) are unreachable through this public API. Frames from the same stream must be encoded in order with the same Encoder. An Encoder is not safe for concurrent use.
func NewEncoder ¶
func NewEncoder(cfg EncoderConfig) (*Encoder, error)
NewEncoder returns a new Encoder for cfg, or an error if cfg is invalid. It is equivalent to calling Reset on a zero-value Encoder.
func (*Encoder) Delay ¶
Delay returns EncoderDelay. It is a method, rather than callers reading the constant directly, so the value can become configuration-dependent in the future without an API break; today it does not vary, and returns EncoderDelay even on a zero-value Encoder.
func (*Encoder) Drained ¶
Drained reports whether the encoder has already emitted its final flush frame in response to a nil EncodeFrame call. It returns false on a zero-value Encoder.
func (*Encoder) EncodeFrame ¶
EncodeFrame encodes the next frame of planar float32 PCM (one slice per channel, up to FrameSize samples each) and appends zero or more complete MP3 frames to dst, returning the extended slice. EncodeFrame is not one-call-in-one-frame-out: the encoder holds a one-frame PCM lookahead for attack detection and block switching, plus a bit reservoir that can carry a coded frame across calls, so the first call typically appends none, and frames for the audio passed to call n emerge no earlier than call n+1. Drain (see below) flushes both the held frame and the final flush frame in one call, so N non-nil calls plus drain always total exactly N+1 emitted frames; do not assume a fixed number of frames per call when sizing dst or counting output. Finite samples are accepted at any magnitude; any sample outside [-1, 1] is clamped to [-1, 1] before encoding. A NaN or an Inf anywhere returns ErrInvalidAudio instead (see its doc comment above). EncodeFrame is append-style, like strconv.AppendInt: allocation-free when dst has spare capacity.
Only the final frame of a stream may be shorter than FrameSize; a short frame is zero-padded internally and finalizes the stream, so submitting any further non-nil audio returns ErrEncoderFinalized until Reset.
A non-nil samples must carry exactly one slice per configured channel, all of equal, nonzero length no greater than FrameSize; violating any of that (wrong channel count, an empty channel, unequal channel lengths, or a channel longer than FrameSize) returns a distinct error, none of them one of the three sentinels documented here.
Pass a nil samples to drain: unless the encoder has been poisoned by prior invalid audio (which makes every later call, including a drain, return ErrInvalidAudio until Reset), a nil call flushes the held frame (the last real audio the encoder was still holding for its one-frame lookahead, if any) plus the final silence flush frame, and is always legal, including right after a short final frame; further nil calls append nothing more. Drained reports whether the drain has already happened. Submitting non-nil audio after a drain also returns ErrEncoderFinalized.
On an Encoder that has not been successfully initialized by NewEncoder or Reset (see ErrEncoderNotInitialized above for exactly what that covers), EncodeFrame returns (dst, ErrEncoderNotInitialized) unconditionally.
func (*Encoder) Reset ¶
func (e *Encoder) Reset(cfg EncoderConfig) error
Reset validates cfg and clears all stream state: the internal filterbank/MDCT history, the padding accumulator, poison, drain, Stats, and this wrapper's own short-final-frame latch, as at the start of a fresh stream. Reset is legal on a zero-value Encoder: NewEncoder is exactly &Encoder{} followed by Reset. It is also the only way to clear a poisoned or finalized Encoder.
func (*Encoder) Stats ¶
Stats returns the encoder's cumulative counters since NewEncoder or the last Reset. It returns a zero Stats on a zero-value Encoder.
Field by field, not a bare struct conversion: internal/enc.Stats gained a ScfsiBitsSaved field (Phase 4 increment 4) that is internal accounting only, not part of this public API, so a straight Stats(e.enc.Stats()) conversion would no longer compile once the two structs' field sets diverged; this stays correct regardless of which fields internal/enc.Stats adds in the future.
func (*Encoder) TotalDelay ¶
TotalDelay returns TotalDelay: a method mirror of the constant, like Delay, so callers holding an Encoder need not import the constant and the surface stays stable if the delay ever becomes config-dependent.
type EncoderConfig ¶
type EncoderConfig struct {
// SampleRate is the input sample rate in Hz: 32000, 44100, or 48000.
// Required.
SampleRate int
// Channels is the number of audio channels: 1 (mono) or 2 (stereo).
// For stereo, the encoder automatically selects L/R or M/S joint
// stereo per frame based on the signal; both decode to 2 channels.
// Required.
Channels int
// Bitrate is the CBR target for the whole stream, in bits per second:
// one of 32000, 40000, 48000, 56000, 64000, 80000, 96000, 112000,
// 128000, 160000, 192000, 224000, 256000, or 320000. Zero selects
// DefaultBitrate. This encoder is CBR-only; there is no VBR setting, and
// RateControl trades encode speed against exactness rather than bitrate.
Bitrate int
// RateControl selects the inner rate loop's global_gain search strategy:
// RateControlExact (the zero value and default) for the best quality, or
// RateControlFast, which costs a small, bounded amount of quality on some
// frames and is faster only on light frames. See RateControl.
RateControl RateControl
}
EncoderConfig configures a new or reset Encoder.
type FrameInfo ¶
type FrameInfo struct {
// Channels is the number of audio channels (1 or 2).
Channels int
// SampleRate is the sample rate in samples per second.
SampleRate int
// Layer is the MPEG audio layer (1, 2, or 3) of a recognized frame
// header, or 0 if DecodeFrame found no frame header in data at all.
// This decoder produces samples only for Layer 3.
Layer int
// Bitrate is the frame's bitrate in kilobits per second.
Bitrate int
// FrameBytes is the total number of bytes consumed by this call,
// including any leading bytes skipped before frame sync (FrameOffset).
// A caller advances its read position by FrameBytes to reach the next
// frame. FrameBytes is 0 only when data was empty; see DecodeFrame for
// the full breakdown of what a zero Channels/Layer/SampleRate paired
// with a nonzero FrameBytes means.
FrameBytes int
// FrameOffset is the number of bytes skipped before the frame's sync
// word was found.
FrameOffset int
}
FrameInfo carries the facts DecodeFrame determined about the frame it just processed.
type RateControl ¶
type RateControl int
RateControl selects the encoder's inner rate-loop strategy for choosing each granule's global_gain, trading encode speed against exactness. The zero value is RateControlExact, so the default costs nothing and never changes output.
const ( // RateControlExact selects the smallest global_gain whose Huffman coding // fits the frame's bit budget, by an upward linear scan: the finest // quantization within budget, hence the best quality this encoder // produces, and the historical behavior. The scan starts at the first gain // a sound lower bound on the Huffman bits admits (found by binary search, // since the bound never increases with the gain), serves quantization from // a per-pass cache, and skips the Huffman region search at every step a // tighter bound proves over budget; none of that changes the result. This // is the default. RateControlExact RateControl = iota // RateControlFast binary-searches global_gain instead of scanning. It is // no longer the faster choice on dense frames: on the loud and broadband // stereo frames of BenchmarkEscalationFrame, RateControlExact is about // 2.3 times faster on amd64 and 2.6 times on arm64 (the Intel i5-7260U and // Cortex-A76 hosts measured). Fast keeps a smaller edge on light frames // (about 1.2 to 1.3 times on the 320 kbps mono case of // BenchmarkTransientFrame) and ties on tonal material. // Because the coded bit count is not strictly monotone in the gain, the // search can occasionally settle one or a few steps above the exact choice: a // slightly coarser quantization on the affected granules (never finer), a // small and bounded quality reduction. Its output is therefore not // bit-identical to RateControlExact. Prefer RateControlExact // unless a benchmark on your own material shows Fast faster. RateControlFast )
func (RateControl) String ¶
func (rc RateControl) String() string
String returns the mode's identifier, e.g. "RateControlFast", or "RateControl(n)" for an out-of-range value.
type Stats ¶
type Stats struct {
// Frames and PaddedFrames count frames CODED (one per non-drain
// EncodeFrame call, plus the drain frame). With the bit reservoir a coded
// frame may stay buffered across EncodeFrame calls, so mid-stream these
// can lead the number of frames actually appended to dst; after Drain
// they equal the emitted frame count. Bytes, in contrast, counts bytes
// actually appended to dst.
Frames int64
Bytes int64
PaddedFrames int64
MeanGlobalGain float64 // mean over all coded granule-channels
}
Stats reports what an Encoder produced since NewEncoder or the last Reset.
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
bits
Package bits provides an MSB-first bit reader matching the bit-position and overrun semantics of minimp3's bs_t/get_bits (see tools/oracle/minimp3.h, CC0-1.0), which every decode unit in this package reads its bitstream through.
|
Package bits provides an MSB-first bit reader matching the bit-position and overrun semantics of minimp3's bs_t/get_bits (see tools/oracle/minimp3.h, CC0-1.0), which every decode unit in this package reads its bitstream through. |
|
dec
Package dec implements the MP3 (MPEG-1/2/2.5 Layer III) decoder core, ported unit-by-unit from the pinned minimp3 (CC0-1.0, see tools/oracle/minimp3.h and PROVENANCE.md) and gated by differential tests against that C oracle.
|
Package dec implements the MP3 (MPEG-1/2/2.5 Layer III) decoder core, ported unit-by-unit from the pinned minimp3 (CC0-1.0, see tools/oracle/minimp3.h and PROVENANCE.md) and gated by differential tests against that C oracle. |
|
enc
Package enc is the clean-room MPEG-1 Layer III encoder for go-mp3.
|
Package enc is the clean-room MPEG-1 Layer III encoder for go-mp3. |
|
quality
Package quality holds the objective audio quality metrics, alignment, WAV I/O, and deterministic test programs behind the tools/quality harness, which compares this project's MP3 encoder against LAME (used strictly as a black-box binary; see PROVENANCE.md).
|
Package quality holds the objective audio quality metrics, alignment, WAV I/O, and deterministic test programs behind the tools/quality harness, which compares this project's MP3 encoder against LAME (used strictly as a black-box binary; see PROVENANCE.md). |
|
testsignal
Package testsignal provides the deterministic pseudo-random and multi-tone generators shared across this project's test suites.
|
Package testsignal provides the deterministic pseudo-random and multi-tone generators shared across this project's test suites. |
|
Package pcm is the high-level streaming PCM API for go-mp3: an MP3 stream (an io.Reader) in, interleaved little-endian PCM out through io.Reader and io.WriterTo.
|
Package pcm is the high-level streaming PCM API for go-mp3: an MP3 stream (an io.Reader) in, interleaved little-endian PCM out through io.Reader and io.WriterTo. |
|
tools
|
|
|
quality
command
Command quality compares this project's MP3 encoder against LAME (used strictly as a black-box binary, see PROVENANCE.md) on a deterministic synthetic corpus and optional user WAV files.
|
Command quality compares this project's MP3 encoder against LAME (used strictly as a black-box binary, see PROVENANCE.md) on a deterministic synthetic corpus and optional user WAV files. |