Aner Signal
Inspect complex spectra, stream reproducible STFT features, build explicit log Mel and MFCC recipes and retain filter state across blocks.
ImplementedAner 0.1.0 or neweraner.signal supplies bounded native CPU analysis over audio and CPU tensors: FFT/IFFT, streaming STFT, explicit log-Mel/MFCC recipes, stateful filters and detached model inputs. It is the 0.0.9-dev.2 analysis foundation. These operations do not require another language runtime, a GPU or a speech model. Audio transport, decoding and sample rate conversion belong to aner.audio; recognition belongs to speech.
The complete source API lists the callable signatures. Runnable, device free examples cover FFT and plots, streaming state and neural/classical model interoperability. Run exporting examples in a fresh writable working directory; Chart saves create new files exclusively.
FFT and physical units
import aner.audio
import aner.signal
let clip = audio.tone(seconds: 0.125, rate: 8192, frequency: 512.0, amplitude: 0.5)
let spectrum = signal.fft(clip, window: "rectangular")
print(signal.frequency(spectrum, 64)) // 512 Hz
print(signal.magnitude(spectrum, 64)) // 0.5 coherent amplitude
print(signal.power(spectrum, 64)) // 0.125 mean-square powerFFT lengths are powers of two in 2..65536. The default n_fft: 0 uses the input frame count, which must already satisfy that rule. An explicit larger length zero pads after windowing the true input. A smaller length is rejected; input is never silently truncated. fft_tensor accepts rank one mono or rank two [sample_frames, channels] CPU Float32/Float64 tensors. Audio samples are interleaved Float32, not encoded bytes.
Windows are rectangular, hann, hamming or blackman, periodic over the window length, rather than symmetric endpoint windows. Forward DFT coefficients are unnormalized; the inverse divides by N. ifft returns an owned detached CPU Float32 [N, channels] tensor containing the windowed waveform and any zero tail. It does not divide by the window, perform overlap add or reconstruct a complete STFT stream. real and imag expose raw DFT components; phase uses radians.
For X[k] = DFT(w*x), W1 = sum(w), W2 = sum(w*w), rate r and FFT length N, the one sided values are:
| Accessor | Value | Units |
|---|---|---|
magnitude | d * abs(X[k]) / W1 | Coherent digital amplitude |
power | d * abs(X[k])² / (N * W2) | Mean square digital amplitude per bin |
psd | d * abs(X[k])² / (r * W2) | Mean square digital amplitude per Hz |
Here d=1 at DC and Nyquist, and d=2 at other positive frequency bins. The bin spacing is r/N Hz, so sum(psd) * r/N == sum(power). This equals sum((w*x)²)/W2; a rectangular window recovers ordinary sample mean square power. Coherent amplitude describes a bin centered sinusoid; spectral leakage and window bandwidth still matter. Digital amplitude is not calibrated sound pressure, voltage or dB SPL.
Causal streaming STFT
let plan = signal.stft_plan(rate: 16000, n_fft: 512, hop: 128,
window: "hann", scaling: "power", pad_end: true)
let stream = signal.processor(plan, max_frames: 32)
let output = signal.spectrogram_slot()
// For each contiguous AudioClip or AudioBlock:
// signal.push_into(stream, block, output)
// Consume signal.frames(output) results before the next push.
// At a real EOF: signal.flush_into(stream, output)The immutable plan fixes rate, FFT/window length, hop, periodic window, scaling and EOF policy. Scaling is power, psd or magnitude using the formulas above. Window length equals n_fft; 1 <= hop <= n_fft. Analysis is causal and uncentered: the first window starts at the first source sample with no leading padding. A push emits full windows only, retaining their overlap for the next block. Arbitrary contiguous chunk boundaries give the same values as one shot spectrogram.
Call flush_into at actual EOF. With pad_end: true, it emits every remaining hop start strictly before the end of the input, padding each window's unavailable tail with zero. For L>0 input samples, total output is ceil(L/hop). With padding disabled, total output is zero for L<n_fft, otherwise 1+floor((L-n_fft)/hop). A second flush emits zero frames. Pushing after flush requires reset.
time(output, frame) is the analysis window's center (absolute_first_sample + n_fft/2)/rate in seconds on the source sample index clock. It is not PTS, wall time, capture receipt time or the moment a result becomes available. Padded final centers can lie after the last genuine sample. valid_samples reports the genuine input support, and the full window's normalization remains unchanged at EOF. frequency is in Hz; bin zero is DC.
For an audio value with an explicit PTS anchor, audio.timeline(block, signal.time(output, 0)) maps the sample clock center onto that value's PTS clock: pts_ns/1e9 + center - first_sample/rate. It requires a known PTS. Use that conversion when aligning analysis with video from the same media timeline; matching raw sample indices, arrival times or unrelated device clocks does not establish synchronization.
A new source/session, channel count, gap flag or noncontiguous sample index requires an explicit reset. The rate must match the plan. Missing samples are never inferred as silence. Coordinate source/clock changes with upstream resampling and capture policies. Sample rate conversion is explicit through audio.resample or a persistent audio.resampler; filtering alone is not an antialiased rate converter.
Log Mel and MFCC recipes
let mel = signal.mel_plan(rate: 16000, n_fft: 512, bands: 40,
min_hz: 20.0, max_hz: 7600.0, scale: "htk", normalization: "none",
floor: 1e-10, log_base: "natural")
let logs = signal.spectrogram_slot()
let cepstra = signal.spectrogram_slot()
// powers must come from scaling: "power" at the same rate and n_fft.
// signal.log_mel_into(mel, powers, logs)
// signal.mfcc_into(logs, cepstra, coefficients: 13)Mel bands are triangles sampled at the FFT's physical bin frequencies. scale: "htk" uses 2595*log10(1+Hz/700). "slaney" uses the piecewise linear/logarithmic recipe with the 1 kHz transition. normalization: "none" preserves triangle peaks at one; "slaney" multiplies each triangle by 2/(upper_hz-lower_hz). Those two choices are independent. max_hz: 0.0 means Nyquist. Frequency bounds must lie in [0, Nyquist]; inadequate FFT resolution that leaves an empty band is rejected.
log_mel_into requires a matching power scaled STFT. Each band is a weighted sum of those bins, floored to finite positive floor, then logged. Log bases are natural, log10 or db (10*log10, reference power one). There is no implicit pre emphasis, per frame maximum subtraction, relative dB clipping, channel mixing, CMVN or training normalization. A model's feature recipe must be matched explicitly; this general transform does not claim compatibility with every ASR checkpoint.
mfcc_into applies orthonormal DCT II to the already logged Mel bands, includes coefficient zero and accepts 1..bands coefficients. It adds no lifter and does not replace C0 with energy. MFCC bins are coefficient indices, so frequency rejects them instead of reporting misleading Hz. The plot adapter labels their axis accordingly.
Native model inputs
signal.tensor(output, layout: "cnn") creates a detached CPU Float32 [1, C, F, T] copy. layout: "sequence" creates [1, T, C*F], with channels concatenated in increasing channel order and frequency/coefficient index increasing within each channel. These are explicit copies; a retained tensor survives slot replacement. A model must accept that shape and feature recipe. Use documented tensor/model placement for GPU inference; analysis has no hidden GPU path or zero copy transfer promise.
signal.features(clip) returns rank two [1, C*5] CPU Float32 features in channel order: mean, RMS, absolute peak, population standard deviation, zero crossing rate. Crossing rate divides sign changes by frames-1, with zero treated as nonnegative; a one sample clip returns zero crossing rate. These descriptive features are suitable for an explicit classical baseline, not a learned speech representation. Cast explicitly when a model's dtype contract requires it.
The learning example sends log Mel tensors to a small randomly initialized native CNN and fits/queries one synthetic KNN fixture. These checks demonstrate integration only. Assess useful accuracy using held out recordings and speaker/session-aware splits, a fixed feature recipe and appropriate metrics; adjacent windows from one recording can otherwise leak across partitions.
Persistent filters
signal.filter creates a lowpass, highpass, bandpass, notch or DC blocking filter. The first four use normalized real RBJ biquad coefficients with frequency in Hz and q in (0,1000]. Bandpass has unity center gain. DC blocking uses y[n]=x[n]-x[n-1]+exp(-2*pi*frequency/rate)*y[n-1]; Q is validated but does not change that first order filter. Frequency must be strictly between zero and Nyquist.
signal.biquad accepts normalized [b0,b1,b2,a1,a2] coefficients, requiring finite coefficients and denominator poles strictly inside the unit circle. Execution uses transposed direct form II with independent double precision history per channel and Float32 output. coefficient(index) exposes those five coefficients; history(channel,index) exposes its two delay values. process_into(filter, block, output) preserves state across contiguous blocks and does not clip or automatically adjust gain. Output beyond finite Float32 is rejected. Stateful aliases share their updates; reset history explicitly when continuity changes.
Plots and bounded ownership
audio.waveform, signal.spectrum_plot and signal.spectrogram_plot produce ordinary immutable Chart values: style, display and save them through aner.plot. No massive sample List is constructed. Exports retain source/sample identifiers and analysis provenance with the chart snapshot.
Waveform and spectrum previews accept max_points: 4..10000. They retain both extrema of each bucket in source order, plus endpoints, rather than skipping every kth sample and potentially losing a transient. Waveform x is absolute sample index seconds and y is digital amplitude. Spectrum x is Hz and its y caption states coherent amplitude, bin power or PSD. A preview is not an integration grid: integrate the original spectral bins for power.
Spectrogram previews accept max_cells: 1..10000, at most 1000 cells per axis. Their numeric x edges lie halfway between window centers, with a half hop outer extent; frequency edges use center midpoints clipped to zero/Nyquist. Mel bands retain their physical center spacing; MFCC uses coefficient indices. When reducing resolution, each tile takes the maximum of its original values, preserving peaks while changing means and power integrals. The caption and retained provenance disclose that rule and the original STFT/Mel/MFCC recipe. These static numeric plots support SVG and offline HTML; they do not promise audio playback or a live scrolling UI.
Native work is bounded: 32 channels, 8,388,608 sample/feature cells per operation, FFT length at most 65,536, and processor max_frames in 1..65536. Mel plans allow 1..1024 bands with at most 8,388,608 filter weights. Those are admission limits, not a total process memory quota: input storage, double precision FFT scratch, transactional work copies, retained tensors and chart snapshots also occupy memory. Choose small capture blocks and a suitable output frame limit; a result that exceeds its frame/cell budget fails rather than truncating.
Plans and FFT results are immutable; processors, filters and spectrogram slots are native mutable handles. Copies alias state. Reusing a slot bounds its current retained result; it does not promise allocation free execution or make concurrent writes safe. Serialize access to each mutable handle. Long running analysis should consume/reuse native slots and request tensors or charts only when needed. Retaining a new Tensor/Chart/Clip on every block intentionally retains storage, and managed wrapper lifetimes can extend to a cell boundary. The streaming example creates no per block tensor, frozen clip or plot.
See the complete callable index for the native module and method name catalogue.