dsp

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 17 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.

Documentation

Overview

Package dsp holds the real-time stages that run after the ring: gain, effects, metering. Everything in this package runs on the audio path, so a stage must not allocate, must not block, and must not take a lock a control goroutine can hold while waiting on the audio thread.

Gain is the first such stage. The effect framework beside it follows the same shape as decode's codec registry: an effect is registered under a kind and an implementation name, a preset names the kind, and the highest-weight implementation wins the automatic choice. What differs is that an effect is editable while audio is running, so its parameters are published by an atomic swap instead of written in place.

Index

Constants

View Source
const (
	BassEnhancerAmount      = "amount"
	BassEnhancerHarmonics   = "harmonics"
	BassEnhancerScope       = "scope"
	BassEnhancerFloor       = "floor"
	BassEnhancerFloorActive = "floor-active"
	BassEnhancerBlend       = "blend"
	BassEnhancerListen      = "listen"
)

Bass enhancer parameter keys matching preset names.

View Source
const (
	ConvolverKernel   = "kernel-name"
	ConvolverIRWidth  = "ir-width"
	ConvolverAutogain = "autogain"
)

Convolver parameter keys.

View Source
const (
	CrossfeedCutoff = "cutoff"
	CrossfeedFeed   = "feed"
)

Crossfeed parameter keys. The names match the preset vocabulary so a stored preset maps one to one.

View Source
const (
	FadeDuration = "duration"
	FadeMode     = "mode"
)

Fade parameter keys.

View Source
const (
	FadeModeIn  = "in"
	FadeModeOut = "out"
)

Fade modes. "in" ramps 0 to 1, "out" ramps 1 to 0.

View Source
const (
	MinVolume = 0.0
	MaxVolume = 1.0
)

MinVolume and MaxVolume bound the gain. The range is closed on both ends: 0 is silence and 1 is unity. Values above unity are not accepted because a post-ring gain has no limiter behind it, so amplifying only moves the clipping point, it cannot prevent it. When a limiter stage lands, raising MaxVolume is that stage's decision, not this one's.

View Source
const (
	LimiterThreshold    = "threshold"
	LimiterAttack       = "attack"
	LimiterRelease      = "release"
	LimiterLookahead    = "lookahead"
	LimiterStereoLink   = "stereo-link"
	LimiterMode         = "mode"
	LimiterOversampling = "oversampling"
)

Limiter parameter keys matching preset names.

View Source
const (
	MaximizerThreshold = "threshold"
	MaximizerRelease   = "release"
	MaximizerCeiling   = "ceiling"
)

Maximizer parameter keys matching preset names.

View Source
const (
	ParamInputGain  = "input-gain"
	ParamOutputGain = "output-gain"
)

ParamInputGain and ParamOutputGain are the standard per-effect gains in dB, applied before and after the effect's own processing. They exist so a preset maps one to one onto a stage and so one stage can be trimmed without touching the master volume.

View Source
const (
	MeterIn  = "in"
	MeterOut = "out"
)

Standard meter keys. An effect that implements Metered reports levels under these names, so a UI can draw a fixed input/output pair without knowing which effect it is looking at. A missing key means "this effect does not measure it", never "zero".

View Source
const (
	EqualizerNumBands = "num-bands"
)

Equalizer parameter keys.

View Source
const GroupGain = "Gain"

GroupGain is the section the standard gains live in. A UI pins this group so the input and output trim always sit together, above whatever sections the effect itself declares.

View Source
const MeterReduction = "reduction"

MeterReduction is the gain-reduction meter key reported by dynamics effects.

View Source
const ParamBypass = "bypass"

ParamBypass is the parameter every effect carries to drop its processing. An effect must still accept Process while bypassed and pass audio through.

Variables

View Source
var Default = NewRegistry()

Default is the registry populated by the init functions in this package.

View Source
var ErrInvalidPreset = errors.New("dsp: invalid EasyEffects preset")

ErrInvalidPreset indicates the JSON document is not a valid EasyEffects preset.

View Source
var ErrUnknownImpl = errors.New("dsp: unknown effect implementation")

ErrUnknownImpl means a kind exists but has no implementation by that name.

View Source
var ErrUnknownKind = errors.New("dsp: unknown effect kind")

ErrUnknownKind means no effect is registered under the requested kind.

View Source
var ErrUnknownParam = errors.New("dsp: unknown parameter")

ErrUnknownParam means a key is not in an effect's schema. A preset loader leans on this: a mistyped key fails loudly instead of quietly doing nothing.

Functions

func CommonParam

func CommonParam(key string) bool

CommonParam reports whether key is one of the standard parameters every effect carries: bypass, input gain and output gain. A UI renders these as its fixed base controls rather than as effect-specific ones, so an effect cannot present them as optional or hide them.

func CrossfadeGains added in v1.1.0

func CrossfadeGains(t float64) (out, in float64)

CrossfadeGains returns the outgoing and incoming gains at t, where t runs from 0 (all outgoing) to 1 (all incoming). Values outside [0, 1] are clamped, so a caller that overshoots its own ramp ends at a clean endpoint rather than a negative or amplified gain.

The returned pair satisfies out^2 + in^2 == 1 across the ramp, which is what keeps a crossfade between uncorrelated material at a constant perceived level. At t == 0 it is (1, 0) and at t == 1 it is (0, 1).

func EqualizerBandFreqKey added in v1.1.0

func EqualizerBandFreqKey(i int) string

EqualizerBandFreqKey formats the frequency parameter key for a band index.

func EqualizerBandGainKey added in v1.1.0

func EqualizerBandGainKey(i int) string

EqualizerBandGainKey formats the gain parameter key for a band index.

func EqualizerBandQKey added in v1.1.0

func EqualizerBandQKey(i int) string

EqualizerBandQKey formats the Q parameter key for a band index.

func Kernels added in v1.1.0

func Kernels() []string

Kernels lists all registered kernel names in sorted order.

func Register

func Register(f Factory)

Register adds a factory to the process-wide Default registry.

func RegisterKernel added in v1.1.0

func RegisterKernel(name, path string) error

RegisterKernel loads and registers an impulse response file under name.

func StandardParamKeys

func StandardParamKeys() []string

StandardParamKeys lists the standard parameter keys in display order. It is the single source a caller iterates to pin the base controls, so it cannot drift from StandardParams.

Types

type BassEnhancer added in v1.1.0

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

BassEnhancer is a post-ring stage that synthesizes harmonics from the bass band, driven by the missing-fundamental principle.

func (*BassEnhancer) Bypassed added in v1.1.0

func (b *BassEnhancer) Bypassed() bool

func (*BassEnhancer) Configure added in v1.1.0

func (b *BassEnhancer) Configure(in core.FrameFormat) (core.FrameFormat, error)

func (*BassEnhancer) Get added in v1.1.0

func (b *BassEnhancer) Get(key string) (any, error)

func (*BassEnhancer) Meters added in v1.1.0

func (b *BassEnhancer) Meters() map[string]float32

func (*BassEnhancer) Name added in v1.1.0

func (b *BassEnhancer) Name() string

func (*BassEnhancer) Process added in v1.1.0

func (b *BassEnhancer) Process(buf []float32, frames int) error

func (*BassEnhancer) Reset added in v1.1.0

func (b *BassEnhancer) Reset() error

func (*BassEnhancer) Schema added in v1.1.0

func (b *BassEnhancer) Schema() []Param

func (*BassEnhancer) Set added in v1.1.0

func (b *BassEnhancer) Set(key string, value any) error

type BassEnhancerFactory added in v1.1.0

type BassEnhancerFactory struct{}

BassEnhancerFactory registers the harmonic bass enhancer implementation.

func NewBassEnhancerFactory added in v1.1.0

func NewBassEnhancerFactory() *BassEnhancerFactory

NewBassEnhancerFactory returns a factory for the harmonic bass enhancer.

func (*BassEnhancerFactory) FriendlyName added in v1.1.0

func (f *BassEnhancerFactory) FriendlyName() string

func (*BassEnhancerFactory) Impl added in v1.1.0

func (f *BassEnhancerFactory) Impl() string

func (*BassEnhancerFactory) Kind added in v1.1.0

func (f *BassEnhancerFactory) Kind() string

func (*BassEnhancerFactory) New added in v1.1.0

func (f *BassEnhancerFactory) New(values Values) (Effect, error)

func (*BassEnhancerFactory) Placement added in v1.1.0

func (f *BassEnhancerFactory) Placement() Placement

func (*BassEnhancerFactory) Schema added in v1.1.0

func (f *BassEnhancerFactory) Schema() []Param

func (*BassEnhancerFactory) Weight added in v1.1.0

func (f *BassEnhancerFactory) Weight() int

type Bypassable

type Bypassable interface {
	Bypassed() bool
}

Bypassable is implemented by an effect that can be switched off without being rebuilt. The chain consults it so a bypassed effect contributes no latency and can be skipped entirely.

type Chain

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

Chain is an ordered set of effects that processes a buffer in place. It is the stage the session inserts between the streamer and the device.

The audio thread reads the effect list through one atomic pointer, so a control goroutine can rebuild and swap the whole chain without ever making Process wait. A swap is the unit of change: adding, removing or reordering an effect publishes a new list, while changing one effect's parameter goes through that effect's own Set.

func NewChain

func NewChain() *Chain

NewChain returns an empty chain. An empty chain passes audio through.

func (*Chain) Configure

func (c *Chain) Configure(in core.FrameFormat) (core.FrameFormat, error)

Configure negotiates the format through every effect in order and returns what the chain produces. It runs off the audio thread, before the chain is installed.

func (*Chain) Effects

func (c *Chain) Effects() []Effect

Effects returns the current list. It is a snapshot: a later Set does not change it, and it must not be mutated.

func (*Chain) Latency

func (c *Chain) Latency() time.Duration

Latency is the total delay the chain adds. A bypassed effect contributes nothing, which is what keeps the reported play position correct when a lookahead stage is switched off.

func (*Chain) Process

func (c *Chain) Process(buf []float32, frames int) error

Process runs every effect in order on the first frames interleaved samples of buf. It loads the list once, so a swap mid-buffer cannot make it run a mix of the old and new chains. It allocates nothing and takes no lock.

func (*Chain) Reset

func (c *Chain) Reset() error

Reset clears the state of every effect, so a seek or a format change cannot blend pre-jump samples into post-jump output. It runs while the audio thread is parked, the same guarantee the streamer gives its pre-ring modules.

func (*Chain) Set

func (c *Chain) Set(effects []Effect)

Set replaces the chain's effects. It is safe while Process is running: the new list is stored atomically and the audio thread picks it up on its next call. The caller owns configuring and resetting the effects before this.

type Convolver added in v1.1.0

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

Convolver implements uniform-partitioned overlap-add convolution.

func (*Convolver) Bypassed added in v1.1.0

func (c *Convolver) Bypassed() bool

func (*Convolver) Configure added in v1.1.0

func (c *Convolver) Configure(in core.FrameFormat) (core.FrameFormat, error)

func (*Convolver) Get added in v1.1.0

func (c *Convolver) Get(key string) (any, error)

func (*Convolver) Latency added in v1.1.0

func (c *Convolver) Latency() time.Duration

func (*Convolver) Meters added in v1.1.0

func (c *Convolver) Meters() map[string]float32

func (*Convolver) Name added in v1.1.0

func (c *Convolver) Name() string

func (*Convolver) Process added in v1.1.0

func (c *Convolver) Process(buf []float32, frames int) error

func (*Convolver) Reset added in v1.1.0

func (c *Convolver) Reset() error

func (*Convolver) Schema added in v1.1.0

func (c *Convolver) Schema() []Param

func (*Convolver) Set added in v1.1.0

func (c *Convolver) Set(key string, value any) error

type ConvolverFactory added in v1.1.0

type ConvolverFactory struct{}

ConvolverFactory registers the partitioned convolver.

func NewConvolverFactory added in v1.1.0

func NewConvolverFactory() *ConvolverFactory

NewConvolverFactory returns a factory for the convolver effect.

func (*ConvolverFactory) FriendlyName added in v1.1.0

func (f *ConvolverFactory) FriendlyName() string

func (*ConvolverFactory) Impl added in v1.1.0

func (f *ConvolverFactory) Impl() string

func (*ConvolverFactory) Kind added in v1.1.0

func (f *ConvolverFactory) Kind() string

func (*ConvolverFactory) New added in v1.1.0

func (f *ConvolverFactory) New(values Values) (Effect, error)

func (*ConvolverFactory) Placement added in v1.1.0

func (f *ConvolverFactory) Placement() Placement

func (*ConvolverFactory) Schema added in v1.1.0

func (f *ConvolverFactory) Schema() []Param

func (*ConvolverFactory) Weight added in v1.1.0

func (f *ConvolverFactory) Weight() int

type Crossfeed

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

Crossfeed is the effect. Its state is published atomically; its filter state is touched only by the audio thread, so the two never race.

func (*Crossfeed) Bypassed

func (c *Crossfeed) Bypassed() bool

Bypassed reports the standard bypass parameter. It reads the published state rather than the store, so the chain can ask without taking a lock the audio thread might contend on.

func (*Crossfeed) Configure

func (c *Crossfeed) Configure(in core.FrameFormat) (core.FrameFormat, error)

Configure records the format and rebuilds for the new rate. It is the only place the rate changes, so a saved state always belongs to the rate the effect is running at.

func (*Crossfeed) Get

func (c *Crossfeed) Get(key string) (any, error)

func (*Crossfeed) Meters

func (c *Crossfeed) Meters() map[string]float32

Meters reports the last input and output levels in dBFS. It is read from a control goroutine, which is why building the map here is harmless.

func (*Crossfeed) Name

func (c *Crossfeed) Name() string

func (*Crossfeed) Process

func (c *Crossfeed) Process(buf []float32, frames int) error

Process applies the crossfeed in place. It reads the state pointer once and takes no lock, so a concurrent Set cannot make one buffer use two coefficient sets and the audio thread never waits on a control goroutine. The standard gains wrap the effect's own work.

func (*Crossfeed) Reset

func (c *Crossfeed) Reset() error

Reset clears the filter state so a seek cannot carry the previous position's tail into the new one. The published state stays as it is.

func (*Crossfeed) Schema

func (c *Crossfeed) Schema() []Param

func (*Crossfeed) Set

func (c *Crossfeed) Set(key string, value any) error

Set validates the value, stores it, and republishes the state. The design equations are cheap here, so there is no work to move off-thread; a heavier effect would build its state on a worker and swap it the same way.

type CrossfeedFactory

type CrossfeedFactory struct{}

CrossfeedFactory registers this implementation.

func NewCrossfeedFactory

func NewCrossfeedFactory() *CrossfeedFactory

NewCrossfeedFactory returns a factory for the crossfeed effect.

func (*CrossfeedFactory) FriendlyName

func (f *CrossfeedFactory) FriendlyName() string

func (*CrossfeedFactory) Impl

func (f *CrossfeedFactory) Impl() string

Impl names the algorithm this implementation follows.

func (*CrossfeedFactory) Kind

func (f *CrossfeedFactory) Kind() string

func (*CrossfeedFactory) New

func (f *CrossfeedFactory) New(values Values) (Effect, error)

func (*CrossfeedFactory) Placement

func (f *CrossfeedFactory) Placement() Placement

func (*CrossfeedFactory) Schema

func (f *CrossfeedFactory) Schema() []Param

func (*CrossfeedFactory) Weight

func (f *CrossfeedFactory) Weight() int

Weight is the only implementation of this kind, so the value is a formality today. It follows decode's convention: higher wins the automatic choice.

type Described

type Described interface {
	// Readings returns the metadata for every key Meters reports beyond the
	// standard pair. The returned slice is a copy and may be kept.
	Readings() []Reading
}

Described is implemented by an effect that can explain its Meters keys. Metered stays the source of the numbers; this is the rendering contract. An effect that implements only Metered shows the legacy in/out pair, so this is additive.

type Effect

type Effect interface {
	// Name identifies the instance in a chain, for diagnostics.
	Name() string

	// Schema describes every parameter, including the standard bypass. The
	// returned slice is a copy and may be kept.
	Schema() []Param

	// Get returns the current value of key, or an error when it is unknown.
	Get(key string) (any, error)

	// Set validates and applies one parameter. It is safe to call while
	// Process is running: the implementation builds the new state and swaps it
	// in, so the audio thread keeps reading the old one until the swap.
	Set(key string, value any) error

	// Configure negotiates the format and rebuilds internal state for it. It
	// runs before Process, off the audio thread.
	Configure(in core.FrameFormat) (out core.FrameFormat, err error)

	// Process transforms the first frames interleaved samples of buf in
	// place. It must not allocate or block, and it must ignore everything past
	// the declared frame count.
	Process(buf []float32, frames int) error

	// Reset clears state that must not survive a seek or a format change.
	Reset() error
}

Effect is one insertable stage of a pipeline. It is core.Module plus the parameter surface a UI and a preset need, so a chain stays a list of modules while an editor can still reach every knob.

An effect is configured once when it is built and then processes buffers on the audio thread. Set is the only method a control goroutine calls while audio is running, and an implementation must publish the new state atomically rather than mutate what Process reads.

func BuildPost

func BuildPost(p Pipeline) ([]Effect, error)

BuildPost builds the post-ring half of the pipeline: the ordered effects the real-time chain runs. The pre-ring half is the streamer's business, so this deliberately ignores it and a caller that wants both builds them from the same Pipeline in their own two places.

func NewEffects

func NewEffects(specs []Spec) ([]Effect, error)

NewEffects builds every spec in order. A failure names the offending spec so a preset with one bad stage does not look like a total failure.

type Equalizer added in v1.1.0

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

Equalizer cascades peaking biquad filters in series.

func (*Equalizer) Bypassed added in v1.1.0

func (e *Equalizer) Bypassed() bool

func (*Equalizer) Configure added in v1.1.0

func (e *Equalizer) Configure(in core.FrameFormat) (core.FrameFormat, error)

Configure sets format and allocates biquad filters once.

func (*Equalizer) Get added in v1.1.0

func (e *Equalizer) Get(key string) (any, error)

func (*Equalizer) Meters added in v1.1.0

func (e *Equalizer) Meters() map[string]float32

func (*Equalizer) Name added in v1.1.0

func (e *Equalizer) Name() string

func (*Equalizer) Process added in v1.1.0

func (e *Equalizer) Process(buf []float32, frames int) error

Process passes samples through active peaking filters without allocations or locks.

func (*Equalizer) Reset added in v1.1.0

func (e *Equalizer) Reset() error

Reset clears filter delay history across all bands.

func (*Equalizer) Schema added in v1.1.0

func (e *Equalizer) Schema() []Param

func (*Equalizer) Set added in v1.1.0

func (e *Equalizer) Set(key string, value any) error

Set stores one parameter and publishes a new snapshot for the audio thread.

type EqualizerFactory added in v1.1.0

type EqualizerFactory struct{}

EqualizerFactory registers the equalizer effect implementation.

func NewEqualizerFactory added in v1.1.0

func NewEqualizerFactory() *EqualizerFactory

NewEqualizerFactory returns a factory for the equalizer effect.

func (*EqualizerFactory) FriendlyName added in v1.1.0

func (f *EqualizerFactory) FriendlyName() string

func (*EqualizerFactory) Impl added in v1.1.0

func (f *EqualizerFactory) Impl() string

Impl identifies the RBJ cookbook biquad implementation.

func (*EqualizerFactory) Kind added in v1.1.0

func (f *EqualizerFactory) Kind() string

func (*EqualizerFactory) New added in v1.1.0

func (f *EqualizerFactory) New(values Values) (Effect, error)

func (*EqualizerFactory) Placement added in v1.1.0

func (f *EqualizerFactory) Placement() Placement

func (*EqualizerFactory) Schema added in v1.1.0

func (f *EqualizerFactory) Schema() []Param

func (*EqualizerFactory) Weight added in v1.1.0

func (f *EqualizerFactory) Weight() int

type Factory

type Factory interface {
	// Kind is the pipeline slot a preset names, such as "crossfeed". Two
	// implementations of one kind are interchangeable in a preset.
	Kind() string

	// Impl is this realisation of the kind, such as "crossfeed-bs2b". It is
	// the name a caller forces when the automatic pick is not wanted.
	Impl() string

	// FriendlyName is the label a UI shows.
	FriendlyName() string

	// Weight orders the implementations of a kind; higher wins. It is only
	// read for automatic selection, exactly as decode weights are.
	Weight() int

	// Placement says which slot the effect may occupy.
	Placement() Placement

	// Schema describes the parameters. It must be stable for the life of the
	// process, because a UI may cache it.
	Schema() []Param

	// New builds an effect from a parameter set. Missing keys take their
	// defaults; an unknown key is an error.
	New(values Values) (Effect, error)
}

Factory builds one effect implementation. It mirrors decode.Factory: the registry dispatches on Kind and Impl, Weight decides the automatic choice, and Schema lets a UI render the controls before anything is built.

type Fade

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

Fade is the effect. Its published state is atomic; its ramp position is touched only by the audio thread.

func (*Fade) Bypassed

func (f *Fade) Bypassed() bool

Bypassed reports the standard bypass parameter from the published state, so the chain can ask without taking a lock.

func (*Fade) Configure

func (f *Fade) Configure(in core.FrameFormat) (core.FrameFormat, error)

func (*Fade) Get

func (f *Fade) Get(key string) (any, error)

func (*Fade) Meters

func (f *Fade) Meters() map[string]float32

Meters reports the last input and output levels in dBFS. It is read from a control goroutine, which is why building the map here is harmless.

func (*Fade) Name

func (f *Fade) Name() string

func (*Fade) Process

func (f *Fade) Process(buf []float32, frames int) error

Process applies the ramp in place, advancing one step per frame. Once the ramp is done the gain holds at its target (1 for in, 0 for out).

func (*Fade) Reset

func (f *Fade) Reset() error

Reset re-arms the ramp so a seek fades in from silence rather than jumping to wherever the previous position left the gain.

func (*Fade) Schema

func (f *Fade) Schema() []Param

func (*Fade) Set

func (f *Fade) Set(key string, value any) error

type FadeFactory

type FadeFactory struct{}

FadeFactory registers this implementation.

func NewFadeFactory

func NewFadeFactory() *FadeFactory

NewFadeFactory returns a factory for the fade effect.

func (*FadeFactory) FriendlyName

func (f *FadeFactory) FriendlyName() string

func (*FadeFactory) Impl

func (f *FadeFactory) Impl() string

func (*FadeFactory) Kind

func (f *FadeFactory) Kind() string

func (*FadeFactory) New

func (f *FadeFactory) New(values Values) (Effect, error)

func (*FadeFactory) Placement

func (f *FadeFactory) Placement() Placement

func (*FadeFactory) Schema

func (f *FadeFactory) Schema() []Param

func (*FadeFactory) Weight

func (f *FadeFactory) Weight() int

Weight is the only implementation of this kind, so the value is a formality.

type Gain

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

Gain is a post-ring volume stage. It scales interleaved float32 samples in place and never allocates, which keeps it legal on the real-time path.

Gain is the master volume stage. Keep it small: no lock, no channel, no allocation, so the audio thread pays only for the multiply.

func NewGain

func NewGain(v float64) *Gain

NewGain returns a gain stage at v, clamped to [MinVolume, MaxVolume]. The caller may keep a reference and call SetVolume while audio is running.

func (*Gain) Configure

func (g *Gain) Configure(in core.FrameFormat) (core.FrameFormat, error)

Configure accepts any format unchanged: scaling samples cannot alter their layout. It only records the channel count, because Process needs it to know how many samples the declared frame count covers. Like every core.Module, Configure runs at setup time; only SetVolume is meant to be called while Process is live.

func (*Gain) Name

func (g *Gain) Name() string

Name identifies the module in the streamer's error messages.

func (*Gain) Process

func (g *Gain) Process(buf []float32, frames int) error

Process multiplies the first frames*channels samples of buf by the current volume. It is safe to call concurrently with SetVolume; the load is atomic.

func (*Gain) Reset

func (g *Gain) Reset() error

Reset satisfies core.Module. Gain carries no state across buffers, so volume intentionally survives a seek or a track change.

func (*Gain) SetVolume

func (g *Gain) SetVolume(v float64)

SetVolume changes the gain for subsequent Process calls. It is safe to call from a control goroutine while the audio thread is in Process. Out-of-range values, including NaN, clamp into [MinVolume, MaxVolume] instead of being ignored, so a bad caller cannot leave the previous volume silently in force.

func (*Gain) Volume

func (g *Gain) Volume() float64

Volume reports the current value, clamped.

type Kind

type Kind uint8

Kind is the type of a parameter value. The set is small on purpose, because a parameter is something a UI can render as a slider, a switch or a list.

const (
	// Float is a continuous number, clamped to its range.
	Float Kind = iota
	// Int is a whole number, rounded and clamped to its range.
	Int
	// Bool is a two-state value.
	Bool
	// Enum is one of a fixed list of Options; a value outside it is rejected.
	Enum
)

type Latent

type Latent interface {
	Latency() time.Duration
}

Latent is implemented by an effect that delays its output, such as a lookahead limiter or a partitioned convolver. The chain sums the latencies of the effects that report it so the play position can be corrected.

type Limiter added in v1.1.0

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

Limiter is a lookahead brickwall dynamics processor.

func (*Limiter) Bypassed added in v1.1.0

func (l *Limiter) Bypassed() bool

Bypassed reports whether the limiter is currently bypassed.

func (*Limiter) Configure added in v1.1.0

func (l *Limiter) Configure(in core.FrameFormat) (core.FrameFormat, error)

Configure allocates scratch buffers and rebuilds filter state for the new format.

func (*Limiter) Get added in v1.1.0

func (l *Limiter) Get(key string) (any, error)

func (*Limiter) Latency added in v1.1.0

func (l *Limiter) Latency() time.Duration

Latency reports the lookahead delay as a duration.

func (*Limiter) Meters added in v1.1.0

func (l *Limiter) Meters() map[string]float32

Meters reports input and output peak levels and gain reduction in dBFS.

func (*Limiter) Name added in v1.1.0

func (l *Limiter) Name() string

func (*Limiter) Process added in v1.1.0

func (l *Limiter) Process(buf []float32, frames int) error

Process applies the lookahead limiter in place without allocations or locks.

func (*Limiter) Reset added in v1.1.0

func (l *Limiter) Reset() error

Reset clears internal filter state and zeroes meters.

func (*Limiter) Schema added in v1.1.0

func (l *Limiter) Schema() []Param

func (*Limiter) Set added in v1.1.0

func (l *Limiter) Set(key string, value any) error

Set validates and stores a parameter, then republishes the state snapshot.

type LimiterFactory added in v1.1.0

type LimiterFactory struct{}

LimiterFactory registers the lookahead limiter implementation.

func NewLimiterFactory added in v1.1.0

func NewLimiterFactory() *LimiterFactory

NewLimiterFactory returns a factory for the lookahead limiter.

func (*LimiterFactory) FriendlyName added in v1.1.0

func (f *LimiterFactory) FriendlyName() string

func (*LimiterFactory) Impl added in v1.1.0

func (f *LimiterFactory) Impl() string

func (*LimiterFactory) Kind added in v1.1.0

func (f *LimiterFactory) Kind() string

func (*LimiterFactory) New added in v1.1.0

func (f *LimiterFactory) New(values Values) (Effect, error)

func (*LimiterFactory) Placement added in v1.1.0

func (f *LimiterFactory) Placement() Placement

func (*LimiterFactory) Schema added in v1.1.0

func (f *LimiterFactory) Schema() []Param

func (*LimiterFactory) Weight added in v1.1.0

func (f *LimiterFactory) Weight() int

type Maximizer added in v1.1.0

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

Maximizer provides lookahead peak limiting with release smoothing and a hard ceiling clamp.

func (*Maximizer) Bypassed added in v1.1.0

func (m *Maximizer) Bypassed() bool

func (*Maximizer) Configure added in v1.1.0

func (m *Maximizer) Configure(in core.FrameFormat) (core.FrameFormat, error)

func (*Maximizer) Get added in v1.1.0

func (m *Maximizer) Get(key string) (any, error)

func (*Maximizer) Latency added in v1.1.0

func (m *Maximizer) Latency() time.Duration

func (*Maximizer) Meters added in v1.1.0

func (m *Maximizer) Meters() map[string]float32

func (*Maximizer) Name added in v1.1.0

func (m *Maximizer) Name() string

func (*Maximizer) Process added in v1.1.0

func (m *Maximizer) Process(buf []float32, frames int) error

func (*Maximizer) Reset added in v1.1.0

func (m *Maximizer) Reset() error

func (*Maximizer) Schema added in v1.1.0

func (m *Maximizer) Schema() []Param

func (*Maximizer) Set added in v1.1.0

func (m *Maximizer) Set(key string, value any) error

type MaximizerFactory added in v1.1.0

type MaximizerFactory struct{}

MaximizerFactory creates instances of the lookahead peak maximizer.

func NewMaximizerFactory added in v1.1.0

func NewMaximizerFactory() *MaximizerFactory

NewMaximizerFactory returns a factory for the lookahead peak maximizer.

func (*MaximizerFactory) FriendlyName added in v1.1.0

func (f *MaximizerFactory) FriendlyName() string

func (*MaximizerFactory) Impl added in v1.1.0

func (f *MaximizerFactory) Impl() string

func (*MaximizerFactory) Kind added in v1.1.0

func (f *MaximizerFactory) Kind() string

func (*MaximizerFactory) New added in v1.1.0

func (f *MaximizerFactory) New(values Values) (Effect, error)

func (*MaximizerFactory) Placement added in v1.1.0

func (f *MaximizerFactory) Placement() Placement

func (*MaximizerFactory) Schema added in v1.1.0

func (f *MaximizerFactory) Schema() []Param

func (*MaximizerFactory) Weight added in v1.1.0

func (f *MaximizerFactory) Weight() int

type Meter

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

Meter is a level accumulator for an effect's input or output. It is written by the audio thread in Push and read by a control goroutine in Read, so every field it shares is atomic and Push takes no lock and allocates nothing.

Policy. A reading has two parts, peak and RMS, both linear amplitude where 1 is full scale:

  • Peak is a block peak-hold with an exponential release. Each Push raises the held peak to that block's maximum if it is higher, otherwise decays it by the per-push release factor. A hold alone would ratchet up and never come down; an instant drop would flicker on every silent block. The release factor is exp(-1/meterReleasePushes), so the peak falls by about 20 dB over meterReleasePushes pushes.
  • RMS is a running mean of squared samples with the same one-pole shape, so it settles instead of jumping between blocks. Read squares it back to amplitude.

Both time constants are in pushes rather than seconds because Push is called once per audio block, and the block size is the caller's to choose. The defaults suit the post-ring path, where a block is a few milliseconds.

Stereo. For a block of ch channels, Peak is the largest absolute sample across all channels, so one loud channel is not hidden by a quiet one. RMS is the mean power across every sample in the block, so it is the same regardless of how the energy splits between channels.

func NewMeter

func NewMeter() *Meter

NewMeter returns a meter ready to push. It is a convenience only: the zero Meter works, since the shaping is constant and the atomics start at zero.

func (*Meter) Peak

func (m *Meter) Peak() float32

Peak returns the held peak without taking a lock.

func (*Meter) Push

func (m *Meter) Push(buf []float32, frames, ch int)

Push folds one block of frames interleaved samples into the accumulator. It only reads buf, takes no lock and allocates nothing, so it is legal on the real-time path and cannot alter the samples it measures.

ch may be 1 or 2, matching the engine's frame widths. What a stereo block reports is settled in the type comment: Peak is the max across channels, RMS the mean power across all samples.

A block with a non-finite sample is treated as silence rather than folded in. One NaN or Inf would otherwise poison the stored mean or peak for the rest of the session, because the update multiplies the previous value: NaN stays NaN and +Inf stays +Inf. Recovering to silence matches the engine's other guards and keeps MeterReading finite, which callers rely on.

Push has a single writer: the goroutine that runs Process. The atomics make the individual load and store race-free so a control-side Read is safe, but they do not make two concurrent Pushers correct: the read-modify-write on peak would lose the higher value. Only one goroutine may call Push.

func (*Meter) Read

func (m *Meter) Read() MeterReading

Read snapshots the current reading. It is safe from any goroutine and pairs with Push's atomics, so a control reader never blocks the audio thread.

func (*Meter) Reset

func (m *Meter) Reset()

Reset clears the accumulator so a seek or a format change starts from silence. It is safe to call while Process is running: a reader may see one more stale block, which is harmless for a display.

type MeterReading

type MeterReading struct {
	Peak float32
	RMS  float32
}

MeterReading is one snapshot of a meter, both parts linear amplitude where 1 is full scale and anything above 1 is clipping.

func (MeterReading) DB

func (r MeterReading) DB() (peakDB, rmsDB float32)

DB converts a reading to dBFS. Silence reads the floor rather than -Inf, and a non-finite or negative amplitude is treated as silence, so a UI can do arithmetic on the result without a special case.

type Metered

type Metered interface {
	Meters() map[string]float32
}

Metered is implemented by an effect that exposes live readings, such as a gain-reduction figure. It is read from a control goroutine, never the audio thread.

type Param

type Param struct {
	Key     string
	Kind    Kind
	Min     float64
	Max     float64
	Step    float64
	Unit    string
	Options []string
	Default any

	// Label is the human name a UI shows. Empty means the UI derives one from
	// Key.
	Label string
	// Group is the section a UI files the control under. Empty means the
	// effect's own unnamed section.
	Group string
	// Widget is the control to draw. WidgetAuto means pick from Kind.
	Widget Widget
}

Param describes one editable setting.

Min and Max bound Float and Int; an out-of-range number is clamped rather than rejected, which is how a bounded control behaves. An Enum is rejected when the value is not one of Options, because there is no nearest neighbour to clamp to. Step, Unit and Options the rest of the way are display metadata.

Label, Group and Widget are the UI layer. A UI groups parameters by Group in the order they first appear, shows Label instead of the raw Key, and picks a control from Widget. All three are optional: an effect that sets none of them still renders, because the UI falls back to the Key and the Kind.

func StandardParams

func StandardParams() []Param

StandardParams returns the three parameters every effect carries, in the order a UI shows them: bypass, input gain, output gain. It is exported because an effect built outside this package, such as a scripted one, has to prepend the same three and must not invent its own copy of them.

type Pipeline

type Pipeline struct {
	Pre  []Spec
	Post []Spec
}

Pipeline is an ordered set of stages split by placement. It is data, not code: a caller composes any chain by filling the slices, and a preset file is one serialisation of it.

The Post half belongs to the real-time chain this package builds; the Pre half belongs to the streamer's producer, which is why it lives here as the shared description rather than inside either one.

func LoadEasyEffectsPreset added in v1.1.0

func LoadEasyEffectsPreset(data []byte) (Pipeline, []string, error)

LoadEasyEffectsPreset parses an EasyEffects preset JSON document into a Pipeline. It maps the output chain into post-processing stages and collects unmapped settings as warnings.

func LoadEasyEffectsPresetFile added in v1.1.0

func LoadEasyEffectsPresetFile(path string) (Pipeline, []string, error)

LoadEasyEffectsPresetFile reads an EasyEffects preset from a file on disk.

type Placement

type Placement uint8

Placement says where an effect may run. A pipeline stage is either pre-ring (in the streamer's producer, where allocation is allowed) or post-ring (the device's real-time path, where it is not), and an effect can be built for either.

const (
	// Post is the real-time path and the default: gain, EQ, crossfeed, and
	// every stage that has to hear the canonical 48 kHz stereo buffer.
	Post Placement = iota
	// Pre runs in the producer before the ring, for a stage that wants the
	// stream as decoded.
	Pre
	// Any runs in either slot.
	Any
)

type Reading

type Reading struct {
	Key   string      `json:"key"`
	Label string      `json:"label"`
	Unit  string      `json:"unit"`
	Min   float64     `json:"min"`
	Max   float64     `json:"max"`
	Kind  ReadingKind `json:"kind"`
}

Reading describes one key that Meters reports, so a UI can draw it without knowing which effect it is looking at. Key must match a Meters key: the number is still the effect's to publish, this only says how to render it.

type ReadingKind

type ReadingKind string

ReadingKind is how a reading should be drawn. It is a string type for the same reason Widget is: the value crosses the JSON bridge, and an iota order is not a contract.

const (
	// ReadingLevel is a level in dBFS, filled from the floor up.
	ReadingLevel ReadingKind = "level"
	// ReadingGainReduction is a reduction in dB, 0 at the top, filled down.
	ReadingGainReduction ReadingKind = "gain-reduction"
	// ReadingScalar is a plain value with a unit.
	ReadingScalar ReadingKind = "scalar"
)

type Registry

type Registry interface {
	Register(f Factory)

	// Kinds lists the registered effect kinds, sorted.
	Kinds() []string

	// Schema returns the parameter set of the implementation that an empty
	// impl would select, so a UI can render before building.
	Schema(kind string) ([]Param, error)

	// SchemaFor returns the parameter schema of one (kind, impl) pair. An
	// empty impl means the highest-weight implementation, identical to Schema.
	SchemaFor(kind, impl string) ([]Param, error)

	// Impls lists every registered factory in registration order, so a chooser
	// can offer each (kind, impl) pair. It is the effect-side analogue of
	// decode's Codecs.
	Impls() []Factory

	// Winner reports the implementation automatic selection would use.
	Winner(kind string) (Factory, error)

	// New builds the chosen implementation. An empty impl selects by weight.
	New(kind, impl string, values Values) (Effect, error)
}

Registry dispatches (kind, impl) pairs to the factories registered at init time. An empty impl means the highest-weight factory for that kind.

func NewRegistry

func NewRegistry() Registry

NewRegistry returns an empty registry. Implementations register into the package-level Default instead; this exists for tests that want an isolated set.

type Spec

type Spec struct {
	// ID names the instance, so two effects of one kind can coexist.
	ID string

	// Kind is required and names the slot, such as "crossfeed".
	Kind string

	// Impl is optional; empty selects the highest-weight implementation.
	Impl string

	// Params are the effect's settings. Validation happens at build time.
	Params Values
}

Spec is one stage of a pipeline: which kind, which implementation, and the parameter set. It is the value a preset serialises.

type Values

type Values map[string]any

Values is a parameter set at the API edge. It is the shape a preset and a UI work with; an effect compiles it into the typed state its audio path reads.

type Visual

type Visual struct {
	Kind     VisualKind `json:"kind"`
	Params   []string   `json:"params"`
	Overlays []string   `json:"overlays"`
	XMin     float64    `json:"xMin"`
	XMax     float64    `json:"xMax"`
	YMin     float64    `json:"yMin"`
	YMax     float64    `json:"yMax"`
}

Visual declares a plot. Params are schema keys the curve is derived from, which is what keeps a static curve off the meter path: the UI recomputes it from the Values it already has. Overlays are reading keys drawn live, such as the current input dot and the gain-reduction bar; for VisualDynamics they are the series the scrolling display plots.

type VisualKind

type VisualKind string

VisualKind names a plot the UI knows how to draw. The effect names the kind and the params; the UI owns the renderer, so a script author never writes frontend.

const (
	// VisualTransfer is a compressor, gate or limiter curve: an input level
	// mapped to an output level.
	VisualTransfer VisualKind = "transfer"
	// VisualGainReduction is a reduction-over-time display.
	VisualGainReduction VisualKind = "gain-reduction"
	// VisualDynamics is a scrolling level display: the overlays are reading
	// keys plotted over time, newest at the right edge, on the yMin..yMax scale.
	VisualDynamics VisualKind = "dynamics"
)

type Visualized

type Visualized interface {
	// Visuals returns every plot this effect wants drawn, in display order.
	// The returned slice and the inner Params and Overlays slices are copies
	// and may be kept.
	Visuals() []Visual
}

Visualized is implemented by an effect that wants one or more plots. Like Described it is optional and additive.

type Widget

type Widget string

Widget names the control a UI should draw for a parameter. It is a display hint only: the value's Kind is what decides how it is validated and stored, so a UI that ignores Widget entirely still renders every parameter.

Auto is the zero value and means "pick from Kind", which is what an effect that has no opinion should use.

const (
	// WidgetAuto lets the UI choose a control from the parameter's Kind.
	WidgetAuto Widget = ""
	// WidgetSlider is a horizontal range, the default for Float and Int.
	WidgetSlider Widget = "slider"
	// WidgetKnob is a rotary control, for a parameter a UI wants to group
	// tightly, such as one EQ band.
	WidgetKnob Widget = "knob"
	// WidgetSwitch is a two-state control for Bool.
	WidgetSwitch Widget = "switch"
	// WidgetSelect is a dropdown or segmented control for Enum.
	WidgetSelect Widget = "select"
)

Jump to

Keyboard shortcuts

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