|
kaldi-native-fbank C++ API
Kaldi-compatible feature extraction C++ API
|
This file is part of kaldi-native-fbank. More...
Classes | |
| struct | CmvnOptions |
| Options matching kaldi's apply-cmvn flags. More... | |
| class | CmvnAccumulator |
| Incremental accumulator for speaker-level / streaming cmvn. More... | |
| struct | DeltaOptions |
| Options for ComputeDeltas(); mirrors kaldi's add-deltas flags. More... | |
| struct | FbankOptions |
| Options for computing filter-bank features. More... | |
| class | FbankComputer |
| Class for computing mel-filterbank features. More... | |
| struct | MfccOptions |
| Options for computing MFCC features. More... | |
| class | MfccComputer |
| Class for computing MFCC features. More... | |
| struct | PitchExtractionOptions |
| Options for the raw pitch extraction stage (kaldi's PitchExtractionOptions). More... | |
| struct | ProcessPitchOptions |
| Options for the pitch post-processing stage (kaldi's ProcessPitchOptions). More... | |
| class | OnlinePitch |
| Streaming pitch extraction with post-processing (kaldi's OnlinePitchFeature + OnlineProcessPitch). More... | |
| struct | RawAudioSamplesOptions |
| Options for framing raw audio samples. More... | |
| class | RawAudioSamplesComputer |
| "Computer" that frames raw audio samples without any processing. More... | |
| struct | SpliceOptions |
| Options for SpliceFrames(); mirrors kaldi's splice-feats flags. More... | |
| class | FeatureTransform |
| A linear (or affine) feature transform, e.g. More... | |
| struct | FrameExtractionOptions |
| Options for extracting frames from a waveform. More... | |
| class | FeatureWindowFunction |
| Stores the windowing coefficients and applies them to a frame. More... | |
| class | IStft |
| Reconstruct a waveform from Stft results. More... | |
| struct | RandomState |
| State for the thread-safe random number generator. More... | |
| struct | MelBanksOptions |
| Options for constructing triangular mel-filterbank bins. More... | |
| class | MelBanks |
| Triangular mel-filterbank bins. More... | |
| struct | OnlineCmvnOptions |
| Options for OnlineCmvn, mirroring kaldi's OnlineCmvnOptions (kaldi/src/feat/online-feature.h). More... | |
| struct | OnlineCmvnState |
| State of CMVN adaptation between utterances (not the within-utterance computation state). More... | |
| class | OnlineCmvn |
| Online (running) cepstral mean and optional variance normalization. More... | |
| class | RecyclingVector |
| This class serves as a storage for feature vectors with an option to limit the memory usage by removing old elements. More... | |
| class | OnlineGenericBaseFeature |
| This is a templated class for online feature extraction; it's templated on a class like MfccComputer or FbankComputer that does the basic feature extraction. More... | |
| struct | NemoFbankOptions |
| Options for OnlineNemoFbank. More... | |
| class | OnlineNemoFbank |
| NeMo-compatible buffered streaming filter-bank features. More... | |
| class | ArbitraryResample |
| Resample a signal at arbitrary (e.g. More... | |
| class | LinearResample |
| Efficient up/downsampling at linearly spaced output times. More... | |
| class | Rfft |
| n-point real discrete Fourier transform, where n is even, n >= 2. More... | |
| struct | StftConfig |
| Configuration for Stft. More... | |
| struct | StftResult |
| Result of Stft::Compute(). More... | |
| class | Stft |
| Compute the short-time Fourier transform of a waveform. More... | |
| struct | WhisperFeatureOptions |
| Options for computing Whisper mel features. More... | |
| class | WhisperFeatureComputer |
| Class for computing Whisper mel features. More... | |
Typedefs | |
| using | MatrixF |
| Row-major feature matrix: rows are frames, columns are features. | |
| using | MatrixD |
| Double-precision accumulator/statistics matrix (e.g. | |
| using | VectorF = Eigen::VectorXf |
| 1-D feature/aux vector (float). | |
| using | OnlineRawAudioSamples = OnlineGenericBaseFeature<RawAudioSamplesComputer> |
| Streaming raw audio samples, framed without any processing. | |
| using | OnlineFbank = OnlineGenericBaseFeature<FbankComputer> |
| Streaming filter-bank features; see FbankComputer. | |
| using | OnlineMfcc = OnlineGenericBaseFeature<MfccComputer> |
| Streaming MFCC features; see MfccComputer. | |
| using | OnlineWhisperFbank = OnlineGenericBaseFeature<WhisperFeatureComputer> |
| Streaming Whisper log-mel features; see WhisperFeatureComputer. | |
Functions | |
| void | InitCmvnStats (int32_t dim, MatrixD *stats) |
| Initialize cmvn stats to zeros in the FULL 2-row layout. | |
| void | AccCmvnStats (const float *feat, int32_t dim, float weight, MatrixD *stats) |
| Accumulate stats for one frame (kaldi AccCmvnStats, same op order). | |
| void | AccCmvnStats (const MatrixF &feats, MatrixD *stats) |
| Accumulate stats for a feature matrix (rows = frames). | |
| MatrixD | ComputeCmvnStats (const MatrixF &feats) |
| Compute full 2-row cmvn stats for a whole matrix. | |
| void | ApplyCmvn (const MatrixD &stats, const CmvnOptions &opts, MatrixF *feats) |
| Apply cmvn to feats in place (kaldi ApplyCmvn / ApplyCmvnReverse). | |
| void | ApplyCmvn (const MatrixD &stats, const CmvnOptions &opts, Eigen::Ref< MatrixF > feats) |
| In-place variant taking a mutable Eigen view of the features. | |
| MatrixF | ApplyCmvn (const MatrixD &stats, const CmvnOptions &opts, const MatrixF &feats) |
| Convenience version of ApplyCmvn(): returns the normalized copy. | |
| MatrixF | ComputeDeltas (const DeltaOptions &opts, const MatrixF &feats) |
| Compute delta (dynamic) features. | |
| std::ostream & | operator<< (std::ostream &os, const FbankOptions &opts) |
| Write the options to the stream, one option per line. | |
| void | ComputePowerSpectrum (std::vector< float > *complex_fft) |
| ComputePowerSpectrum converts a complex FFT (as produced by the FFT functions in csrc/rfft.h), and converts it into a power spectrum. | |
| std::ostream & | operator<< (std::ostream &os, const MfccOptions &opts) |
| Write the options to the stream, one option per line. | |
| MatrixF | ComputeAndProcessKaldiPitch (const PitchExtractionOptions &pitch_opts, const ProcessPitchOptions &process_opts, const float *wave, int32_t n) |
| Batch pitch extraction (kaldi's ComputeAndProcessKaldiPitch). | |
| std::ostream & | operator<< (std::ostream &os, const RawAudioSamplesOptions &opts) |
| MatrixF | SpliceFrames (const MatrixF &feats, const SpliceOptions &opts) |
| Concatenate each frame with its left/right context neighbors. | |
| int32_t | RoundUpToNearestPowerOfTwo (int32_t n) |
| Round n up to the nearest power of two. | |
| std::ostream & | operator<< (std::ostream &os, const FrameExtractionOptions &opts) |
| Write the options to the stream, one option per line. | |
| int64_t | FirstSampleOfFrame (int32_t frame, const FrameExtractionOptions &opts) |
| Return the index of the first sample of the frame indexed frame. | |
| int32_t | NumFrames (int64_t num_samples, const FrameExtractionOptions &opts, bool flush=true) |
| This function returns the number of frames that we can extract from a wave file with the given number of samples in it (assumed to have the same sampling rate as specified in 'opts'). | |
| void | ExtractWindow (int64_t sample_offset, const std::vector< float > &wave, int32_t f, const FrameExtractionOptions &opts, const FeatureWindowFunction &window_function, std::vector< float > *window, float *log_energy_pre_window=nullptr) |
| ExtractWindow() extracts a windowed frame of waveform (possibly with a power-of-two, padded size, depending on the config), including all the processing done by ProcessWindow(). | |
| void | ProcessWindow (const FrameExtractionOptions &opts, const FeatureWindowFunction &window_function, float *window, float *log_energy_pre_window=nullptr) |
| This function does all the windowing steps after actually extracting the windowed signal: depending on the configuration, it does dithering, dc offset removal, preemphasis, and multiplication by the windowing function. | |
| float | InnerProduct (const float *a, const float *b, int32_t n) |
| Compute the inner product of two vectors of size n. | |
| std::vector< float > | GetWindow (const std::string &window_type, int32_t window_size, float blackman_coeff=0.42) |
| Return the window coefficients of the given window type. | |
| float | Log (float x) |
| Natural logarithm of x (float overload; matches kaldi's Log). | |
| double | Log (double x) |
| Natural logarithm of x (double overload; matches kaldi's Log). | |
| float | Exp (float x) |
| Exponential of x (float overload; matches kaldi's Exp). | |
| double | Exp (double x) |
| Exponential of x (double overload; matches kaldi's Exp). | |
| template<typename I> | |
| I | Gcd (I m, I n) |
| Greatest common divisor of two integers. | |
| template<typename I> | |
| I | Lcm (I m, I n) |
| Least common multiple of two integers. | |
| template<typename Real> | |
| bool | ApproxEqual (Real a, Real b, Real tol=0.01) |
| Approximate floating-point equality test. | |
| int | Rand (struct RandomState *state=nullptr) |
| Return a random integer between 0 and RAND_MAX, inclusive. | |
| float | RandUniform (struct RandomState *state=nullptr) |
| Returns a random number strictly between 0 and 1. | |
| float | RandGauss (struct RandomState *state=nullptr) |
| Return a random sample from the standard normal distribution. | |
| void | Sqrt (float *in_out, int32_t n) |
| Compute the square root of each element of an array in place. | |
| std::ostream & | operator<< (std::ostream &os, const MelBanksOptions &opts) |
| Write the options to the stream, one option per line. | |
| void | ComputeLifterCoeffs (float Q, std::vector< float > *coeffs) |
| Compute liftering coefficients (scaling on cepstral coeffs). | |
| std::ostream & | operator<< (std::ostream &os, const NemoFbankOptions &opts) |
| Write the options to the stream, one option per line. | |
| void | ResampleWaveform (float orig_freq, const VectorF &wave, float new_freq, VectorF *new_wave) |
| Downsample or upsample a waveform (convenience wrapper). | |
| bool | LoadNpy (const std::string &path, MatrixD *out) |
| Minimal .npy (v1/v2, C-order, float32/float64) reader for golden files. | |
| std::string | GoldenDir () |
| Locate tests/data/feat_golden relative to this header. | |
| double | MaxAbsDiff (const MatrixF &a, const MatrixD &b) |
| Return the maximum absolute difference between a float matrix and a double matrix of the same shape (for golden comparisons). | |
Variables | |
| constexpr double | kGoldenDotProductTol = 1e-4 |
| Comparison tolerance for golden matrices whose kaldi reference was produced by matrix multiplications or long dot products (the LDA transform-feats outputs and the pitch NCCF): kaldi's BLAS and Eigen accumulate the sums in different orders, which gives per-platform float noise of up to a few 1e-5. | |
This file is part of kaldi-native-fbank.
| using knf::MatrixD |
Double-precision accumulator/statistics matrix (e.g.
cmvn stats), matching kaldi's Matrix<double> layout.
| using knf::MatrixF |
Row-major feature matrix: rows are frames, columns are features.
Row-major matches kaldi's Matrix<float> memory layout, so golden data produced by kaldi can be compared directly.
Streaming filter-bank features; see FbankComputer.
Streaming MFCC features; see MfccComputer.
Streaming raw audio samples, framed without any processing.
Streaming Whisper log-mel features; see WhisperFeatureComputer.
| using knf::VectorF = Eigen::VectorXf |
1-D feature/aux vector (float).
| void knf::AccCmvnStats | ( | const float * | feat, |
| int32_t | dim, | ||
| float | weight, | ||
| MatrixD * | stats ) |
Accumulate stats for one frame (kaldi AccCmvnStats, same op order).
The following updates are applied to stats, which must use the full 2-row layout (see InitCmvnStats()); with \( w = \) weight and \( x_d = \) feat[d]:
\[ c \mathrel{+}= w, \qquad S_d \mathrel{+}= x_d\, w, \qquad Q_d \mathrel{+}= x_d^2\, w \qquad (0 \le d < \mathrm{dim}) \]
| [in] | feat | Pointer to one frame, a 1-D array of size dim. |
| [in] | dim | Feature dimension of the frame; must equal stats->cols() - 1. |
| [in] | weight | Weight of this frame, e.g. 1.0. |
| [in,out] | stats | Stats to update; must use the full 2-row layout. |
Accumulate stats for a feature matrix (rows = frames).
This is equivalent to calling the single-frame AccCmvnStats() above for every row of feats, with weight 1.0.
| [in] | feats | Feature matrix of size num_frames x dim. |
| [in,out] | stats | Stats to update; must use the full 2-row layout. |
| MatrixF knf::ApplyCmvn | ( | const MatrixD & | stats, |
| const CmvnOptions & | opts, | ||
| const MatrixF & | feats ) |
Convenience version of ApplyCmvn(): returns the normalized copy.
Same semantics as the in-place ApplyCmvn() above, but feats is left unchanged and a normalized copy is returned.
| [in] | stats | 1-row or 2-row cmvn stats; see InitCmvnStats(). |
| [in] | opts | Options: norm_vars (normalize variances), reverse (undo cmvn). |
| [in] | feats | Feature matrix of size num_frames x dim. |
| void knf::ApplyCmvn | ( | const MatrixD & | stats, |
| const CmvnOptions & | opts, | ||
| Eigen::Ref< MatrixF > | feats ) |
In-place variant taking a mutable Eigen view of the features.
Same semantics as the pointer version above. The view must already have the right shape. It enables zero-copy application to a mapped buffer (e.g. a numpy array via pybind11).
| void knf::ApplyCmvn | ( | const MatrixD & | stats, |
| const CmvnOptions & | opts, | ||
| MatrixF * | feats ) |
Apply cmvn to feats in place (kaldi ApplyCmvn / ApplyCmvnReverse).
Let \( c = \mathrm{stats}(0, \mathrm{dim}) \) be the frame count, \( \mu_d = \mathrm{stats}(0, d) / c \) the mean and, when norm_vars is true, \( \sigma_d^2 = \mathrm{stats}(1, d) / c - \mu_d^2 \) the variance of dimension \( d \).
Forward (opts.reverse == false), applied to every frame \( x \):
\[ x_d \leftarrow x_d - \mu_d \]
and, if opts.norm_vars:
\[ x_d \leftarrow (x_d - \mu_d) / \sigma_d \]
Reverse (opts.reverse == true) undoes the normalization:
\[ x_d \leftarrow x_d + \mu_d \]
and, if opts.norm_vars:
\[ x_d \leftarrow x_d \cdot \sigma_d + \mu_d \]
Accepts 1-row (mean-only) or 2-row stats; requesting norm_vars with 1-row stats is an error (same as kaldi).
| [in] | stats | 1-row or 2-row cmvn stats; see InitCmvnStats(). |
| [in] | opts | Options: norm_vars (normalize variances), reverse (undo cmvn). |
| [in,out] | feats | Feature matrix of size num_frames x dim; each row is normalized in place. |
|
inline |
Approximate floating-point equality test.
Returns true if a and b are equal to a relative tolerance tol:
\[ |a - b| \le \mathrm{tol} \cdot (|a| + |b|) \]
Mirrors kaldi's ApproxEqual in src/base/kaldi-math.h.
| [in] | a | First value. |
| [in] | b | Second value. |
| [in] | tol | Relative tolerance (default 0.01). |
| MatrixF knf::ComputeAndProcessKaldiPitch | ( | const PitchExtractionOptions & | pitch_opts, |
| const ProcessPitchOptions & | process_opts, | ||
| const float * | wave, | ||
| int32_t | n ) |
Batch pitch extraction (kaldi's ComputeAndProcessKaldiPitch).
Combines the raw pitch extraction and the post-processing in one call; the output equals what kaldi's compute-and-process-kaldi-pitch-feats produces for the same input and options. It is sensitive to the variables in pitch_opts that relate to online processing, i.e. max_frames_latency, frames_per_chunk, simulate_first_pass_online, recompute_frame.
| [in] | pitch_opts | Raw pitch extraction options. |
| [in] | process_opts | Post-processing options. |
| [in] | wave | Pointer to a 1-D array of n waveform samples (as returned by a WAV reader; kaldi semantics, i.e. raw int16 magnitudes, not divided by 32768). |
| [in] | n | Number of samples in wave. |
Compute full 2-row cmvn stats for a whole matrix.
Equivalent to InitCmvnStats() followed by AccCmvnStats() over all rows.
| [in] | feats | Feature matrix of size num_frames x dim. |
| MatrixF knf::ComputeDeltas | ( | const DeltaOptions & | opts, |
| const MatrixF & | feats ) |
Compute delta (dynamic) features.
This is kaldi's add-deltas (kaldi DeltaFeatures / ComputeDeltas in src/feat/feature-functions.cc), same arithmetic. The \( i \)-th block of the output is the \( i \)-th order regression delta; with \( N = \) opts.window, the first-order delta of frame \( t \) is
\[ \Delta_t = \frac{\sum_{j=-N}^{N} j\, x_{\mathrm{clamp}(t+j)}} {2 \sum_{j=1}^{N} j^2} \]
where out-of-range frames clamp to the first/last frame (edge frames are replicated). Higher orders apply the same operator recursively to the previous order's window (kaldi's scales_ recursion). The output rows are [x_t, \Delta_t, \Delta^2_t, \ldots], i.e. the block order is baseline first, then increasing delta order.
| [in] | opts | Order/window; see DeltaOptions. |
| [in] | feats | Feature matrix of size T x D (T > 0, D > 0). |
The regression windows themselves are computed as follows. With \( N \) = opts.window, the first-order window is
\[ w^{(1)}_j = \frac{j}{\sum_{k=-N}^{N} k^2} = \frac{j}{2 \sum_{k=1}^{N} k^2}, \qquad j = -N, \ldots, N \]
and each higher-order window is the discrete convolution of the previous window with \( w^{(1)} \) (kaldi's scales_ recursion):
\[ w^{(i)} = w^{(i-1)} * w^{(1)}, \qquad w^{(0)} = [1] \]
so \( w^{(i)} \) is the \( i \)-fold convolution of \( w^{(1)} \) (its length is 1 + 2 * i * window).
Motivation.** The spectrum of speech is strongly non-stationary: the trajectory* of the spectrum over time carries information that the static spectrum does not. Furui (1986) showed that appending the time derivative of the spectrum (the "delta") significantly improves recognition. HTK refined this into the regression-based formulation used here: instead of a raw difference such as \( x_{t+1} - x_{t-1} \), the local slope of a least-squares line is estimated over a window of \( 2N+1 \) frames, which is less sensitive to noise and to isolated outliers. kaldi's DeltaFeatures implements the same HTK formulation.
Why this definition.** The first-order window is the slope of the least-squares straight line fitted to the frames around \( t \) — the classic HTK regression delta that kaldi's DeltaFeatures implements. Fitting \( y(j) = a + b\, j \) to \( x_{t+j} \), \( j = -N, \ldots, N \), by minimizing \( \sum_j (x_{t+j} - a - b\, j)^2 \), and using \( \sum_j j = 0 \) (which decouples the intercept from the slope), the slope estimate is
\[ b = \frac{\sum_j j\, x_{t+j}}{\sum_j j^2} = \sum_j w^{(1)}_j\, x_{t+j} \]
so \( w^{(1)}_j = j / \sum_k k^2 \) is exactly the least-squares slope estimator: \( \Delta_t = b \) is the local slope of the fitted line, i.e. a least-squares estimate of the first derivative (the \( \sum_j j^2 \) normalizer is the OLS denominator).
Higher orders apply the same slope estimator to the previous order's output ( \( \Delta^2 \) is "the slope of the slope"). Since the slope estimator is a linear filter with kernel \( w^{(1)} \), filtering an already-filtered sequence convolves the kernels, hence \( w^{(i)} = w^{(i-1)} * w^{(1)} \) with support growing to \( \pm i N \). Note this is recursive slope-of-slope — it is not identical to the \( i \)-th derivative of a degree- \( i \) least-squares polynomial fitted over the wider \( \pm iN \) window.
Normalizing by \( \sum_j j^2 \) at every order keeps each block on the scale of a true \( i \)-th derivative, and edge frames replicate the first/last frame so the frame count is preserved and the regression "sees" a locally constant signal at the borders. This is the standard HTK/kaldi dynamic-feature formulation.
References.**
The ported implementation: kaldi's DeltaFeatures (src/feat/feature-functions.cc, src/feat/feature-functions.h). The regression-delta formulation: The HTK Book, S. Young et al., Cambridge University Engineering Department, 2006, chapter 5 ("Speech Input/Output"), section 5.9 ("Delta, Acceleration and Third Differential Coefficients"); PDF: htkbook.pdf Delta features originate from S. Furui, "Speaker-independent isolated word recognition using dynamic features of speech spectrum", IEEE Trans. Acoustics, Speech, and Signal Processing, 1986, https://doi.org/10.1109/TASSP.1986.1164788
How the convolution is computed.** The discrete convolution of two windows \( a \) (indices \( -A..A \)) and \( b \) (indices \( -B..B \)) is the window \( c = a * b \) (indices \( -(A+B)..A+B \)) defined by
\[ c_m = \sum_{k} a_k \, b_{m-k} \]
where \( a_k \) and \( b_k \) are zero outside their index ranges. For the second-order window this is
\[ w^{(2)}_m = \sum_{k=-N}^{N} w^{(1)}_k \, w^{(1)}_{m-k} \]
Window example 1 - N = 1, orders 1 to 3.** \( \sum_{k=-1}^{1} k^2 = 2 \), so the first-order window is \( w^{(1)}_j = j/2 = [-0.5, 0, 0.5] \). The convolution \( w^{(2)}_m = \sum_k w^{(1)}_k w^{(1)}_{m-k} \) term by term:
\( m = -2 \): \( w^{(1)}_{-1} w^{(1)}_{-1} = (-0.5)(-0.5) = 0.25 \) \( m = -1 \): \( w^{(1)}_{-1} w^{(1)}_{0} + w^{(1)}_{0} w^{(1)}_{-1} = (-0.5)(0) + (0)(-0.5) = 0 \) \( m = 0 \): \( w^{(1)}_{-1} w^{(1)}_{1} + w^{(1)}_{0} w^{(1)}_{0} + w^{(1)}_{1} w^{(1)}_{-1} = (-0.5)(0.5) + 0 + (0.5)(-0.5) = -0.5 \) \( m = 1 \): \( w^{(1)}_{0} w^{(1)}_{1} + w^{(1)}_{1} w^{(1)}_{0} = 0 \) \( m = 2 \): \( w^{(1)}_{1} w^{(1)}_{1} = (0.5)(0.5) = 0.25 \)
which gives \( w^{(2)} = [0.25, 0, -0.5, 0, 0.25] \). Convolving once more, \( w^{(3)} = w^{(2)} * w^{(1)} \); e.g. \( w^{(3)}_{-3} = w^{(1)}_{-1} w^{(2)}_{-2} = (-0.5)(0.25) = -0.125 \) and \( w^{(3)}_{-1} = w^{(1)}_{-1} w^{(2)}_{0} + w^{(1)}_{1} w^{(2)}_{-2} = (-0.5)(-0.5) + (0.5)(0.25) = 0.375 \). The full chain for N = 1:
\( w^{(0)} = [1] \) \( w^{(1)} = [-0.5, 0, 0.5] \) \( w^{(2)} = [0.25, 0, -0.5, 0, 0.25] \) \( w^{(3)} = [-0.125, 0, 0.375, 0, -0.375, 0, 0.125] \)
Window example 2 - N = 2.** \( \sum_{k=-2}^{2} k^2 = 10 \), so \( w^{(1)}_j = j/10 = [-0.2, -0.1, 0, 0.1, 0.2] \). Two sample convolution sums for \( w^{(2)} = w^{(1)} * w^{(1)} \):
\( w^{(2)}_{0} = \sum_k w^{(1)}_k w^{(1)}_{-k} = 2(-0.2)(0.2) + 2(-0.1)(0.1) + (0)(0) = -0.1 \) \( w^{(2)}_{4} = w^{(1)}_{2} w^{(1)}_{2} = (0.2)(0.2) = 0.04 \)
The full 9-tap window is \( w^{(2)} = [0.04, 0.04, 0.01, -0.04, -0.1, -0.04, 0.01, 0.04, 0.04] \).
Example 1 - full derivation** (x = [1, 2, 4], order=2, window=1). With the windows derived above, \( w^{(1)} = [-0.5, 0, 0.5] \) and \( w^{(2)} = [0.25, 0, -0.5, 0, 0.25] \), i.e.
\[ \Delta_t = -0.5\, x_{t-1} + 0.5\, x_{t+1} \]
\[ \Delta^2_t = 0.25\, x_{t-2} - 0.5\, x_t + 0.25\, x_{t+2} \]
For the 1-D input x = [1, 2, 4] (out-of-range frames clamp to the first/last frame) the output rows [x_t, \Delta_t, \Delta^2_t] are:
Example 2 - larger window** (x = [3, 1, 4, 1, 5], order=1, window=2). With \( N = 2 \), \( \sum_{k=-2}^{2} k^2 = 10 \), so \( w^{(1)} = [-0.2, -0.1, 0, 0.1, 0.2] \) (each entry is \( j/10 \)). At \( t = 2 \): \( \Delta = -0.2 \cdot 3 - 0.1 \cdot 1 + 0.1 \cdot 1 + 0.2 \cdot 5 = 0.4 \). The output rows [x, delta] are:
Example 3 - two feature dimensions** (D = 2, order=2, window=1). Each dimension is processed independently; the blocks are [x, delta, delta2] with dimensions interleaved per block:
| void knf::ComputeLifterCoeffs | ( | float | Q, |
| std::vector< float > * | coeffs ) |
Compute liftering coefficients (scaling on cepstral coeffs).
For \( i = 0, \ldots, n-1 \), where \( n = \) coeffs->size():
\[ \mathrm{coeffs}[i] = 1 + \frac{Q}{2} \sin\left(\frac{\pi i}{Q}\right) \]
Coeffs are numbered slightly differently from HTK: the zeroth index is C0, which is not affected. Q must be > 0: with Q == 0 the result is undefined (division by zero). "No liftering" is handled by the caller by not calling this function at all (see MfccOptions::cepstral_lifter).
| [in] | Q | Liftering constant, e.g. 22.0 (kaldi default). |
| [out] | coeffs | Pre-allocated output vector of size num_ceps. |
| void knf::ComputePowerSpectrum | ( | std::vector< float > * | complex_fft | ) |
ComputePowerSpectrum converts a complex FFT (as produced by the FFT functions in csrc/rfft.h), and converts it into a power spectrum.
If the complex FFT is a vector of size n (representing half of the complex FFT of a real signal of size n, as described there), this function computes in the first (n/2) + 1 elements of it, the energies of the fft bins from zero to the Nyquist frequency. Contents of the remaining (n/2) - 1 elements are undefined at output.
| [in,out] | complex_fft | The complex FFT in the packed layout used by csrc/rfft.h; modified in place to hold the power spectrum. |
|
inline |
Exponential of x (double overload; matches kaldi's Exp).
|
inline |
Exponential of x (float overload; matches kaldi's Exp).
| void knf::ExtractWindow | ( | int64_t | sample_offset, |
| const std::vector< float > & | wave, | ||
| int32_t | f, | ||
| const FrameExtractionOptions & | opts, | ||
| const FeatureWindowFunction & | window_function, | ||
| std::vector< float > * | window, | ||
| float * | log_energy_pre_window = nullptr ) |
ExtractWindow() extracts a windowed frame of waveform (possibly with a power-of-two, padded size, depending on the config), including all the processing done by ProcessWindow().
| [in] | sample_offset | If 'wave' is not the entire waveform, but part of it to the left has been discarded, then the number of samples prior to 'wave' that we have already discarded. Set this to zero if you are processing the entire waveform in one piece, or if you get 'no matching function' compilation errors when updating the code. |
| [in] | wave | The waveform |
| [in] | f | The frame index to be extracted, with 0 <= f < NumFrames(sample_offset + wave.Dim(), opts, true) |
| [in] | opts | The options class to be used |
| [in] | window_function | The windowing function, as derived from the options class. |
| [out] | window | The windowed, possibly-padded waveform to be extracted. Will be resized as needed. |
| [out] | log_energy_pre_window | If non-NULL, the log-energy of the signal prior to pre-emphasis and multiplying by the windowing function will be written to here. |
| int64_t knf::FirstSampleOfFrame | ( | int32_t | frame, |
| const FrameExtractionOptions & | opts ) |
Return the index of the first sample of the frame indexed frame.
If snip_edges=true, it just returns frame * opts.WindowShift(); if snip_edges=false, the formula is a little more complicated and the result may be negative.
|
inline |
Greatest common divisor of two integers.
Euclid's algorithm; both arguments must be >= 0 and not both zero. Mirrors kaldi's Gcd in src/base/kaldi-math.h.
| [in] | m | First integer. |
| [in] | n | Second integer. |
| std::vector< float > knf::GetWindow | ( | const std::string & | window_type, |
| int32_t | window_size, | ||
| float | blackman_coeff = 0.42 ) |
Return the window coefficients of the given window type.
Let \( N \) be window_size, \( n = 0, \ldots, N-1 \) the sample index, and \( a = 2\pi/(N-1) \). The supported window types and their formulas are:
If window_type is not one of the above, an error is logged with KNF_LOGE() and std::invalid_argument is thrown.
| window_type | One of "hamming", "rectangular", "povey", "hanning", "hann", "sine", "blackman". |
| window_size | Number of samples in the window. |
| blackman_coeff | Constant coefficient for generalized Blackman window; only used if window_type is "blackman". |
|
inline |
Locate tests/data/feat_golden relative to this header.
Uses plain string operations (std::filesystem is not portable). The header lives in the same directory as the test-*.cc files, so the resolved path is the same for every test.
| void knf::InitCmvnStats | ( | int32_t | dim, |
| MatrixD * | stats ) |
Initialize cmvn stats to zeros in the FULL 2-row layout.
The output matrix stats is resized to 2 x (dim+1) and set to zero. Its layout matches kaldi's cmvn.ark format exactly:
\[ \mathrm{stats} = \left( \begin{array}{cccc|c} S_1 & S_2 & \cdots & S_D & c \\ Q_1 & Q_2 & \cdots & Q_D & - \end{array} \right) \]
Row 0 (above): columns 0 .. dim-1 hold the sums \( S_d = \sum_t x_t(d) \) of each feature dimension; the last column \( c \) holds the frame count (sum of weights).
Row 1 (below): columns 0 .. dim-1 hold the sums of squares \( Q_d = \sum_t x_t(d)^2 \); the last column is unused.
This is the form produced/consumed by AccCmvnStats(), ComputeCmvnStats() and ApplyCmvn() with norm_vars=true.
Note: ApplyCmvn() also accepts 1-row (mean-only) stats, where only row 0 above is present; this function, however, only produces the 2-row form used for accumulating both mean and variance.
| [in] | dim | Feature dimension of the frames that will be accumulated, e.g. 39 for 39-dim MFCC. |
| [out] | stats | The output stats matrix, resized to 2 x (dim+1). |
| float knf::InnerProduct | ( | const float * | a, |
| const float * | b, | ||
| int32_t | n ) |
Compute the inner product of two vectors of size n.
|
inline |
Least common multiple of two integers.
Mirrors kaldi's Lcm in src/base/kaldi-math.h.
| [in] | m | First integer. |
| [in] | n | Second integer. |
|
inline |
Minimal .npy (v1/v2, C-order, float32/float64) reader for golden files.
| [in] | path | Path of the .npy file. |
| [out] | out | Matrix filled with the file contents. |
|
inline |
Natural logarithm of x (double overload; matches kaldi's Log).
|
inline |
Natural logarithm of x (float overload; matches kaldi's Log).
Return the maximum absolute difference between a float matrix and a double matrix of the same shape (for golden comparisons).
| int32_t knf::NumFrames | ( | int64_t | num_samples, |
| const FrameExtractionOptions & | opts, | ||
| bool | flush = true ) |
This function returns the number of frames that we can extract from a wave file with the given number of samples in it (assumed to have the same sampling rate as specified in 'opts').
| [in] | num_samples | The number of samples in the wave file. |
| [in] | opts | The frame-extraction options class |
| [in] | flush | True if we are asserting that this number of samples is 'all there is', false if we expecting more data to possibly come in. This only makes a difference to the answer if opts.snip_edges== false. For offline feature extraction you always want flush == true. In an online-decoding context, once you know (or decide) that no more data is coming in, you'd call it with flush == true at the end to flush out any remaining data. |
| std::ostream & knf::operator<< | ( | std::ostream & | os, |
| const FbankOptions & | opts ) |
Write the options to the stream, one option per line.
| std::ostream & knf::operator<< | ( | std::ostream & | os, |
| const FrameExtractionOptions & | opts ) |
Write the options to the stream, one option per line.
| std::ostream & knf::operator<< | ( | std::ostream & | os, |
| const MelBanksOptions & | opts ) |
Write the options to the stream, one option per line.
| std::ostream & knf::operator<< | ( | std::ostream & | os, |
| const MfccOptions & | opts ) |
Write the options to the stream, one option per line.
| std::ostream & knf::operator<< | ( | std::ostream & | os, |
| const NemoFbankOptions & | opts ) |
Write the options to the stream, one option per line.
| std::ostream & knf::operator<< | ( | std::ostream & | os, |
| const RawAudioSamplesOptions & | opts ) |
| void knf::ProcessWindow | ( | const FrameExtractionOptions & | opts, |
| const FeatureWindowFunction & | window_function, | ||
| float * | window, | ||
| float * | log_energy_pre_window = nullptr ) |
This function does all the windowing steps after actually extracting the windowed signal: depending on the configuration, it does dithering, dc offset removal, preemphasis, and multiplication by the windowing function.
| [in] | opts | The options class to be used |
| [in] | window_function | The windowing function– should have been initialized using 'opts'. |
| [in,out] | window | A vector of size opts.WindowSize(). Note: it will typically be a sub-vector of a larger vector of size opts.PaddedWindowSize(), with the remaining samples zero, as the FFT code is more efficient if it operates on data with power-of-two size. |
| [out] | log_energy_pre_window | If non-NULL, then after dithering and DC offset removal, this function will write to this pointer the log of the total energy (i.e. sum-squared) of the frame. |
| int knf::Rand | ( | struct RandomState * | state = nullptr | ) |
Return a random integer between 0 and RAND_MAX, inclusive.
|
inline |
Return a random sample from the standard normal distribution.
Uses the Box-Muller transform: \( \sqrt{-2 \ln U_1} \cos(2 \pi U_2) \) with \( U_1, U_2 \) drawn uniformly from (0, 1).
|
inline |
Returns a random number strictly between 0 and 1.
| void knf::ResampleWaveform | ( | float | orig_freq, |
| const VectorF & | wave, | ||
| float | new_freq, | ||
| VectorF * | new_wave ) |
Downsample or upsample a waveform (convenience wrapper).
This is a convenience wrapper for the class 'LinearResample'. The low-pass filter cutoff used in 'LinearResample' is 0.99 of the Nyquist, where the Nyquist is half of the minimum of (orig_freq, new_freq). The resampling is done with a symmetric FIR filter with N_z (number of zeros) as 6.
We compared the downsampling results with those from the sox resampling toolkit. Sox's design is inspired by Laurent De Soras' paper, https://ccrma.stanford.edu/~jos/resample/Implementation.html
Note: we expect that while orig_freq and new_freq are floats, they are actually required to have exact integer values (like 16000 or 8000) with a ratio between them that can be expressed as a rational number with reasonably small integer factors.
| [in] | orig_freq | Original sample rate in Hz. |
| [in] | wave | The input waveform. |
| [in] | new_freq | Desired sample rate in Hz. |
| [out] | new_wave | The resampled waveform (resized internally). |
|
inline |
| MatrixF knf::SpliceFrames | ( | const MatrixF & | feats, |
| const SpliceOptions & | opts ) |
Concatenate each frame with its left/right context neighbors.
This is kaldi's splice-feats (kaldi SpliceFrames in src/feat/feature-functions.cc), same arithmetic: for every frame index \( t \) the output row is
\[ y_t = [ x_{\max(0, t-L)}, \ldots, x_{\min(T-1, t+R)} ] \]
where \( L = \) opts.left_context, \( R = \) opts.right_context and \( T \) is the number of input frames. Edge frames are replicated: out-of-range indices clamp to the first/last frame. The output therefore has the same number of frames as the input and dim * (1 + L + R) dimensions.
| [in] | feats | Feature matrix of size T x D (T > 0, D > 0). |
| [in] | opts | Contexts; see SpliceOptions. |
| void knf::Sqrt | ( | float * | in_out, |
| int32_t | n ) |
Compute the square root of each element of an array in place.
| in_out | Pointer to an array of size n. |
| n | Number of elements. |
|
constexpr |
Comparison tolerance for golden matrices whose kaldi reference was produced by matrix multiplications or long dot products (the LDA transform-feats outputs and the pitch NCCF): kaldi's BLAS and Eigen accumulate the sums in different orders, which gives per-platform float noise of up to a few 1e-5.
Observed maxima for the LDA goldens: 1.5e-5 (linux-arm32), 1.1e-5 (windows-x64), 2.7e-5 (windows-arm64); the golden-generating platform agrees at <= 1e-5. 1e-4 leaves headroom while still catching real implementation differences (>= 1e-3). Pipelines of sequential reductions (cmvn/delta/splice) compare at the tighter 1e-5 instead.