dsp

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 9 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 analyzes, mixes, and resamples PCM. Use NewFFT for stereo amplitude spectra, NewDecimator to reduce the sample rate of stereo PCM, and NewPlanarResampler to change the rate of channel planes.

Index

Examples

Constants

View Source
const TrackerClickDecay = 4095.0 / 4096

TrackerClickDecay approximates the WAV driver's integer click-removal decay.

Variables

This section is empty.

Functions

func NormalizeComplexSamples added in v1.0.0

func NormalizeComplexSamples[T sample](dst []complex128, src []T) []complex128

NormalizeComplexSamples writes normalized samples to the real part of dst. A nil destination allocates storage. Otherwise it must fit all samples.

func NormalizeSamples added in v1.0.0

func NormalizeSamples[T sample](dst []float64, s []T) []float64

NormalizeSamples converts src to normalized float64 samples in dst.

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

func SQNR

func SQNR(bits int) float64

SQNR is the signal-to-quantization-noise ratio.

Types

type DecimationProfile added in v1.0.0

type DecimationProfile struct {
	InputHz    int
	OutputHz   int
	PassbandHz int
}

DecimationProfile selects the input and output sample rate and the band that must survive filtering. Equal rates leave PCM unmodified. For unequal rates the stopband begins at the output Nyquist frequency.

type Decimator added in v1.0.0

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

Decimator applies an anti-alias filter before reducing the stereo sample rate, keeping filter history and phase across Process calls. Use one Decimator per stream.

func NewDecimator added in v1.0.0

func NewDecimator(profile DecimationProfile) (*Decimator, error)

NewDecimator prepares a unity-gain polyphase Blackman-windowed sinc filter. The output rate cannot exceed the input rate and its Nyquist must be above the requested passband. Filter storage is limited to 65,536 coefficient pairs.

Example
package main

import (
	"fmt"

	"github.com/BeatGlow/audio/dsp"
)

func main() {
	decimator, err := dsp.NewDecimator(dsp.DecimationProfile{
		InputHz:    48000,
		OutputHz:   24000,
		PassbandHz: 6000,
	})
	if err != nil {
		panic(err)
	}
	// Keep the decimator and reuse output storage for subsequent PCM blocks.
	pcm := make([]dsp.Stereo, 8)
	output := make([]dsp.Stereo, len(pcm))
	n := decimator.Process(output, pcm)
	fmt.Printf("%d frames at %d Hz\n", n, decimator.OutputHz())

}
Output:
4 frames at 24000 Hz

func (*Decimator) OutputHz added in v1.0.0

func (d *Decimator) OutputHz() int

OutputHz returns the sample rate produced by Process.

func (*Decimator) Process added in v1.0.0

func (d *Decimator) Process(dst, src []Stereo) int

Process consumes src and returns the number of frames written to dst. A destination as long as src is sufficient. Exact in-place operation is supported. Call Reset before passing PCM from a discontinuous stream.

func (*Decimator) Reset added in v1.0.0

func (d *Decimator) Reset()

Reset discards the filter history and phase, for example after a capture gap.

func (*Decimator) SeekFrame added in v1.0.0

func (d *Decimator) SeekFrame(frame int64, seekInput func(int64) error) error

SeekFrame positions the filter for an output frame. seekInput positions the source at the first input frame required to rebuild the filter history.

type FFT added in v1.0.0

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

FFT computes a one-sided amplitude spectrum for each channel of stereo PCM. It owns reusable work buffers. Use one FFT per concurrent caller. Float32 keeps buffer traffic and SIMD lane width small while preserving amplitude precision well below the visualizers' -60 dB display floor.

func NewFFT added in v1.0.0

func NewFFT(size int, window Window) (*FFT, error)

NewFFT prepares a transform of size samples. Size must be a power of two from 4 through 65536.

Example
package main

import (
	"fmt"

	"github.com/BeatGlow/audio/dsp"
)

func main() {
	fft, err := dsp.NewFFT(4, dsp.Rectangular)
	if err != nil {
		panic(err)
	}
	// One full-scale cycle in the left channel and silence on the right.
	pcm := []dsp.Stereo{
		{1, 0},
		{0, 0},
		{-1, 0},
		{0, 0},
	}
	var left, right [3]float32
	fft.Spectrum(left[:], right[:], pcm)
	fmt.Printf("First harmonic: left %.1f, right %.1f\n", left[1], right[1])

}
Output:
First harmonic: left 1.0, right 0.0

func NewZeroPaddedFFT added in v1.0.0

func NewZeroPaddedFFT(inputSize, transformSize int, window Window) (*FFT, error)

NewZeroPaddedFFT prepares a transform that zero-pads inputSize samples to transformSize before applying the transform. The transform size must be a power of two, and inputSize must be between 4 and transformSize. The selected window covers only the input samples; magnitudes are normalized by its sum.

func (*FFT) Spectrum added in v1.0.0

func (f *FFT) Spectrum(dstL, dstR []float32, src []Stereo)

Spectrum writes linear amplitude magnitudes, from DC through transform Nyquist, into dstL and dstR. A full-scale sine centered on an input-window frequency bin has amplitude 1. Zero-padded transforms sample the windowed spectrum more densely without changing its true resolution. The input must contain exactly the configured input size in frames and each distinct destination must have at least transformSize/2+1 bins. Spectrum allocates no buffers.

type FrequencyPower

type FrequencyPower struct {
	Frequency int
	Magnitude float64
}

FrequencyPower denotes a single frequency and its magnitude in a Fast Fourier Transform of a signal.

type FrequencyPowerCalculator

type FrequencyPowerCalculator[T sample] struct {
	SampleRate int // Samples per second.

	Window window.Window // Optional window function.
	// contains filtered or unexported fields
}

FrequencyPowerCalculator computes spectra from mono PCM and reuses its work buffers. Use one calculator per concurrent caller.

func NewFrequencyPowerCalculator

func NewFrequencyPowerCalculator[T sample](sampleRate int, window window.Window) *FrequencyPowerCalculator[T]

NewFrequencyPowerCalculator creates a mono spectrum calculator. Set sampleRate to the input rate in Hz. Pass nil to skip windowing.

func (*FrequencyPowerCalculator[T]) Apply

func (c *FrequencyPowerCalculator[T]) Apply(dst []FrequencyPower, samples []T) []FrequencyPower

Apply returns the positive-frequency bins between DC and Nyquist, in order. Magnitudes are unscaled FFT magnitudes of the normalized, optionally windowed samples. Apply leaves samples unchanged.

The input length must be a power of two of at least four. A non-nil Window must have at least one weight per sample. Invalid input returns dst[:0] without writing to dst.

Apply appends len(samples)/2-1 bins to dst[:0]. It reuses dst when its capacity is sufficient and allocates otherwise. The returned slice contains exactly the bins written. Any unused destination elements are untouched.

type MixBuffer added in v1.0.0

type MixBuffer[T sample] struct {
	// contains filtered or unexported fields
}

MixBuffer holds one reusable mix block in the negotiated encoding.

func NewMixBuffer added in v1.0.0

func NewMixBuffer[T sample](channels, frames, sampleBits int) MixBuffer[T]

NewMixBuffer allocates accumulation space for one planar PCM block. The caller supplies positive dimensions and a valid sample depth for T.

func (*MixBuffer[T]) Add added in v1.0.0

func (s *MixBuffer[T]) Add(src [][]T, frames int)

Add sums the first frames of an input block. The block must fit the mix.

func (*MixBuffer[T]) AddNormalized added in v1.0.0

func (s *MixBuffer[T]) AddNormalized(channel, frame int, value float64)

AddNormalized adds a linear PCM sample to the mix before clipping.

func (*MixBuffer[T]) Render added in v1.0.0

func (s *MixBuffer[T]) Render(dst [][]T, frames int)

Render clips the accumulated block into dst, which must fit the mix.

func (*MixBuffer[T]) Reset added in v1.0.0

func (s *MixBuffer[T]) Reset()

Reset starts a silent block.

func (*MixBuffer[T]) Scale added in v1.0.0

func (s *MixBuffer[T]) Scale(gain float64, frames int)

Scale attenuates the first frames of each accumulated plane before clipping. The caller provides a gain between zero and one.

func (*MixBuffer[T]) Wrap added in v1.0.0

func (s *MixBuffer[T]) Wrap(limit, frames int)

Wrap folds the first frames of each accumulated plane into [-limit, limit) in normalized PCM units. The caller supplies a positive power of two.

type PlanarResampler added in v1.0.0

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

PlanarResampler converts the sample rate of independent float64 channels with a causal Blackman-windowed sinc filter. It starts with silent history and delays the signal by half the filter length in input frames.

func NewPlanarResampler added in v1.0.0

func NewPlanarResampler(inputHz, outputHz, passbandHz, channels int) (*PlanarResampler, error)

NewPlanarResampler designs a unity-gain filter with a stopband at the lower Nyquist frequency. The input and output rates must be positive and unequal. The filter has at most 32,766 coefficients per phase.

func (*PlanarResampler) Process added in v1.0.0

func (r *PlanarResampler) Process(dst, src [][]float64) (written, consumed int, err error)

Process copies as many resampled frames as fit in dst and reports the number of output and input frames used. Pass back any unconsumed input on the next call. A nil src can drain pending outputs from the last input frame without adding silence or extending the stream. All supplied planes on each side must have the same length and must not overlap.

func (*PlanarResampler) SeekFrame added in v1.0.0

func (r *PlanarResampler) SeekFrame(frame int64, seekInput func(int64) error) error

SeekFrame positions the filter for an output frame. seekInput positions the source at the first input frame required to rebuild the filter history.

type Stereo added in v1.0.0

type Stereo [2]float32

Stereo holds one normalized floating-point PCM frame in left, right order.

func RMSPower added in v1.0.0

func RMSPower(samples []Stereo) (sum Stereo)

RMSPower returns the per-channel sum of squared samples.

type Window added in v1.0.0

type Window uint8

Window selects the weighting applied before a spectrum transform.

const (
	Hann        Window = iota // Periodic Hann weighting.
	Rectangular               // Uniform weighting.
	Hamming                   // Periodic Hamming weighting.
)

Directories

Path Synopsis
Package filter designs and applies finite impulse response filters.
Package filter designs and applies finite impulse response filters.
Package fourier computes forward and inverse discrete Fourier transforms over complex samples.
Package fourier computes forward and inverse discrete Fourier transforms over complex samples.
Package window generates weights for time-domain samples.
Package window generates weights for time-domain samples.

Jump to

Keyboard shortcuts

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