audio

package module
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: 16 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

BeatGlow Audio

Go 1.27.3 or later. The module builds with CGO_ENABLED=0.

Decode a file with audio.NewDecoder or build its peaks with waveform.WaveForm. See the v1 compatibility guide for supported targets, contracts, and migration notes.

Decoding files and tracker modules

Import the formats the application uses. Use the registration-only imports github.com/BeatGlow/audio/codec/all for file codecs and github.com/BeatGlow/audio/tracker/all for tracker modules. Applications can register their own formats with audio.RegisterFormat, audio.RegisterFormatProbe, or tracker.RegisterFormat.

decoder, err := audio.NewDecoder[float32](ctx, input)

The decoder is an audio.Source[float32]. Pass it to the mixer, or call ReadFrames with an audio.Buffer[float32] for caller-owned planes. Call NextBlock to borrow one block until the next read, seek, or close. audio.WithSampleRate(rate) asks for output at a specific rate. When the format cannot render directly at that rate, the decoder resamples.

Reading metadata

Use codec.ReadMetadata(ctx, readerAt, size) for file tags and artwork. It returns a tag.Metadata snapshot and leaves the input position unchanged. If you already have a decoder, use decoder.Metadata() and drain updates with decoder.TakeMetadataUpdates(). See the metadata guide for artwork ownership and supported formats.

Waveform previews

Use waveform.WaveForm(ctx, readerAt, size, waveform.Options{}) for a file. Use waveform.WaveFormCUE for one track or waveform.WaveFormsCUE for every audio track in a sheet. Both use the INDEX 01 ranges of the referenced FLAC files. The decoder uses the formats the application registers.

The default file or CUE waveform returns 2,048 chronological left/right peak pairs in [0, 1] at the native sample rate. Set Options.Points to change the peak count and Options.SampleRate to resample before measuring. Mono appears on both sides. Surround channels are mixed into stereo by speaker position, with LFE omitted.

For live previews, pass a waveform.StreamBatch to StreamWaveForm.AddBatch. The batch carries normalized left and right PCM planes and their position in the capture stream. The same planes can feed history, as shown in the live waveform example. The zero value expects 48 kHz stereo PCM and retains 320 peaks at 40 peaks per second. Use waveform.NewStreamWaveForm to set the incoming PCM rate, peak rate, or retained peak count.

Sources, sinks, and mixing

audio.Source[T] and audio.Sink[T] exchange planar PCM and report counts in frames. The audio.Format returned by PCMFormat() specifies the rate, ordered channel layout, and encoding. The Go type describes storage. For example, signed 24-bit PCM uses right-justified values in int32.

For the encoded codec and native rate without PCM decoding, use codec.ReadSourceFormat. The probe needs no format registration and inspects from the input's current position.

Use audio.MonoLayout or audio.StereoLayout when constructing a PCM format with a known channel order.

format := audio.Format{
    RateHz:   48000,
    Layout:   audio.StereoLayout,
    Encoding: audio.Encoding{Kind: audio.FloatPCM, Bits: 32},
}

Treat the shared layouts as read-only. Call format.Clone() before editing its channel order.

audio.NewMixer(sink, sources...) checks that each source matches the sink's format, then mixes with reusable buffers in Run(ctx). The sink can suggest a block size. Short I/O is handled in frames, and an exhausted source becomes silent while the other sources continue. A canceled run returns the context error even if its final read reports EOF. Live sources and sinks can implement audio.ContextSource and audio.ContextSink so cancellation interrupts pending I/O. For plain sources and sinks, the caller must unblock any pending I/O.

  • audio.NewRawSource and audio.NewRawSink handle interleaved raw PCM. A seekable, frame-aligned source also implements audio.FrameSeeker.
  • synth.NewTone generates mono PCM and supports phase-aligned time seeks. synth.Sine[T] creates voices that can start, change pitch, and stop on scheduled output frames.
  • synth.LoadPCMInstrument decodes a clip from an audio file. Set its root frequency and any envelopes or loops when loading it.
  • synth.NewSequencer plays overlapping tracks of notes and rests for a fixed duration. Give the score enough time for any release tails.
  • tracker.NewReplayPlayer plays a tick-based replay with scheduled synth voices, tempo changes, and order and row transitions. Its player implements audio.Source[T], audio.FrameSeeker, and audio.BlockSizeHint. Forward seeks advance the current replay. Backward seeks rebuild replay state from the start.
  • The individual tracker packages load native modules and build typed PCM replays for MOD, XM, S3M, IT, STM and MTM. See the module replay demo for playback profiles and examples.
  • tracker.NewSong and tracker.NewSongPlayer edit patterns and play an independent snapshot. synth.FM[T] provides a two-operator instrument with scheduled controls and optional envelopes.
  • driver.OpenPlayback opens a float32 sink on the default output using CoreAudio on macOS or ALSA on Linux AMD64 and ARM64.
  • On Linux, alsa.OpenPlayback[int16] and alsa.OpenPlayback[float32] open typed playback streams. Build the sources with the opened sink's negotiated format. Use alsa.Card.Devices for playback and capture discovery. For playback, read the negotiated format with PCMFormat() on the opened sink.
  • On macOS, coreaudio.OpenPlayback takes a mono or stereo float32 PCM format and queues it to the default output device.

Drain a hardware sink to play its pending frames, then close it to release the device. Codec inputs and raw stream readers and writers remain caller-owned.

Matching an opened sink

Read the negotiated format from sink.PCMFormat(), then adapt each source before constructing the mixer. audio.ResampleSource changes the sample rate, audio.MapChannels applies a gain matrix, and audio.ConvertSource changes the sample type and encoding. Keep the signal in floating-point PCM through resampling and channel mixing if you want to quantize to integer PCM once.

The following function takes a mono float32 source and a negotiated stereo int16 sink. The two rows of the matrix each copy the mono input to one output plane in the sink's channel order.

func playMono(ctx context.Context, sink audio.Sink[int16], source audio.Source[float32]) error {
    target := sink.PCMFormat()
    rated, err := audio.ResampleSource(source, target.RateHz)
    if err != nil {
        return err
    }
    stereo, err := audio.MapChannels(rated, target.Layout, [][]float64{{1}, {1}})
    if err != nil {
        return err
    }
    converted, err := audio.ConvertSource[int16](stereo, target.Encoding)
    if err != nil {
        return err
    }
    mixer, err := audio.NewMixer(sink, converted)
    if err != nil {
        return err
    }
    return mixer.Run(ctx)
}

Pass an explicit matrix for surround downmixing. For a packed 24-bit raw PCM sink, use int32 and signed 24-bit encoding. Rate conversion uses a causal filter with startup delay. It retains advertised media duration and exact frame seeking when the source supplies those capabilities.

Development checks

Install pre-commit and run the following from the checkout:

CGO_ENABLED=0 go install golang.org/x/tools/cmd/goimports@v0.52.0
pre-commit install
CGO_ENABLED=0 GOTOOLCHAIN=local pre-commit run --all-files

Keep the Go binary directory on PATH so the hooks can find goimports. Pre-commit installs the pinned Go, Markdown, and YAML hook environments. Forgejo Actions runs the same hooks on pull requests and pushes to dev and main, then tests scalar fallbacks and cross-builds for Linux and macOS. CI uses Go 1.27.4 and also runs a vulnerability scan and a Linux race job with CGO enabled for instrumentation. On macOS ARM64, the local hook runs race tests with CGO disabled.

Use dev as the base for development branches. See the release runbook for candidate checks.

Documentation

Overview

Package audio decodes encoded audio and mixes typed planar PCM.

Open encoded audio with NewDecoder. Import the formats the application uses, or import github.com/BeatGlow/audio/codec/all and github.com/BeatGlow/audio/tracker/all for the built-in file and tracker formats. Read from the decoder as a Source or pass it to NewMixer. Use Decoder.NextBlock for a borrowed block when you can consume its data before the next read, seek or close.

Use NewRawSource and NewRawSink for interleaved raw PCM with a known format. NewReader and NewWriter handle individual sample words for sample-level code such as github.com/BeatGlow/audio/filter.

Pass a non-nil context to public operations. Use context.Background when no parent context is available. A nil context returns ErrNilContext.

Playback

Open the sink and read its PCMFormat. Use ResampleSource, MapChannels and ConvertSource when the rate, layout or encoding differs. The caller owns both endpoints and drains and closes a device when playback finishes. Context-aware endpoints can interrupt pending I/O. With ordinary I/O, cancel the transport or close the caller-owned pipe when needed.

File inspection and live PCM

See github.com/BeatGlow/audio/codec for header and tag inspection, github.com/BeatGlow/audio/waveform for file and live peak previews and History for bounded planar PCM windows.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// MonoLayout carries one monaural channel.
	MonoLayout = Layout{Mono}

	// StereoLayout carries front left and front right.
	StereoLayout = Layout{
		FrontLeft,
		FrontRight,
	}

	// StereoSubwooferLayout carries 2.1 audio in left, right, LFE order.
	StereoSubwooferLayout = Layout{
		FrontLeft,
		FrontRight,
		Subwoofer,
	}

	// Surround51Layout carries 5.1 audio with a back speaker pair.
	Surround51Layout = Layout{
		FrontLeft,
		FrontRight,
		FrontCenter,
		Subwoofer,
		BackLeft,
		BackRight,
	}

	// Surround71Layout carries 7.1 audio with both back and side speaker pairs.
	Surround71Layout = Layout{
		FrontLeft,
		FrontRight,
		FrontCenter,
		Subwoofer,
		BackLeft,
		BackRight,
		SideLeft,
		SideRight,
	}
)

Common layouts are listed in plane order. Treat them as read-only.

View Source
var ErrFormat = errors.New("audio: invalid PCM format")

ErrFormat indicates an invalid or incompatible PCM format.

View Source
var ErrNilContext = errors.New("audio: nil context")

ErrNilContext reports that an operation requires a non-nil context.

View Source
var ErrSeekRequired = errors.New("audio: container requires a seekable reader")

ErrSeekRequired means the container needs random access to the input.

View Source
var ErrUnsupportedFormat = errors.New("audio: unsupported audio codec format")

ErrUnsupportedFormat means no registered decoder recognized the input.

View Source
var ErrUnsupportedSampleRate = errors.New("audio: unsupported sample rate")

ErrUnsupportedSampleRate means the decoder cannot provide the requested rate.

Functions

func FrameAt added in v1.0.0

func FrameAt(at time.Duration, rate int) (int64, bool)

FrameAt returns the frame at or immediately before an elapsed time.

func RegisterFormat added in v1.0.0

func RegisterFormat(name, magic string, open OpenDecoderFunc)

RegisterFormat registers a decoder for magic at the start of an input. A '?' in magic matches any byte, as in image.RegisterFormat.

func RegisterFormatProbe added in v1.0.0

func RegisterFormatProbe(name string, size int, probe func([]byte) bool, open OpenDecoderFunc)

RegisterFormatProbe registers a decoder using a bounded prefix probe. The first matching registration supplies the decoder. Probe may receive a shorter prefix at EOF and must treat it as read-only. A missing name, nonpositive size, nil probe, or nil opener panics.

func TimeAtFrame added in v1.0.0

func TimeAtFrame(frame int64, rate int) (time.Duration, bool)

TimeAtFrame reports the first nanosecond at or after the frame's start. This rounding lets the reported time seek back to the same frame at audio rates.

func ValidateFormat added in v1.0.0

func ValidateFormat[T Sample](format Format) error

ValidateFormat checks the metadata and whether T can represent the samples.

Types

type BlockSizeHint added in v1.0.0

type BlockSizeHint interface {
	PreferredBlockFrames() int
}

BlockSizeHint suggests a preferred PCM read or write size in frames.

Example
package main

import (
	"bytes"
	"context"
	"encoding/binary"
	"fmt"

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

// A sink can tell the mixer its preferred block size.
type oneFrameSink struct {
	audio.Sink[uint8]
}

func (oneFrameSink) PreferredBlockFrames() int { return 1 }

func (s oneFrameSink) WriteFrames(src audio.Buffer[uint8]) (int, error) {
	if src.Frames() > 1 {
		panic("expected a one-frame block")
	}
	return s.Sink.WriteFrames(src)
}

func main() {
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.UnsignedPCM,
			Bits: 8,
		},
	}
	source, err := audio.NewRawSource[uint8](
		bytes.NewReader([]byte{128, 192}),
		format,
		binary.LittleEndian,
	)
	if err != nil {
		panic(err)
	}
	var output bytes.Buffer
	sink, err := audio.NewRawSink[uint8](&output, format, binary.LittleEndian)
	if err != nil {
		panic(err)
	}

	mix, err := audio.NewMixer(oneFrameSink{Sink: sink}, source)
	if err != nil {
		panic(err)
	}
	if err := mix.Run(context.Background()); err != nil {
		panic(err)
	}
	fmt.Printf("% x\n", output.Bytes())

}
Output:
80 c0

type Buffer

type Buffer[T Sample] [][]T

Buffer represents a multi channel audio buffer.

func BufferPlanes added in v1.0.0

func BufferPlanes[T Sample](planes [][]T, samples []T, frames, stride int) Buffer[T]

BufferPlanes sets each plane to a view of a contiguous sample allocation. Consecutive planes start stride samples apart and each view has frames samples.

func Deinterleave

func Deinterleave[T Sample](dst Buffer[T], src Samples[T], channels int) Buffer[T]

Deinterleave splits complete interleaved frames into channel planes.

Pass nil dst to allocate, or supply at least channels planes with room for all frames. The source and destination must use separate storage. Invalid channel counts, partial frames, and short destinations return nil before writing any samples.

Example
package main

import (
	"fmt"

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

func main() {
	pcm := audio.Samples[int16]{1, 10, 2, 20}
	planes := audio.Deinterleave(nil, pcm, 2)
	fmt.Println(planes[0], planes[1])
	fmt.Println(audio.Interleave(nil, planes))

}
Output:
[1 2] [10 20]
[1 10 2 20]

func (Buffer[T]) BitsPerSample

func (b Buffer[T]) BitsPerSample() int

BitsPerSample is the number of bits required to store one sample.

func (Buffer[T]) Channels

func (b Buffer[T]) Channels() int

Channels is the number of channels in the buffer.

func (Buffer[T]) Frames added in v1.0.0

func (b Buffer[T]) Frames() int

Frames reports the number of complete frames across all planes.

func (Buffer[T]) ToFloat

func (b Buffer[T]) ToFloat(dst [][]float64) [][]float64

ToFloat converts the buffers in b to [][]float64 in dst.

The provided buffer dst should be nil, or adequately sized to fit all samples in all channels.

func (Buffer[T]) ToMono

func (b Buffer[T]) ToMono(dst []T) int

ToMono converts a multi channel buffer to a mono channel by averaging the sounds per channel.

type Channel added in v1.0.0

type Channel string

Channel identifies a plane's speaker position or a caller-defined discrete channel.

const (
	Mono               Channel = "M"   // Monaural channel.
	FrontLeft          Channel = "FL"  // Front left.
	FrontRight         Channel = "FR"  // Front right.
	FrontCenter        Channel = "FC"  // Front center.
	Subwoofer          Channel = "LFE" // Low-frequency effects (LFE).
	BackLeft           Channel = "BL"  // Back left.
	BackRight          Channel = "BR"  // Back right.
	FrontLeftOfCenter  Channel = "FLC" // Between front left and center.
	FrontRightOfCenter Channel = "FRC" // Between front right and center.
	BackCenter         Channel = "BC"  // Back center.
	SideLeft           Channel = "SL"  // Side left.
	SideRight          Channel = "SR"  // Side right.
	TopCenter          Channel = "TC"  // Overhead center.
	TopFrontLeft       Channel = "TFL" // Overhead front left.
	TopFrontCenter     Channel = "TFC" // Overhead front center.
	TopFrontRight      Channel = "TFR" // Overhead front right.
	TopBackLeft        Channel = "TBL" // Overhead back left.
	TopBackCenter      Channel = "TBC" // Overhead back center.
	TopBackRight       Channel = "TBR" // Overhead back right.
)

type ContextSink added in v1.0.0

type ContextSink[T Sample] interface {
	Sink[T]
	WriteFramesContext(ctx context.Context, src Buffer[T]) (int, error)
}

ContextSink is a sink whose pending writes can be interrupted by context cancellation. WriteFramesContext reports frames accepted before it stopped. Any accepted frames remain owned by the sink.

Example
package main

import (
	"context"
	"errors"
	"io"

	"github.com/BeatGlow/audio"
)

// pcmQueue exchanges mono frames with an external producer or consumer.
type pcmQueue struct {
	frames chan int16
}

func (q pcmQueue) PCMFormat() audio.Format {
	return audio.Format{
		RateHz: 48000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.SignedPCM,
			Bits: 16,
		},
	}
}

func (q pcmQueue) ReadFrames(dst audio.Buffer[int16]) (int, error) {
	return q.ReadFramesContext(context.Background(), dst)
}

func (q pcmQueue) ReadFramesContext(ctx context.Context, dst audio.Buffer[int16]) (int, error) {
	for i := range dst.Frames() {
		select {
		case <-ctx.Done():
			return i, ctx.Err()
		case frame, ok := <-q.frames:
			if !ok {
				return i, io.EOF
			}
			dst[0][i] = frame
		}
	}
	return dst.Frames(), nil
}

func (q pcmQueue) WriteFrames(src audio.Buffer[int16]) (int, error) {
	return q.WriteFramesContext(context.Background(), src)
}

func (q pcmQueue) WriteFramesContext(ctx context.Context, src audio.Buffer[int16]) (int, error) {
	for i := range src.Frames() {
		select {
		case <-ctx.Done():
			return i, ctx.Err()
		case q.frames <- src[0][i]:
		}
	}
	return src.Frames(), nil
}

func main() {
	frames := make(chan int16, 1)
	var sink audio.ContextSink[int16] = pcmQueue{frames: frames}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	src := audio.Buffer[int16]{{42, 84}}
	if n, err := sink.WriteFramesContext(
		ctx,
		audio.Buffer[int16]{src[0][:1]},
	); n != 1 || err != nil {
		panic("expected one queued frame")
	}

	// The queue is full. Cancellation stops the pending write.
	cancel()
	if n, err := sink.WriteFramesContext(
		ctx,
		audio.Buffer[int16]{src[0][1:]},
	); n != 0 || !errors.Is(err, context.Canceled) {
		panic("write did not honor cancellation")
	}
	if <-frames != 42 {
		panic("the accepted frame was lost")
	}

}

type ContextSource added in v1.0.0

type ContextSource[T Sample] interface {
	Source[T]
	ReadFramesContext(ctx context.Context, dst Buffer[T]) (int, error)
}

ContextSource is a source whose pending reads can be interrupted by context cancellation. ReadFramesContext uses the same buffer and frame-count rules as Source.ReadFrames. A blocked read must return when ctx is canceled, without requiring the caller to close the source. A nil context returns ErrNilContext from library adapters.

Example
package main

import (
	"context"
	"errors"
	"io"

	"github.com/BeatGlow/audio"
)

// pcmQueue exchanges mono frames with an external producer or consumer.
type pcmQueue struct {
	frames chan int16
}

func (q pcmQueue) PCMFormat() audio.Format {
	return audio.Format{
		RateHz: 48000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.SignedPCM,
			Bits: 16,
		},
	}
}

func (q pcmQueue) ReadFrames(dst audio.Buffer[int16]) (int, error) {
	return q.ReadFramesContext(context.Background(), dst)
}

func (q pcmQueue) ReadFramesContext(ctx context.Context, dst audio.Buffer[int16]) (int, error) {
	for i := range dst.Frames() {
		select {
		case <-ctx.Done():
			return i, ctx.Err()
		case frame, ok := <-q.frames:
			if !ok {
				return i, io.EOF
			}
			dst[0][i] = frame
		}
	}
	return dst.Frames(), nil
}

func (q pcmQueue) WriteFrames(src audio.Buffer[int16]) (int, error) {
	return q.WriteFramesContext(context.Background(), src)
}

func (q pcmQueue) WriteFramesContext(ctx context.Context, src audio.Buffer[int16]) (int, error) {
	for i := range src.Frames() {
		select {
		case <-ctx.Done():
			return i, ctx.Err()
		case q.frames <- src[0][i]:
		}
	}
	return src.Frames(), nil
}

func main() {
	frames := make(chan int16, 1)
	frames <- 42
	var source audio.ContextSource[int16] = pcmQueue{frames: frames}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dst := audio.Buffer[int16]{{0}}
	if n, err := source.ReadFramesContext(ctx, dst); n != 1 || err != nil || dst[0][0] != 42 {
		panic("expected one queued frame")
	}

	// An empty queue can stop without the producer closing it.
	cancel()
	if n, err := source.ReadFramesContext(ctx, dst); n != 0 || !errors.Is(err, context.Canceled) {
		panic("read did not honor cancellation")
	}

}

type DecodeBackend added in v1.0.0

type DecodeBackend struct {
	Format              Format
	Read                func() (any, error)
	Close               func() error
	Metadata            func() tag.Metadata
	TakeMetadataUpdates func() []tag.Update
	FrameCount          func() (int64, bool)
	SeekFrame           func(int64) error
}

DecodeBackend provides the native operations for one registered stream. Read returns Buffer[int32], Buffer[float32], or Buffer[float64]. Unsigned native integer samples use the bit pattern of int32. Read and Close are required. Read may return PCM with its final error. The planes remain valid until the next read, seek or close. Optional metadata updates use native output frames and arrive in presentation order. Close releases the backend's resources. The caller owns the input.

type DecodeConfig added in v1.0.0

type DecodeConfig struct {
	SampleRate     int    // Requested output rate, or zero for the native rate.
	ICYInterval    int    // Audio bytes between ICY records, or zero.
	ICYStationName string // Optional ICY station name.
	// contains filtered or unexported fields
}

DecodeConfig holds the options passed to an OpenDecoderFunc.

func (DecodeConfig) FormatRegistered added in v1.0.0

func (c DecodeConfig) FormatRegistered(name string) bool

FormatRegistered reports whether another format can participate in a shared container or transport handled by the decoder.

type DecodeOption added in v1.0.0

type DecodeOption func(*DecodeConfig) error

DecodeOption configures a decoder before it opens the input.

func WithICY added in v1.0.0

func WithICY(interval int, stationName string) DecodeOption

WithICY sets the audio byte interval and station name of an ICY stream.

func WithSampleRate added in v1.0.0

func WithSampleRate(rate int) DecodeOption

WithSampleRate requests output at rate Hz. The decoder uses that rate natively when possible and resamples otherwise.

type Decoder added in v1.0.0

type Decoder[T Sample] interface {
	Source[T]

	// NextBlock returns the next nonempty block, or a terminal error.
	// Its read-only planes are borrowed until the next read, seek or close.
	// ReadFrames and NextBlock advance the same cursor.
	NextBlock() (Buffer[T], error)

	// Metadata reports the latest snapshot at the position already delivered.
	Metadata() tag.Metadata

	// TakeMetadataUpdates drains pending snapshots in presentation order.
	// Frame offsets use the output sample rate. If the queue fills, older
	// updates are discarded. A successful seek replaces the queue.
	TakeMetadataUpdates() []tag.Update

	// Close releases decoder resources. It leaves the input open.
	Close() error
}

Decoder reads typed, planar PCM and metadata from one cursor. Serialize calls. The caller owns the input and must keep it open while decoding or reading file-backed artwork. Some decoders also implement FrameSeeker, FrameCounter and DurationSource.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	file, err := os.Open("testdata/aac-lc-stereo-44100.m4a")
	if err != nil {
		panic(err)
	}
	defer func() { _ = file.Close() }()

	decoder, err := audio.NewDecoder[float32](context.Background(), file)
	if err != nil {
		panic(err)
	}
	defer func() { _ = decoder.Close() }()

	// Consume the borrowed planes before the next read or seek.
	block, err := decoder.NextBlock()
	if err != nil {
		panic(err)
	}
	fmt.Println(decoder.PCMFormat().RateHz, block.Channels(), block.Frames() > 0)

}
Output:
44100 2 true

func NewDecoder added in v1.0.0

func NewDecoder[T Sample](ctx context.Context, r io.Reader, options ...DecodeOption) (Decoder[T], error)

NewDecoder selects a registered format at r's current position and converts samples to T when needed. Import the desired format packages before opening. Matching integer types retain the native valid bits when they fit in T. The caller owns r. To interrupt a blocked read, cancel the underlying transport or close it. The decoder observes ctx before and after probing and uses it for subsequent reads and seeks. A nil context returns ErrNilContext.

Example
package main

import (
	"bytes"
	"context"
	"encoding/binary"
	"fmt"
	"os"

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

func main() {
	ctx := context.Background()
	input, err := os.Open("testdata/aac-lc-stereo-44100.m4a")
	if err != nil {
		panic(err)
	}
	defer func() { _ = input.Close() }()

	decoder, err := audio.NewDecoder[int16](ctx, input)
	if err != nil {
		panic(err)
	}
	defer func() { _ = decoder.Close() }()

	format := decoder.PCMFormat()
	var output bytes.Buffer
	sink, err := audio.NewRawSink[int16](&output, format, binary.LittleEndian)
	if err != nil {
		panic(err)
	}
	mixer, err := audio.NewMixer(sink, decoder)
	if err != nil {
		panic(err)
	}
	if err := mixer.Run(ctx); err != nil {
		panic(err)
	}

	fmt.Printf(
		"%d Hz, %d channels, PCM written %t\n",
		format.RateHz,
		len(format.Layout),
		output.Len() > 0,
	)
}
Output:
44100 Hz, 2 channels, PCM written true

type DurationSource added in v1.0.0

type DurationSource interface {
	Duration() (time.Duration, bool)
}

DurationSource reports the presented duration, if known.

Example
package main

import (
	"bytes"
	"encoding/binary"
	"fmt"

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

func main() {
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.UnsignedPCM,
			Bits: 8,
		},
	}
	source, err := audio.NewRawSource[uint8](
		bytes.NewReader([]byte{128, 192}),
		format,
		binary.LittleEndian,
	)
	if err != nil {
		panic(err)
	}
	if timed, ok := source.(audio.DurationSource); ok {
		duration, known := timed.Duration()
		fmt.Println(duration, known)
	}

}
Output:
250µs true

type Encoding added in v1.0.0

type Encoding struct {
	Kind Kind
	Bits int // Valid integer depth or IEEE float width.
}

Encoding describes right-justified integer PCM or floating-point PCM.

type Format

type Format struct {
	RateHz   int    // Samples per second per channel.
	Layout   Layout // Channel labels in plane order.
	Encoding Encoding
}

Format describes the samples crossing a PCM endpoint.

func (Format) Clone added in v1.0.0

func (f Format) Clone() Format

Clone returns a format whose layout has independent storage.

func (Format) Equal added in v1.0.0

func (f Format) Equal(other Format) bool

Equal compares rate, encoding, and ordered channel labels.

type FrameCounter added in v1.0.0

type FrameCounter interface {
	FrameCount() (int64, bool)
}

FrameCounter reports the presentation frame count at the output sample rate. The boolean is false when the count is unknown.

Example
package main

import (
	"context"
	"fmt"
	"os"

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

func main() {
	file, err := os.Open("testdata/aac-lc-stereo-44100.m4a")
	if err != nil {
		panic(err)
	}
	defer func() { _ = file.Close() }()

	decoder, err := audio.NewDecoder[float32](
		context.Background(),
		file,
		audio.WithSampleRate(48000),
	)
	if err != nil {
		panic(err)
	}
	defer func() { _ = decoder.Close() }()

	// Check the optional capability. Counts use the output sample rate.
	if counter, ok := decoder.(audio.FrameCounter); ok {
		frames, known := counter.FrameCount()
		fmt.Println(decoder.PCMFormat().RateHz, known, frames > 0)
	}

}
Output:
48000 true true

type FrameSeeker added in v1.0.0

type FrameSeeker interface {
	SeekFrame(int64) error
}

FrameSeeker seeks to an exact, zero-based frame in the output timeline. If the frame count is known, seeking to it positions the source at EOF. Use FrameAt to convert a time to a frame number.

Example
package main

import (
	"bytes"
	"encoding/binary"
	"fmt"

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

func main() {
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.UnsignedPCM,
			Bits: 8,
		},
	}
	source, err := audio.NewRawSource[uint8](
		bytes.NewReader([]byte{128, 192}),
		format,
		binary.LittleEndian,
	)
	if err != nil {
		panic(err)
	}
	// This input is seekable and frame-aligned.
	if seeker, ok := source.(audio.FrameSeeker); ok {
		if err := seeker.SeekFrame(1); err != nil {
			panic(err)
		}
		dst := audio.Buffer[uint8]{{0}}
		n, err := source.ReadFrames(dst)
		fmt.Printf("% x %v\n", dst[0][:n], err)
	}

}
Output:
c0 <nil>

type History added in v1.0.0

type History[T Sample] struct {
	// contains filtered or unexported fields
}

History stores bounded PCM windows for concurrent stream and render callers. Its zero value cannot store frames.

func NewHistory added in v1.0.0

func NewHistory[T Sample](format Format, capacityFrames int) (*History[T], error)

NewHistory returns a planar history with the specified PCM format and capacity. A nonpositive capacity creates an empty history that cannot store frames.

func (*History[T]) AddBlock added in v1.0.0

func (h *History[T]) AddBlock(block Buffer[T], epoch, firstFrame uint64) error

AddBlock copies frames in the history's plane order at firstFrame within epoch. Short gaps are filled with silence. Gaps at least as large as the capacity discard previous frames. Older capture epochs and duplicate frames are ignored.

func (*History[T]) AdvanceEpoch added in v1.0.0

func (h *History[T]) AdvanceEpoch(epoch uint64)

AdvanceEpoch drops history when capture advances to a newer epoch.

func (*History[T]) CaptureEpoch added in v1.0.0

func (h *History[T]) CaptureEpoch() uint64

CaptureEpoch returns the most recent capture epoch accepted or advanced to.

func (*History[T]) PCMFormat added in v1.0.0

func (h *History[T]) PCMFormat() Format

PCMFormat returns the fixed format in which History stores its planes.

func (*History[T]) Snapshot added in v1.0.0

func (h *History[T]) Snapshot(dst Buffer[T]) bool

Snapshot copies the latest complete window, including silence for short gaps. The destination must have one equally sized plane per history channel.

func (*History[T]) SnapshotAt added in v1.0.0

func (h *History[T]) SnapshotAt(dst Buffer[T], firstEnd, hopFrames uint64) (ok bool, end, generation, gridStart uint64)

SnapshotAt copies the latest complete window on the hop grid. firstEnd and end are exclusive frame offsets within the capture epoch. firstEnd is the earliest desired boundary and gridStart is that boundary adjusted for the start of the available segment. generation changes on capture restarts and gaps that discard the previous history.

func (*History[T]) SnapshotConsecutive added in v1.0.0

func (h *History[T]) SnapshotConsecutive(dst Buffer[T]) (generation uint64, ok bool)

SnapshotConsecutive copies the latest complete window of real PCM. Its local generation changes on every gap and capture epoch advance.

func (*History[T]) SnapshotGrowingAt added in v1.0.0

func (h *History[T]) SnapshotGrowingAt(dst Buffer[T], firstEnd, hopFrames uint64) (ok bool, end, generation, gridStart uint64, frames int)

SnapshotGrowingAt uses the available PCM until the destination fills, then follows the same hop grid as SnapshotAt. On success, it writes frames samples per channel.

type Kind added in v1.0.0

type Kind uint8

Kind is the numerical interpretation of a PCM sample.

const (
	SignedPCM   Kind = iota + 1 // Signed integer PCM.
	UnsignedPCM                 // Unsigned integer PCM.
	FloatPCM                    // Floating-point PCM.
)

type Layout added in v1.0.0

type Layout []Channel

Layout lists channel positions in plane order.

func LayoutFromMask added in v1.0.0

func LayoutFromMask(channels int, mask uint32) Layout

LayoutFromMask reports the ordered speaker positions for a WAVE speaker mask, falling back to the conventional layout shared by FLAC and unmasked WAVE.

type Mixer added in v1.0.0

type Mixer[T Sample] struct {
	// contains filtered or unexported fields
}

Mixer runs a fixed group of PCM sources into a sink. Construct it with NewMixer.

Example
package main

import (
	"bytes"
	"context"
	"encoding/binary"
	"fmt"

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

func main() {
	// Both sources and the sink use the same PCM format.
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.UnsignedPCM,
			Bits: 8,
		},
	}
	var sources []audio.Source[uint8]
	// In unsigned 8-bit PCM, 0x80 represents silence.
	for _, samples := range [][]byte{
		{0x90, 0x90},
		{0xa0, 0x80},
	} {
		source, err := audio.NewRawSource[uint8](
			bytes.NewReader(samples),
			format,
			binary.LittleEndian,
		)
		if err != nil {
			panic(err)
		}
		sources = append(sources, source)
	}

	var output bytes.Buffer
	sink, err := audio.NewRawSink[uint8](&output, format, binary.LittleEndian)
	if err != nil {
		panic(err)
	}
	mixer, err := audio.NewMixer(sink, sources...)
	if err != nil {
		panic(err)
	}
	if err := mixer.Run(context.Background()); err != nil {
		panic(err)
	}
	fmt.Printf("% x\n", output.Bytes())

}
Output:
b0 90

func NewMixer added in v1.0.0

func NewMixer[T Sample](sink Sink[T], sources ...Source[T]) (*Mixer[T], error)

NewMixer prepares a mix with one fixed PCM format. Sources and the sink remain caller-owned. Each mixer runs once. Use PCM adapters to change a source or sink's layout, rate, or sample format.

func (*Mixer[T]) PCMFormat added in v1.0.0

func (m *Mixer[T]) PCMFormat() Format

PCMFormat returns a copy of the format shared by the sources and sink.

func (*Mixer[T]) Run added in v1.0.0

func (m *Mixer[T]) Run(ctx context.Context) error

Run mixes until the sources finish, an operation fails, or ctx is canceled. Each mixer can run once. Cancellation observed after I/O takes precedence over its result. Run drops any block it has yet to write.

Run calls context-aware methods when endpoints implement them. The caller must arrange to unblock plain endpoints. The caller also owns endpoint draining and closing. A nil context returns ErrNilContext.

type OpenDecoderFunc added in v1.0.0

type OpenDecoderFunc func(context.Context, io.Reader, DecodeConfig) (DecodeBackend, error)

OpenDecoderFunc opens a registered decoder at the input's original position. The caller owns the input. Return a backend that releases its own resources.

type Reader

type Reader[T Sample] interface {
	ReadSamples(Samples[T]) (int, error)
}

Reader can read samples.

Example

Reader works in individual sample words without channel layout information.

package main

import (
	"bytes"
	"encoding/binary"
	"fmt"

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

func main() {
	reader := audio.NewReader[int16](bytes.NewReader([]byte{1, 0, 2, 0}), binary.LittleEndian)
	samples := make(audio.Samples[int16], 2)
	n, err := reader.ReadSamples(samples)
	fmt.Println(samples[:n], err)

}
Output:
[1 2] <nil>

func NewReader

func NewReader[T Sample](r io.Reader, order binary.ByteOrder) Reader[T]

NewReader returns a Reader that can read from any io.Reader.

type Sample

type Sample interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
		~float32 | ~float64
}

Sample permits the numeric types used by raw sample-word I/O. PCM streams support 8-, 16-, and 32-bit signed and unsigned integers, and 32- and 64-bit floats, including named forms. See ValidateFormat.

Example
package main

import (
	"fmt"

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

// A generic helper can accept the sample types used by audio.Buffer.
func firstSample[T audio.Sample](plane []T) T { return plane[0] }

func main() {
	fmt.Println(firstSample([]int16{1200}), firstSample([]float32{0.5}))

}
Output:
1200 0.5

type Samples

type Samples[T Sample] []T

Samples represents a mono audio buffer, or a single channel.

func Interleave

func Interleave[T Sample](dst Samples[T], src Buffer[T]) Samples[T]

Interleave copies equal-length channel planes into one interleaved slice.

Pass nil dst to allocate, or supply room for all samples. The source and destination must use separate storage. Unequal planes and short destinations return nil before writing any samples.

func (Samples[T]) BitsPerSample

func (s Samples[T]) BitsPerSample() int

BitsPerSample is the number of bits required to store one sample.

func (Samples[T]) Decode

func (s Samples[T]) Decode(b []byte, order binary.ByteOrder)

Decode reads samples encoded in b using the specified byte order.

func (Samples[T]) DecodeFrom

func (s Samples[T]) DecodeFrom(r io.Reader, order binary.ByteOrder) (n int, err error)

DecodeFrom reads samples from r to s.

func (Samples[T]) DecodeFromChunked

func (s Samples[T]) DecodeFromChunked(r io.Reader, order binary.ByteOrder, chunkSize int) (int, error)

DecodeFromChunked reads samples from r to s in chunks of at most chunkSize samples. It returns the number of complete samples decoded.

func (Samples[T]) Encode

func (s Samples[T]) Encode(b []byte, order binary.ByteOrder)

Encode writes the sample slice as bytes in b.

func (Samples[T]) EncodeTo

func (s Samples[T]) EncodeTo(w io.Writer, order binary.ByteOrder) (int, error)

EncodeTo writes samples contained in s to w.

func (Samples[T]) EncodeToChunked

func (s Samples[T]) EncodeToChunked(w io.Writer, order binary.ByteOrder, chunkSize int) (int, error)

EncodeToChunked writes samples to w in chunks of at most chunkSize samples. It returns the number of complete samples written.

func (Samples[T]) ToComplex

func (s Samples[T]) ToComplex(dst []complex128) []complex128

ToComplex converts the samples in s to []complex128 in dst.

func (Samples[T]) ToFloat

func (s Samples[T]) ToFloat(dst []float64) []float64

ToFloat converts samples in s to normalized float64 samples in dst. Pass a nil destination to allocate storage, or provide room for all samples.

func (Samples[T]) ToInt16

func (s Samples[T]) ToInt16(dst []int16) []int16

ToInt16 converts samples in s to signed 16-bit PCM in dst. The midpoint of unsigned PCM is treated as silence. Floating-point samples are rounded to the nearest PCM value and clipped to the int16 range. NaN becomes silence.

The provided buffer dst should be nil, or adequately sized to fit all samples.

type Sink added in v1.0.0

type Sink[T Sample] interface {
	PCMFormat() Format
	WriteFrames(src Buffer[T]) (int, error)
}

Sink consumes PCM channel planes. WriteFrames may accept a prefix and returns the number of frames accepted. The sink reads the planes only during the call. Retry an unwritten suffix after a short write with a nil error.

Example

Send one plane per channel, in the order reported by PCMFormat.

package main

import (
	"bytes"
	"encoding/binary"
	"fmt"

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

func main() {
	var output bytes.Buffer
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.StereoLayout,
		Encoding: audio.Encoding{
			Kind: audio.UnsignedPCM,
			Bits: 8,
		},
	}
	sink, err := audio.NewRawSink[uint8](&output, format, binary.LittleEndian)
	if err != nil {
		panic(err)
	}
	n, err := sink.WriteFrames(audio.Buffer[uint8]{
		{128, 192},
		{64, 128},
	})
	fmt.Printf("%d % x %v\n", n, output.Bytes(), err)

}
Output:
2 80 40 c0 80 <nil>

func NewRawSink added in v1.0.0

func NewRawSink[T Sample](w io.Writer, format Format, order binary.ByteOrder) (Sink[T], error)

NewRawSink writes interleaved PCM in the requested byte order. Integer samples occupy 8, 16, 24, or 32 bits. The caller owns the writer.

type Source added in v1.0.0

type Source[T Sample] interface {
	PCMFormat() Format
	ReadFrames(dst Buffer[T]) (int, error)
}

Source generates PCM in caller-owned channel planes. ReadFrames returns the valid frame count, which may be positive with an error. The source may reuse its own state as soon as the read returns. Use the channel order in PCMFormat, and consume the returned prefix of each plane before handling the error. End of input is io.EOF, possibly with valid frames. Serialize calls unless the implementation documents concurrent use.

Example

Read PCM in caller-owned channel planes.

package main

import (
	"bytes"
	"encoding/binary"
	"fmt"

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

func main() {
	format := audio.Format{
		RateHz: 8000,
		Layout: audio.MonoLayout,
		Encoding: audio.Encoding{
			Kind: audio.UnsignedPCM,
			Bits: 8,
		},
	}
	source, err := audio.NewRawSource[uint8](
		bytes.NewReader([]byte{128, 192}),
		format,
		binary.LittleEndian,
	)
	if err != nil {
		panic(err)
	}
	dst := audio.Buffer[uint8]{make([]uint8, 2)}
	n, err := source.ReadFrames(dst)
	fmt.Printf("% x %v\n", dst[0][:n], err)

}
Output:
80 c0 <nil>

func ConvertSource added in v1.0.0

func ConvertSource[To, From Sample](source Source[From], encoding Encoding) (Source[To], error)

ConvertSource presents source in encoding, keeping its sample rate and layout. Matching encodings and sample types return the validated source directly. The caller owns source and must read or seek it through the adapter while it is in use.

Conversion centers unsigned PCM at its midpoint and scales integer PCM according to its valid bit depth. Integer output rounds to nearest, with ties away from zero, saturates to the valid range, and represents NaN as silence. Floating-point output is unclipped and keeps nonfinite values.

func MapChannels added in v1.0.0

func MapChannels[T Sample](source Source[T], output Layout, matrix [][]float64) (Source[T], error)

MapChannels presents source with the requested output layout and the same rate and encoding. Matrix rows correspond to output planes and columns to input planes, in their respective layout orders. Each output sample is the sum of its connected input samples multiplied by their gains. A zero gain disconnects that input, including any nonfinite samples it carries.

Gains must be finite. Integer inputs are centered about their silence code; results round to nearest with ties away from zero, saturate, and encode NaN as silence. Floating-point mixes follow IEEE arithmetic without clipping.

The caller owns source and must read or seek it through the adapter while it is in use. An identity map returns the validated source directly. Other maps retain their own copy of the layout and gains.

func NewRawSource added in v1.0.0

func NewRawSource[T Sample](r io.Reader, format Format, order binary.ByteOrder) (Source[T], error)

NewRawSource opens interleaved PCM at the reader's current position. Integer samples occupy 8, 16, 24, or 32 bits. The caller owns the reader. If r is seekable and the remaining length is frame-aligned, the source also implements FrameSeeker and DurationSource. Frame zero is r's opening position.

func ResampleSource added in v1.0.0

func ResampleSource[T Sample](source Source[T], outputHz int) (Source[T], error)

ResampleSource changes a source's sample rate while preserving its channel order and encoding. It returns the original source when rates already match. For a source with N input frames, the adapter emits ceil(N*outputHz/inputHz) frames. The causal filter starts with silent history, delays the signal by half its filter length in input frames, and does not append a filter tail. The adapter preserves advertised media duration. A source with exact frame seeking retains that capability at the new rate. The caller owns the source and must read it exclusively through the adapter while resampling. If a context-aware read is canceled, the next read can resume with a fresh context and retain buffered PCM.

type Writer

type Writer[T Sample] interface {
	WriteSamples(Samples[T]) (int, error)
}

Writer can write samples.

Example
package main

import (
	"bytes"
	"encoding/binary"
	"fmt"

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

func main() {
	var output bytes.Buffer
	writer := audio.NewWriter[int16](&output, binary.LittleEndian)
	n, err := writer.WriteSamples(audio.Samples[int16]{1, 2})
	fmt.Printf("%d % x %v\n", n, output.Bytes(), err)

}
Output:
2 01 00 02 00 <nil>

func NewWriter

func NewWriter[T Sample](w io.Writer, order binary.ByteOrder) Writer[T]

NewWriter returns a Writer that can write to any io.Writer.

Directories

Path Synopsis
Package codec provides shared file-decoder support and reads tags and artwork.
Package codec provides shared file-decoder support and reads tags and artwork.
aac
Package aac registers AAC in ADTS and MP4 with audio.
Package aac registers AAC in ADTS and MP4 with audio.
aiff
Package aiff registers AIFF and AIFC decoding with audio.
Package aiff registers AIFF and AIFC decoding with audio.
alac
Package alac registers ALAC decoding with audio.
Package alac registers ALAC decoding with audio.
all
Package all registers all built-in file codecs with audio.
Package all registers all built-in file codecs with audio.
flac
Package flac registers FLAC decoding with audio.
Package flac registers FLAC decoding with audio.
matroska
Package matroska registers Matroska and WebM audio decoding with audio.
Package matroska registers Matroska and WebM audio decoding with audio.
mp3
Package mp3 registers MP3 decoding with audio.
Package mp3 registers MP3 decoding with audio.
wave
Package wave registers WAVE decoding with audio.
Package wave registers WAVE decoding with audio.
Package driver opens the default audio playback device for the host platform.
Package driver opens the default audio playback device for the host platform.
alsa
Package alsa discovers ALSA PCM endpoints and opens Linux playback streams.
Package alsa discovers ALSA PCM endpoints and opens Linux playback streams.
coreaudio
Package coreaudio plays PCM through the macOS default output device.
Package coreaudio plays PCM through the macOS default output device.
dsp
Package dsp analyzes, mixes, and resamples PCM.
Package dsp analyzes, mixes, and resamples PCM.
filter
Package filter designs and applies finite impulse response filters.
Package filter designs and applies finite impulse response filters.
fourier
Package fourier computes forward and inverse discrete Fourier transforms over complex samples.
Package fourier computes forward and inverse discrete Fourier transforms over complex samples.
window
Package window generates weights for time-domain samples.
Package window generates weights for time-domain samples.
Package filter provides low-pass and high-pass filters for sample slices and a fixed delay for sample readers.
Package filter provides low-pass and high-pass filters for sample slices and a fixed delay for sample readers.
internal
aaclc
Package aaclc decodes 5.1 AAC-LC access units (channel configuration 6).
Package aaclc decodes 5.1 AAC-LC access units (channel configuration 6).
aiff
Package aiff reads metadata from AIFF and AIFF-C containers.
Package aiff reads metadata from AIFF and AIFF-C containers.
alac
Package alac decodes Apple Lossless audio in progressive MP4 files.
Package alac decodes Apple Lossless audio in progressive MP4 files.
alac/mp4
Package mp4 extracts ALAC audio tracks and sample tables from MP4/M4A containers.
Package mp4 extracts ALAC audio tracks and sample tables from MP4/M4A containers.
cpu
Package cpu reports the SIMD features available to BeatGlow's codec kernels.
Package cpu reports the SIMD features available to BeatGlow's codec kernels.
crc
Package crc computes FLAC frame CRCs.
Package crc computes FLAC frame CRCs.
dolby
Package dolby decodes AC-3 and single-program E-AC-3 packets to planar PCM.
Package dolby decodes AC-3 and single-program E-AC-3 packets to planar PCM.
dts
The scale books and RMS table adapt the published ETSI rows transcribed by OxideAV.
The scale books and RMS table adapt the published ETSI rows transcribed by OxideAV.
flac
Package flac decodes native FLAC streams for file analysis.
Package flac decodes native FLAC streams for file analysis.
gf1
Package gf1 provides the fixed-point sample and mixer operations shared by tracker drivers that target the Gravis Ultrasound GF1.
Package gf1 provides the fixed-point sample and mixer operations shared by tracker drivers that target the Gravis Ultrasound GF1.
heaac/adts
Package adts builds and parses Audio Data Transport Stream headers.
Package adts builds and parses Audio Data Transport Stream headers.
heaac/internal/bits
Package bits implements the MSB-first bit I/O used by AAC syntax elements.
Package bits implements the MSB-first bit I/O used by AAC syntax elements.
heaac/internal/coder
Package coder implements the quantization and entropy-coding layer shared by the AAC encoder and decoder: scalefactor and spectral Huffman codes (ISO/IEC 14496-3 §4.6.3) and the inverse quantizer (§4.6.2).
Package coder implements the quantization and entropy-coding layer shared by the AAC encoder and decoder: scalefactor and spectral Huffman codes (ISO/IEC 14496-3 §4.6.3) and the inverse quantizer (§4.6.2).
heaac/internal/tables
Package tables contains data tables shared by the AAC codec stages.
Package tables contains data tables shared by the AAC codec stages.
heaac/internal/transform
Package transform implements the inverse modified discrete cosine transform and synthesis windows used by AAC (ISO/IEC 14496-3 §4.6.11).
Package transform implements the inverse modified discrete cosine transform and synthesis windows used by AAC (ISO/IEC 14496-3 §4.6.11).
iffchunks
Package iffchunks reads bounded chunk headers in IFF-based audio containers.
Package iffchunks reads bounded chunk headers in IFF-based audio containers.
m4a
Package m4a demuxes MPEG-4 Audio into access units for the audio decoder.
Package m4a demuxes MPEG-4 Audio into access units for the audio decoder.
m4a/box
Package box parses ISO Base Media File Format boxes for the AAC demuxer.
Package box parses ISO Base Media File Format boxes for the AAC demuxer.
mp3
Package mp3 implements the MPEG-1/2/2.5 Layer III decoder core.
Package mp3 implements the MPEG-1/2/2.5 Layer III decoder core.
mp3/bits
Package bits provides an MSB-first bit reader matching the bit-position and overrun semantics of minimp3's bs_t/get_bits (see 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 minimp3.h, CC0-1.0), which every decode unit in this package reads its bitstream through.
opus
Package opus decodes elementary Opus packets to borrowed planar PCM.
Package opus decodes elementary Opus packets to borrowed planar PCM.
opus/pion
Package opus provides a Opus Audio Codec RFC 6716 implementation
Package opus provides a Opus Audio Codec RFC 6716 implementation
opus/pion/internal/bitdepth
Package bitdepth provides utilities to convert between different audio bitdepths
Package bitdepth provides utilities to convert between different audio bitdepths
opus/pion/internal/celt
Package celt implements the MDCT layer of the Opus decoder.
Package celt implements the MDCT layer of the Opus decoder.
opus/pion/internal/rangecoding
Package rangecoding provides a Range coder for the Opus bitstream
Package rangecoding provides a Range coder for the Opus bitstream
opus/pion/internal/resample/silk
Package silkresample ports the RFC 6716 SILK resampler.
Package silkresample ports the RFC 6716 SILK resampler.
opus/pion/internal/silk
Package silk provides a Silk coder
Package silk provides a Silk coder
opus/pion/internal/slicetools
Package slicetools provides shared helpers for reusing scratch slices.
Package slicetools provides shared helpers for reusing scratch slices.
st3sinc
Package st3sinc resamples the hardware mixers used by Scream Tracker 3.
Package st3sinc resamples the hardware mixers used by Scream Tracker 3.
tagdata
Package tagdata defines the values shared by the codec metadata parsers.
Package tagdata defines the values shared by the codec metadata parsers.
test/internal/authorplay
Package authorplay builds the authored Korobeiniki demo score.
Package authorplay builds the authored Korobeiniki demo score.
test/internal/demoplay
Package demoplay plays or renders a bounded synth demo.
Package demoplay plays or renders a bounded synth demo.
test/internal/demoqa
Package demoqa inspects rendered synth demos.
Package demoqa inspects rendered synth demos.
test/synth/envelope-and-sample command
Command envelope-and-sample demonstrates pitched samples and voice envelopes.
Command envelope-and-sample demonstrates pitched samples and voice envelopes.
test/synth/multitrack-score command
Command multitrack-score plays or renders a short sequenced arrangement.
Command multitrack-score plays or renders a short sequenced arrangement.
test/synth/scheduled-sine command
Command scheduled-sine plays or renders a short phrase with timed controls.
Command scheduled-sine plays or renders a short phrase with timed controls.
test/tracker/author-and-play command
Command author-and-play builds and plays an authored tracker score.
Command author-and-play builds and plays an authored tracker score.
test/tracker/baseline-effects command
Command baseline-effects plays independently authored tracker modules.
Command baseline-effects plays independently authored tracker modules.
test/tracker/internal/verify
Package verify streams tracker renders and produces comparable PCM and tick records.
Package verify streams tracker renders and produces comparable PCM and tick records.
test/tracker/it-instruments command
Command it-instruments renders the ranked IT excerpt and companion demos.
Command it-instruments renders the ranked IT excerpt and companion demos.
test/tracker/it-verification command
Command it-verification replays the pinned IT songs and validation fixtures.
Command it-verification replays the pinned IT songs and validation fixtures.
test/tracker/mod-verification command
Command mod-verification verifies an unmodified Mod Archive download corpus.
Command mod-verification verifies an unmodified Mod Archive download corpus.
test/tracker/module-replay command
Command module-replay plays the four native tracker module fixtures.
Command module-replay plays the four native tracker module fixtures.
test/tracker/mtm-verification command
Command mtm-verification compares the ranked corpus with pinned playback references.
Command mtm-verification compares the ranked corpus with pinned playback references.
test/tracker/repeatable-render command
Command repeatable-render checks an archive excerpt at two PCM rates.
Command repeatable-render checks an archive excerpt at two PCM rates.
test/tracker/s3m-verification command
Command s3m-verification renders playback from the pinned S3M corpus.
Command s3m-verification renders playback from the pinned S3M corpus.
test/tracker/stm-verification command
Command stm-verification audits first-pass tracker playback and renders the ranked preview.
Command stm-verification audits first-pass tracker playback and renders the ranked preview.
test/tracker/tick-effects command
Command tick-effects plays or renders a small in-Go tracker replay.
Command tick-effects plays or renders a small in-Go tracker replay.
test/tracker/xm-verification command
Command xm-verification audits the pinned Mod Archive XM corpus.
Command xm-verification audits the pinned Mod Archive XM corpus.
truehd
Package truehd parses framed TrueHD (FBA) access units and reconstructs channel-based PCM for the supported restart syntax and layouts.
Package truehd parses framed TrueHD (FBA) access units and reconstructs channel-based PCM for the supported restart syntax and layouts.
Package synth generates typed PCM sources.
Package synth generates typed PCM sources.
internal/opl2
Package opl2 renders the melodic mode of the Yamaha YM3812.
Package opl2 renders the melodic mode of the Yamaha YM3812.
Package tag describes audio metadata, including normalized fields, native tags, embedded artwork, and snapshots delivered during playback.
Package tag describes audio metadata, including normalized fields, native tags, embedded artwork, and snapshots delivered during playback.
Package tracker renders tick-based replays using synth voices.
Package tracker renders tick-based replays using synth voices.
all
Package all registers all built-in tracker formats with audio.
Package all registers all built-in tracker formats with audio.
internal/module
Package module provides byte and PCM helpers for native tracker formats.
Package module provides byte and PCM helpers for native tracker formats.
it
Package it loads and replays Impulse Tracker modules.
Package it loads and replays Impulse Tracker modules.
mod
Package mod loads four-channel M.K. modules and replays their PCM samples.
Package mod loads four-channel M.K. modules and replays their PCM samples.
mtm
Package mtm loads MultiTracker modules with reusable tracks and PCM samples.
Package mtm loads MultiTracker modules with reusable tracks and PCM samples.
s3m
Package s3m loads and replays Scream Tracker 3 modules.
Package s3m loads and replays Scream Tracker 3 modules.
stm
Package stm loads Scream Tracker 2 embedded-sample modules.
Package stm loads Scream Tracker 2 embedded-sample modules.
xm
Package xm loads FastTracker 2 XM 1.04 modules and replays pitched PCM.
Package xm loads FastTracker 2 XM 1.04 modules and replays pitched PCM.
Package waveform generates stereo peak envelopes for files, CUE tracks, and live PCM.
Package waveform generates stereo peak envelopes for files, CUE tracks, and live PCM.

Jump to

Keyboard shortcuts

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