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
- Variables
- func Decode(br *Reader, si StreamInfo, dst *Frame) (err error)
- func DecodeResidual[T Sample](br *Reader, dst []T, blockSize, predOrder int) error
- func ReadTags(source io.ReaderAt, size int64) (tagdata.Result, error)
- func Update8(crc, b uint8) uint8
- func Update16(crc uint16, b byte) uint16
- type ByteRangeTap
- type ByteTap
- type Decoder
- func (d *Decoder) BufferedInput() int
- func (d *Decoder) Close() error
- func (d *Decoder) Decode(consume func(channels [][]int32)) error
- func (d *Decoder) Format() (channels, bitsPerSample int)
- func (d *Decoder) FrameCount() (int64, bool)
- func (d *Decoder) NextBlock() (audio.Buffer[int32], error)
- func (d *Decoder) PCMFormat() audio.Format
- type Frame
- type Reader
- func (r *Reader) BufferedInput() int
- func (r *Reader) ByteAligned() bool
- func (r *Reader) FlushTap()
- func (r *Reader) ReadBits(n uint) (uint64, error)
- func (r *Reader) ReadRice(k uint) (uint64, uint64, error)
- func (r *Reader) ReadSigned(n uint) (int64, error)
- func (r *Reader) ReadUnary() (uint64, error)
- func (r *Reader) Reset(src io.Reader)
- func (r *Reader) SetTapper(t ByteTap)
- func (r *Reader) SkipToByteBoundary() error
- func (r *Reader) SwitchTapToDeferred()
- type Sample
- type StreamHeader
- type StreamInfo
Constants ¶
const Signature = "fLaC"
Signature marks the start of a native FLAC stream.
const StreamInfoSize = 34
StreamInfoSize is the size of the STREAMINFO metadata body.
Variables ¶
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") )
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 ¶
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.
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 ¶
Open reads STREAMINFO and skips optional metadata. The caller owns r and must keep it open until decoding finishes.
func OpenWithTags ¶
OpenWithTags opens a forward-only FLAC stream and retains bounded leading text and artwork while consuming its metadata blocks.
func (*Decoder) BufferedInput ¶
BufferedInput reports compressed bytes read ahead of the last decoded frame.
func (*Decoder) Decode ¶
Decode calls consume synchronously for each verified block. The signed channel slices are read-only and valid until consume returns.
func (*Decoder) FrameCount ¶
FrameCount reports the STREAMINFO count when present.
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 ¶
NewReaderSize makes a Reader with an owned buffer of at least size bytes.
func (*Reader) BufferedInput ¶
BufferedInput reports unread bytes held here and in the upstream byte buffer.
func (*Reader) ByteAligned ¶
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) ReadRice ¶
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 ¶
ReadSigned reads n bits and sign-extends them as a two's-complement integer.
func (*Reader) ReadUnary ¶
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) SetTapper ¶
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 ¶
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 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.