1.9 KiB
dct — type-II discrete cosine transform
Purpose
The DCT-II module is the cepstral projection step of the MFCC pipeline: it takes the log mel-spectrum of one frame and produces a compact vector of cepstral coefficients. The same routine is reusable anywhere a closed-form orthonormal-with-scale DCT is needed.
This implementation is unscaled (no sqrt(2/N) orthonormality factor) because downstream MFCC analysis is unit-agnostic: every coefficient is later compared to peers, not to an external reference. Callers that need an orthonormal form can post-multiply by the standard scaling factor.
Features
- Closed-form
X_k = Σ x_n · cos((π/N)(n + ½)k)for0 ≤ k < coefficients. - Cached per
(inputSize, coefficients)so repeated frames reuse the kernel matrix. - Pure portable TypeScript over
Float32Arrayinputs and outputs.
Usage: Basic
import { dctII } from "@suaveplan/audio-analysis-spectrum/algorithms/dct";
const logMel = new Float32Array(40); // log mel-spectrum
const mfcc = dctII(logMel, 13);
Usage: Advanced
import {
clearDctCache,
dctII,
} from "@suaveplan/audio-analysis-spectrum/algorithms/dct";
const coeffs = dctII(logMel, 20);
// later, before a benchmark sweep
clearDctCache();
API Reference
dctII(input, coefficients): Float32Array— firstcoefficientscepstral values.clearDctCache(): void— evict every cached kernel.
Implementation Notes
The kernel is stored as a flat Float64Array of coefficients * inputSize doubles so the per-frame inner loop is a single linear pass with no nested allocation. Kernel construction is O(coefficients · inputSize) and is cached on the (inputSize, coefficients) pair; runtime cost is then a single matrix-vector multiply per frame. Boundary checks on coefficients (positive, ≤ melBands) are enforced at the analyzer layer before this routine is called, so this module assumes a validated input.