flac

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 15 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 flac decodes native FLAC streams for file analysis.

Package flac implements the frame decoder used by the native FLAC codec.

Index

Constants

View Source
const Signature = "fLaC"

Signature marks the start of a native FLAC stream.

View Source
const StreamInfoSize = 34

StreamInfoSize is the size of the STREAMINFO metadata body.

Variables

View Source
var (
	ErrUnsupported      = errors.New("FLAC: unsupported or reserved bitstream value")
	ErrCRCMismatch      = errors.New("FLAC: CRC mismatch")
	ErrSampleOutOfRange = errors.New("FLAC: decoded sample outside the frame bit depth")
)
View Source
var ErrResidualRange = fmt.Errorf("rice: residual outside the signed 32-bit range: %w", ErrSampleOutOfRange)

ErrResidualRange is returned by DecodeResidual when a Rice-coded residual leaves the signed 32-bit range. It is returned only after the whole residual has been read, so the caller can finish its frame and report the violation once the frame CRC-16 has matched. It wraps ErrSampleOutOfRange so it classifies correctly if it ever escapes. It is a package-level value so returning it allocates nothing.

Functions

func Decode

func Decode(br *Reader, si StreamInfo, dst *Frame) (err error)

Decode decodes exactly one frame from br into dst. dst.Channels is grown/reused to hold the frame's channels at its block size.

A frame is accepted only when its header CRC-8 and frame CRC-16 match, every Rice residual is within the signed 32-bit range and every decoded sample fits the frame bit depth. The checks run in that order: a subframe or stereo channel found out of range, or a residual outside the 32-bit range, is remembered while the frame is read to its end, and ErrSampleOutOfRange is returned only after the stored CRC-16 has matched. A frame with a damaged CRC therefore reports ErrCRCMismatch whatever its samples decode to.

func DecodeResidual

func DecodeResidual[T Sample](br *Reader, dst []T, blockSize, predOrder int) error

DecodeResidual decodes the partitioned Rice residual that follows the warmup samples of a subframe, filling dst[predOrder:blockSize]. dst[:predOrder] holds warmup samples already written by the caller.

A Rice-coded symbol whose zigzag-folded value is 2^32 or more decodes to a residual outside the signed 32-bit range; the whole residual is still read and ErrResidualRange is returned at the end. The bound is one value looser than RFC 9639 section 9.2.7.3, which also excludes -2^31: it accepts the folded value 2^32-1 (residual -2^31), the limit libFLAC 1.5.0 applies in its signed Rice block reader (src/libFLAC/deduplication/bitreader_read_rice_signed_block.c at tag 1.5.0, line 17 and lines 69 to 70). Past it the residual does not fit int32, and narrowing it on the int32 path would wrap without notice. That libFLAC function does not check the Rice parameter 0 path (lines 27 to 28) or its tail path from line 96; this decoder checks every Rice symbol. Escape partitions carry at most 31 raw bits and are always in range.

func ReadTags

func ReadTags(source io.ReaderAt, size int64) (tagdata.Result, error)

ReadTags reads the leading FLAC metadata blocks through a bounded view. The returned pictures refer to the encoded bytes in source.

func Update8

func Update8(crc, b uint8) uint8

Update8 folds one byte into a running CRC-8.

func Update16

func Update16(crc uint16, b byte) uint16

Update16 folds one byte into a running CRC-16.

Types

type ByteRangeTap

type ByteRangeTap interface{ TapBytes(p []byte) }

ByteRangeTap folds a whole run of consumed bytes at once. A tap that also implements it can be switched to deferred bulk mode (SwitchTapToDeferred), in which the hot read path does no per-byte tap work and consumed runs are handed over in bulk at buffer-refill boundaries (readMore) and on demand (FlushTap). The frame decoder uses this to fold the frame CRC-16 over large runs in bulk instead of one byte at a time.

p aliases the Reader's internal buffer and is valid only for the duration of the call: readMore reuses and compacts that buffer, so an implementation that needs to retain the bytes must copy them. The frame CRC tap folds them immediately.

type ByteTap

type ByteTap interface{ TapByte(b byte) }

ByteTap receives every fully consumed source byte while installed. It is the non-closure form of the tap: the frame decoder installs a reusable tap whose state lives on the (heap-resident) reused frame, so decoding a frame allocates no per-frame tap closure.

type Decoder

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

Decoder decodes native FLAC into signed PCM samples at the stream's bit depth. A decoder is for a single pass and must be used by one goroutine at a time.

func Open

func Open(ctx context.Context, r io.Reader) (*Decoder, error)

Open reads STREAMINFO and skips optional metadata. The caller owns r and must keep it open until decoding finishes.

func OpenWithTags

func OpenWithTags(ctx context.Context, r io.Reader) (*Decoder, tagdata.Result, error)

OpenWithTags opens a forward-only FLAC stream and retains bounded leading text and artwork while consuming its metadata blocks.

func (*Decoder) BufferedInput

func (d *Decoder) BufferedInput() int

BufferedInput reports compressed bytes read ahead of the last decoded frame.

func (*Decoder) Close

func (d *Decoder) Close() error

Close releases the decoder and leaves the input open.

func (*Decoder) Decode

func (d *Decoder) Decode(consume func(channels [][]int32)) error

Decode calls consume synchronously for each verified block. The signed channel slices are read-only and valid until consume returns.

func (*Decoder) Format

func (d *Decoder) Format() (channels, bitsPerSample int)

Format reports the number of channels and the native sample depth.

func (*Decoder) FrameCount

func (d *Decoder) FrameCount() (int64, bool)

FrameCount reports the STREAMINFO count when present.

func (*Decoder) NextBlock

func (d *Decoder) NextBlock() (audio.Buffer[int32], error)

NextBlock reads the next verified frame into borrowed channel planes.

func (*Decoder) PCMFormat

func (d *Decoder) PCMFormat() audio.Format

PCMFormat reports the native sample rate, ordered channels and depth.

type Frame

type Frame struct {
	BlockSize     int
	SampleRate    int
	BitsPerSample int
	Channels      [][]int32 // len == number of channels; each len == BlockSize
	// contains filtered or unexported fields
}

Frame holds one decoded FLAC frame. Channels and the decorrelation scratch buffers are reused across Decode calls.

type Reader

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

Reader reads bits MSB-first from an underlying byte source, the bit order FLAC uses. Bytes are pulled into an owned block and shifted into a 64-bit accumulator, so there is no per-byte interface dispatch. A tap, if set, receives every fully consumed source byte in order, which the frame decoder uses to feed CRC hashers.

Bit layout is LEFT-ALIGNED, MSB-first: the nbits valid bits occupy the TOP nbits positions of acc (bits [64-nbits, 63]); all lower bits are zero. This makes acc>>(64-n) a mask-free extractor and bits.LeadingZeros64(acc) a correct zero-run scan.

func NewReaderSize

func NewReaderSize(r io.Reader, size int) *Reader

NewReaderSize makes a Reader with an owned buffer of at least size bytes.

func (*Reader) BufferedInput

func (r *Reader) BufferedInput() int

BufferedInput reports unread bytes held here and in the upstream byte buffer.

func (*Reader) ByteAligned

func (r *Reader) ByteAligned() bool

ByteAligned reports whether the next bit starts a fresh byte. The accumulator can hold several whole buffered bytes, so alignment is nbits&7==0, not nbits==0.

func (*Reader) FlushTap

func (r *Reader) FlushTap()

FlushTap hands the range tap every byte consumed since the last flush (the run buf[tapCur:consumedBytes]). It is used in deferred mode to sweep up the final run of a frame before a value that must be excluded from the tap is read. It is a no-op when no range tap is installed or nothing new has been consumed.

func (*Reader) ReadBits

func (r *Reader) ReadBits(n uint) (uint64, error)

ReadBits reads n bits (0..64) MSB-first and returns them right-aligned.

func (*Reader) ReadRice

func (r *Reader) ReadRice(k uint) (uint64, uint64, error)

ReadRice reads one folded Rice symbol. The returned quotient is checked by the caller before it can be shifted out of range.

func (*Reader) ReadSigned

func (r *Reader) ReadSigned(n uint) (int64, error)

ReadSigned reads n bits and sign-extends them as a two's-complement integer.

func (*Reader) ReadUnary

func (r *Reader) ReadUnary() (uint64, error)

ReadUnary counts zero bits up to and including the terminating one bit and returns the count of zeros. It scans zeros across the whole accumulator word via bits.LeadingZeros64, so a long zero run costs one iteration per 64-bit word.

func (*Reader) Reset

func (r *Reader) Reset(src io.Reader)

Reset empties the buffer and starts reading from src without reallocating.

func (*Reader) SetTapper

func (r *Reader) SetTapper(t ByteTap)

SetTapper registers t to be called with every fully consumed source byte. It reseats the consumption cursor so only bytes consumed WHILE t is installed are tapped. If t also implements ByteRangeTap it may later be switched to deferred bulk mode with SwitchTapToDeferred. Pass nil to clear the tap.

func (*Reader) SkipToByteBoundary

func (r *Reader) SkipToByteBoundary() error

SkipToByteBoundary discards remaining bits in the current partial byte so the next read starts on a byte boundary. The skipped byte is tapped if it had been partially consumed.

func (*Reader) SwitchTapToDeferred

func (r *Reader) SwitchTapToDeferred()

SwitchTapToDeferred puts the installed range-capable tap into deferred bulk mode: it stops the per-byte hot-path emit (by clearing the ByteTap gate) while keeping the ByteRangeTap, so consumed runs are folded in bulk at readMore and FlushTap instead of one byte at a time. The caller invokes it at a byte boundary where the tap has already seen every consumed byte (tapCur == consumedBytes), so no byte is skipped across the switch. It is a no-op if the current tap is not range-capable.

type Sample

type Sample interface{ ~int32 | ~int64 }

Sample is the integer width used for decoded residuals/samples.

type StreamHeader

type StreamHeader struct {
	StreamInfo
	MinBlockSize uint16
	MaxBlockSize uint16
	TotalSamples uint64
	LastMetadata bool
}

StreamHeader contains the STREAMINFO fields used by the probe and decoder.

func ParseStreamInfo

func ParseStreamInfo(body []byte) (StreamHeader, error)

ParseStreamInfo reads a standalone STREAMINFO metadata body.

func ReadStreamHeader

func ReadStreamHeader(r io.Reader) (StreamHeader, error)

ReadStreamHeader reads the FLAC marker and mandatory first metadata block.

type StreamInfo

type StreamInfo struct {
	SampleRate int
	Channels   int
	BitDepth   int
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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