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 ¶
- Constants
- func NormalizeComplexSamples[T sample](dst []complex128, src []T) []complex128
- func NormalizeSamples[T sample](dst []float64, s []T) []float64
- func SQNR(bits int) float64
- type DecimationProfile
- type Decimator
- type FFT
- type FrequencyPower
- type FrequencyPowerCalculator
- type MixBuffer
- func (s *MixBuffer[T]) Add(src [][]T, frames int)
- func (s *MixBuffer[T]) AddNormalized(channel, frame int, value float64)
- func (s *MixBuffer[T]) Render(dst [][]T, frames int)
- func (s *MixBuffer[T]) Reset()
- func (s *MixBuffer[T]) Scale(gain float64, frames int)
- func (s *MixBuffer[T]) Wrap(limit, frames int)
- type PlanarResampler
- type Stereo
- type Window
Examples ¶
Constants ¶
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
NormalizeSamples converts src to normalized float64 samples in dst.
The provided buffer dst should be nil, or adequately sized to fit all samples.
Types ¶
type DecimationProfile ¶ added in v1.0.0
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) Process ¶ added in v1.0.0
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.
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
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
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
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 ¶
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
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
Add sums the first frames of an input block. The block must fit the mix.
func (*MixBuffer[T]) AddNormalized ¶ added in v1.0.0
AddNormalized adds a linear PCM sample to the mix before clipping.
func (*MixBuffer[T]) Render ¶ added in v1.0.0
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.
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.
Source Files
¶
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. |