Documentation
¶
Overview ¶
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. It wraps the frame-at-a-time mp3.Decoder with the buffering, ID3v2 skipping and format conversion a consumer that just wants samples would otherwise have to write by hand.
It is shaped like the sibling pcm packages in go-flac, go-aac and go-wav so a consumer can switch codecs with the same call shape. The package name deliberately collides with those; import it with an alias:
import mp3pcm "github.com/Mag1cFall/go-mp3/pcm"
Decoding ¶
NewDecoder reads far enough to establish the stream configuration, skipping a leading ID3v2 tag and syncing to the first audio frame, and returns a Decoder whose Info is populated:
d, err := mp3pcm.NewDecoder(r)
if err != nil {
// no decodable MP3 frame
}
pcm, err := io.ReadAll(d) // or io.Copy(w, d) via WriteTo
Read accepts any buffer size, including ones that do not align to a whole sample; leftover bytes resume on the next call. The default output is interleaved little-endian signed 16-bit PCM (2 bytes per sample), matching go-aac and go-wav.
Pass WithF32 to NewDecoder (or to the DecodeInterleaved one-shots) to emit interleaved little-endian float32 (4 bytes per sample) instead.
Gapless trim ¶
A stream carrying a LAME gapless tag is trimmed to its playable extent, so the decoded output lines up sample for sample with what went into the encoder. The window is the one ffmpeg and mpg123 apply, not the tag's own two fields: the head trim is the tag's encoder delay PLUS the standard 529-sample Layer III synthesis delay, and the tail trim is the tag's padding LESS that same 529, floored at zero. Info reports the raw tag fields in EncoderDelay and EncoderPadding, so those two do not describe the applied window on their own. Info.TotalSamples is the playable count and always equals the number of samples per channel Read emits.
Encoding ¶
NewEncoder wraps the root mp3.Encoder as an io.WriteCloser that consumes interleaved little-endian signed 16-bit PCM and writes a CBR MP3 stream:
e, err := mp3pcm.NewEncoder(w, mp3pcm.Config{
SampleRate: 44100,
Channels: 2,
Bitrate: 128000, // zero selects the 128 kb/s default
})
// e.Write(interleavedS16); e.Close()
Write accepts any chunk size, buffering across calls; Close flushes the final partial frame and drains the encoder's one-frame lookahead. EncodeInterleaved is the one-shot form for a caller that already holds the whole buffer. The stream is tagless CBR (no LAME gapless tag), so a decoder does not trim the encoder's algorithmic delay: decoded output carries mp3.TotalDelay leading samples per channel, which a caller aligning back to the original input drops.
Reuse ¶
Decoder.Reset rebinds an existing Decoder to a new source, reusing its internal buffers and the wrapped mp3.Decoder, so a caller decoding many clips can pool decoders.
Index ¶
Examples ¶
Constants ¶
const DefaultMaxDecodedBytes = 1 << 30
DefaultMaxDecodedBytes is the ceiling DecodeInterleaved applies to its output. An MP3 stream's decoded length is not proportional to its encoded size, and a crafted or very long stream can decode to something huge; the one-shot helpers hold the whole decode in memory, so they stop at this ceiling rather than let a small input drive an unbounded allocation. It is 1 GiB, about 101 minutes of CD-quality (44.1 kHz, 16-bit) 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 ¶
var ErrDecodeLimit = errors.New("go-mp3/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.
var ErrEncoderClosed = errors.New("go-mp3/pcm: encoder is closed")
ErrEncoderClosed is returned by Encoder.Write after Close, mirroring flac.ErrEncoderClosed and aac.ErrEncoderClosed in the sibling pcm packages. The go-mp3 root package has no such sentinel (its frame encoder uses ErrEncoderFinalized), so the streaming wrapper defines its own.
var ErrInvalidSeek = errors.New("go-mp3/pcm: invalid seek")
ErrInvalidSeek is returned by SeekToSample for a negative sample index. It is an argument error: the decoder is left usable.
var ErrSeekUnsupported = errors.New("go-mp3/pcm: seek unsupported")
ErrSeekUnsupported is returned by SeekToSample when the source does not implement io.Seeker, or cannot be positioned by a frame-header walk (a free-format stream). It is a capability error: the decoder is left usable.
Functions ¶
func EncodeInterleaved ¶
EncodeInterleaved encodes a complete interleaved little-endian S16 PCM buffer to a CBR MP3 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.
The buffer must hold a whole number of inter-channel samples for cfg; a trailing partial sample is an error before any sink write. A final partial frame (fewer than mp3.FrameSize samples) is zero-padded internally, exactly as the streaming Close path does, so the buffer need not be a whole number of frames.
Example ¶
package main
import (
"bytes"
"fmt"
mp3pcm "github.com/Mag1cFall/go-mp3/pcm"
)
func main() {
// 1152 stereo samples of silence (S16LE): 1152 * 2 channels * 2 bytes.
pcm := make([]byte, 1152*2*2)
var out bytes.Buffer
if err := mp3pcm.EncodeInterleaved(&out, mp3pcm.Config{
SampleRate: 44100,
Channels: 2,
Bitrate: 128000,
}, pcm); err != nil {
panic(err)
}
fmt.Println(out.Len() > 0)
}
Output: true
Types ¶
type Config ¶
type Config struct {
// SampleRate is the input sample rate in Hz: 32000, 44100, or 48000.
// Required; there is no zero default.
SampleRate int
// Channels is 1 (mono) or 2 (stereo). Required; there is no zero default.
// For stereo the encoder selects L/R or M/S joint stereo per frame; both
// decode to 2 channels.
Channels int
// Bitrate is the CBR target in bits per second for the whole stream: one of
// the 14 MPEG-1 Layer III rates (32000, 40000, 48000, 56000, 64000, 80000,
// 96000, 112000, 128000, 160000, 192000, 224000, 256000, 320000). Zero
// selects mp3.DefaultBitrate (128000).
Bitrate int
}
Config controls the pcm encoder output. It is a flat struct mirroring the sibling pcm.Config in go-flac, go-aac and go-opus: every field's zero value is documented. Input PCM is always interleaved little-endian signed 16-bit (S16LE), so there is no bit-depth field.
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder decodes an MP3 stream into interleaved little-endian PCM: S16 (2 bytes/sample) by default, or native float32 (4 bytes/sample) with WithF32. It implements io.Reader and io.WriterTo, mirroring the sibling pcm.Decoder shape (NewDecoder, Reset, Info, Read, WriteTo).
A Decoder is not safe for concurrent use.
func NewDecoder ¶
NewDecoder reads enough of r to establish the stream configuration and returns a Decoder with Info populated. A nil reader, or a stream with no decodable MP3 frame, returns an error.
func (*Decoder) Read ¶
Read fills p with interleaved little-endian PCM (S16 by default, or float32 with WithF32). It returns (0, io.EOF) at a clean stream end and returns any latched terminal error on every later call. Short reads across a p that is not a whole number of samples are fine: pending is byte-granular, so a partial sample simply resumes on the next call.
func (*Decoder) Reset ¶
Reset rebinds the Decoder to a new source, reusing the internal buffers and the wrapped mp3.Decoder so a caller decoding many streams pays no per-stream allocation after warm-up. It clears any latched error and re-establishes Info from the new stream's first audio frame.
func (*Decoder) SeekToSample ¶
SeekToSample positions the decoder so the next Read or WriteTo yields audio starting at sampleIndex, counted in the playable (gapless-trimmed) per-channel timeline that Read emits, where sample 0 is the first playable sample. It returns the sample actually positioned at, which equals sampleIndex on success. Seeking to or past the known total lands at the stream end and returns the total (the next read is io.EOF).
It returns ErrSeekUnsupported when the source is not an io.Seeker, or when the stream cannot be positioned by the frame-header walk (a free-format stream, whose frames carry no size in their headers). A negative index returns ErrInvalidSeek. Both are argument/capability errors that leave the decoder usable. A trailing non-frame header met after at least one real frame (an ID3v1 tag or junk past the last audio frame) is treated like the stream end, landing there rather than failing. Any other mid-seek failure (a Seek or read error, or a landing frame that decodes to no samples) latches sticky, so a later Read returns it rather than resuming from an indeterminate position; a subsequent successful seek clears it.
Landing is exact rather than merely frame-accurate: SeekToSample recovers the target frame's exact index by an inexpensive frame-header walk from the first audio frame (a byte-based Xing/VBRI TOC is only approximate for a real VBR stream and cannot place a sample exactly), primes the bit reservoir and MDCT overlap by decoding seekPrimeFrames lead-in frames, then drops the leading samples inside the landing frame to hit sampleIndex precisely.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder streams interleaved little-endian signed 16-bit PCM (as []byte) to a CBR MPEG-1 Layer III (MP3) stream on an io.Writer. It is shaped like the sibling pcm.Encoders in go-flac, go-aac and go-opus: a flat Config, NewEncoder(w, cfg), Reset(w, cfg) for pooling, and Write/Close.
MP3 frames are self-framing, so the Encoder needs no seeking and no stream finalization beyond Close, which flushes the final partial frame and drains the root encoder's one-frame attack-detection lookahead. Because the encoder emits a tagless CBR stream (no LAME gapless tag), the decoded output carries mp3.TotalDelay leading samples of algorithmic delay; a caller aligning decoded audio back to the original input must drop them (see the root mp3.TotalDelay).
An Encoder is not safe for concurrent use.
func NewEncoder ¶
NewEncoder validates cfg and returns an Encoder writing a CBR MP3 stream to w. A config error returns immediately, before any byte is written.
func (*Encoder) Close ¶
Close flushes the final partial frame (zero-padded to a whole frame by the root encoder) and drains the encoder's one-frame lookahead plus the final flush frame. The drain is mandatory: without it the last real frame of audio, held in the encoder's lookahead, is never emitted. Close is idempotent; a Write after Close returns ErrEncoderClosed. It errors if the buffered trailing bytes are not a whole number of inter-channel samples.
func (*Encoder) Reset ¶
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, the pooling path for a many-short-clips workload. It re-validates cfg, discards buffered input, and resets all per-stream state (the root encoder's filterbank history, lookahead, and drain latch). 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, the usual pooling pattern (Reset, Write, Close, repeat).
func (*Encoder) Write ¶
Write consumes interleaved little-endian S16 PCM in arbitrary chunk sizes. Bytes that do not yet complete a full frame are buffered until the next Write or Close, so io.Copy works with any buffer size, including one not divisible by the sample stride. 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). A sink error is terminal for the stream: the frame that failed to write has already advanced the encoder's internal state, so the caller must abandon the stream rather than resume it by retrying the same bytes. After Close, Write returns ErrEncoderClosed.
type Info ¶
type Info struct {
SampleRate int // samples per second
Channels int // number of channels (1 or 2)
TotalSamples uint64 // per channel; 0 when unknown (no length tag)
// EncoderDelay and EncoderPadding are the RAW LAME tag fields, 0 when
// absent. They are not the window the decoder applies: the tag's delay
// covers the encoder side only, so the head trim is EncoderDelay plus the
// standard 529-sample synthesis delay and the tail trim is
// EncoderPadding less that same 529 (never below zero), which is what
// ffmpeg and mpg123 apply. A caller reconstructing the trim from these
// two fields alone would disagree with the decoder by 529 at each end.
EncoderDelay int
EncoderPadding int
}
Info describes the decoded stream. SampleRate and Channels are populated at construction from the first audio frame; the remaining fields are filled by later tasks (Xing/VBRI/LAME parsing) and stay at their zero values here.
func DecodeInterleaved ¶
DecodeInterleaved reads an entire MP3 stream from r and returns the decoded interleaved little-endian 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, go-aac's and go-opus' pcm.DecodeInterleaved). Output is S16 by default, or interleaved little-endian float32 when WithF32 is passed.
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.
Example ¶
package main
import (
"bytes"
"fmt"
mp3pcm "github.com/Mag1cFall/go-mp3/pcm"
)
func main() {
// Encode a short stream, then decode it back to interleaved S16 PCM.
pcm := make([]byte, 1152*2*2)
var enc bytes.Buffer
cfg := mp3pcm.Config{SampleRate: 44100, Channels: 2, Bitrate: 128000}
if err := mp3pcm.EncodeInterleaved(&enc, cfg, pcm); err != nil {
panic(err)
}
out, info, err := mp3pcm.DecodeInterleaved(bytes.NewReader(enc.Bytes()))
if err != nil {
panic(err)
}
fmt.Println(info.SampleRate, info.Channels, len(out) > 0)
}
Output: 44100 2 true
func DecodeInterleavedLimit ¶
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 WithF32 ¶
func WithF32() Option
WithF32 configures a Decoder to emit interleaved little-endian float32 bytes (4 bytes/sample), the decoder's own native sample type, instead of the default S16 (2 bytes/sample) conversion. Everything else (gapless trim, Xing/Info-tag exclusion, Read/WriteTo semantics) is unchanged; only the per-sample pack width and format differ.