kaldi-native-fbank C++ API
Kaldi-compatible feature extraction C++ API
Loading...
Searching...
No Matches
knf Namespace Reference

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.

Detailed Description

This file is part of kaldi-native-fbank.

Typedef Documentation

◆ MatrixD

using knf::MatrixD
Initial value:
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>

Double-precision accumulator/statistics matrix (e.g.

cmvn stats), matching kaldi's Matrix<double> layout.

◆ MatrixF

using knf::MatrixF
Initial value:
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>

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.

◆ OnlineFbank

Streaming filter-bank features; see FbankComputer.

◆ OnlineMfcc

Streaming MFCC features; see MfccComputer.

◆ OnlineRawAudioSamples

Streaming raw audio samples, framed without any processing.

◆ OnlineWhisperFbank

◆ VectorF

using knf::VectorF = Eigen::VectorXf

1-D feature/aux vector (float).

Function Documentation

◆ AccCmvnStats() [1/2]

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}) \]

Parameters
[in]featPointer to one frame, a 1-D array of size dim.
[in]dimFeature dimension of the frame; must equal stats->cols() - 1.
[in]weightWeight of this frame, e.g. 1.0.
[in,out]statsStats to update; must use the full 2-row layout.
knf::InitCmvnStats(dim, &stats);
for (int32_t t = 0; t < num_frames; ++t) {
knf::AccCmvnStats(feats.row(t).data(), dim, 1.0f, &stats);
}
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).
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > MatrixD
Double-precision accumulator/statistics matrix (e.g.
Definition feature-matrix.h:31
See also
InitCmvnStats, ComputeCmvnStats, CmvnAccumulator::Add

◆ AccCmvnStats() [2/2]

void knf::AccCmvnStats ( const MatrixF & feats,
MatrixD * stats )

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.

Parameters
[in]featsFeature matrix of size num_frames x dim.
[in,out]statsStats to update; must use the full 2-row layout.
See also
InitCmvnStats, CmvnAccumulator::Accumulate

◆ ApplyCmvn() [1/3]

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.

Parameters
[in]stats1-row or 2-row cmvn stats; see InitCmvnStats().
[in]optsOptions: norm_vars (normalize variances), reverse (undo cmvn).
[in]featsFeature matrix of size num_frames x dim.
Returns
A copy of feats with cmvn applied.

◆ ApplyCmvn() [2/3]

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).

See also
ApplyCmvn

◆ ApplyCmvn() [3/3]

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).

Parameters
[in]stats1-row or 2-row cmvn stats; see InitCmvnStats().
[in]optsOptions: norm_vars (normalize variances), reverse (undo cmvn).
[in,out]featsFeature matrix of size num_frames x dim; each row is normalized in place.
knf::CmvnOptions opts; // norm_vars=false, reverse=false
knf::ApplyCmvn(stats, opts, &feats); // feats normalized in place
void ApplyCmvn(const MatrixD &stats, const CmvnOptions &opts, MatrixF *feats)
Apply cmvn to feats in place (kaldi ApplyCmvn / ApplyCmvnReverse).
MatrixD ComputeCmvnStats(const MatrixF &feats)
Compute full 2-row cmvn stats for a whole matrix.
Options matching kaldi's apply-cmvn flags.
Definition feature-cmvn.h:50
See also
ComputeCmvnStats, CmvnOptions, CmvnAccumulator

◆ ApproxEqual()

template<typename Real>
bool knf::ApproxEqual ( Real a,
Real b,
Real tol = 0.01 )
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.

Parameters
[in]aFirst value.
[in]bSecond value.
[in]tolRelative tolerance (default 0.01).
Returns
True if a and b are approximately equal.

◆ ComputeAndProcessKaldiPitch()

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.

Parameters
[in]pitch_optsRaw pitch extraction options.
[in]process_optsPost-processing options.
[in]wavePointer 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]nNumber of samples in wave.
Returns
Feature matrix of shape (num_frames, process_opts.Dim()).

◆ ComputeCmvnStats()

MatrixD knf::ComputeCmvnStats ( const MatrixF & feats)

Compute full 2-row cmvn stats for a whole matrix.

Equivalent to InitCmvnStats() followed by AccCmvnStats() over all rows.

Parameters
[in]featsFeature matrix of size num_frames x dim.
Returns
The stats matrix of size 2 x (dim+1); see InitCmvnStats() for the layout. The frame count in stats(0, dim) is num_frames.
See also
InitCmvnStats, AccCmvnStats, ApplyCmvn

◆ ComputeDeltas()

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.

Parameters
[in]optsOrder/window; see DeltaOptions.
[in]featsFeature matrix of size T x D (T > 0, D > 0).
Returns
The matrix of size T x (D * (order + 1)).

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:

[1, 0.5, 0.75] // t=0: D = -0.5*1 + 0.5*2; D2 = 0.25*1 - 0.5*1 + 0.25*4
[2, 1.5, 0.25] // t=1: D = -0.5*1 + 0.5*4; D2 = 0.25*1 - 0.5*2 + 0.25*4
[4, 1.0, -0.75] // t=2: D = -0.5*2 + 0.5*4; D2 = 0.25*1 - 0.5*4 + 0.25*4

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:

[3, 0.0]
[1, -0.3]
[4, 0.4]
[1, 0.9]
[5, 0.6]

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:

x = [[1, 10], [2, 20], [4, 40]]
out rows [x1, x2, d1, d2, dd1, dd2]:
[1, 10, 0.5, 5.0, 0.75, 7.5]
[2, 20, 1.5, 15.0, 0.25, 2.5]
[4, 40, 1.0, 10.0, -0.75, -7.5]
knf::DeltaOptions opts; // order=2, window=2 -> 3*D dims
knf::MatrixF out = knf::ComputeDeltas(opts, feats);
Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > MatrixF
Row-major feature matrix: rows are frames, columns are features.
Definition feature-matrix.h:26
MatrixF ComputeDeltas(const DeltaOptions &opts, const MatrixF &feats)
Compute delta (dynamic) features.
Options for ComputeDeltas(); mirrors kaldi's add-deltas flags.
Definition feature-delta.h:42
Used by:
Pipelines that add dynamic features after cmvn (mfcc -> cmvn -> deltas).
See also
DeltaOptions, SpliceFrames

◆ ComputeLifterCoeffs()

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).

Parameters
[in]QLiftering constant, e.g. 22.0 (kaldi default).
[out]coeffsPre-allocated output vector of size num_ceps.
Used by:
MfccComputer (via MfccOptions::cepstral_lifter).
See also
MfccComputer, MfccOptions

◆ ComputePowerSpectrum()

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.

Parameters
[in,out]complex_fftThe complex FFT in the packed layout used by csrc/rfft.h; modified in place to hold the power spectrum.
See also
Rfft

◆ Exp() [1/2]

double knf::Exp ( double x)
inline

Exponential of x (double overload; matches kaldi's Exp).

◆ Exp() [2/2]

float knf::Exp ( float x)
inline

Exponential of x (float overload; matches kaldi's Exp).

◆ ExtractWindow()

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().

Parameters
[in]sample_offsetIf '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]waveThe waveform
[in]fThe frame index to be extracted, with 0 <= f < NumFrames(sample_offset + wave.Dim(), opts, true)
[in]optsThe options class to be used
[in]window_functionThe windowing function, as derived from the options class.
[out]windowThe windowed, possibly-padded waveform to be extracted. Will be resized as needed.
[out]log_energy_pre_windowIf non-NULL, the log-energy of the signal prior to pre-emphasis and multiplying by the windowing function will be written to here.
See also
ProcessWindow, NumFrames, FbankComputer::Compute, MfccComputer::Compute

◆ FirstSampleOfFrame()

int64_t knf::FirstSampleOfFrame ( int32_t frame,
const FrameExtractionOptions & opts )

Return the index of the first sample of the frame indexed frame.

See also
NumFrames, FrameExtractionOptions

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.

◆ Gcd()

template<typename I>
I knf::Gcd ( I m,
I n )
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.

Parameters
[in]mFirst integer.
[in]nSecond integer.
Returns
The greatest common divisor of m and n.

◆ GetWindow()

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:

  • "hanning": \( w[n] = 0.5 - 0.5 \cos(a n) \)
  • "hann": \( w[n] = 0.5 - 0.5 \cos(a n) \) with \( a = 2\pi/N \) (periodic variant; see https://pytorch.org/docs/stable/generated/torch.hann_window.html)
  • "sine": \( w[n] = \sin(0.5\,a\,n) = \sin(\pi n/(N-1)) \)
  • "hamming": \( w[n] = 0.54 - 0.46 \cos(a n) \)
  • "povey": \( w[n] = (0.5 - 0.5 \cos(a n))^{0.85} \) (like hamming but goes to zero at the edges)
  • "rectangular": \( w[n] = 1 \)
  • "blackman": \( w[n] = c - 0.5 \cos(a n) + (0.5 - c) \cos(2 a n) \) where \( c = \) blackman_coeff.

If window_type is not one of the above, an error is logged with KNF_LOGE() and std::invalid_argument is thrown.

Parameters
window_typeOne of "hamming", "rectangular", "povey", "hanning", "hann", "sine", "blackman".
window_sizeNumber of samples in the window.
blackman_coeffConstant coefficient for generalized Blackman window; only used if window_type is "blackman".
Returns
A vector of window_size window coefficients.
See also
FeatureWindowFunction

◆ GoldenDir()

std::string knf::GoldenDir ( )
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.

◆ InitCmvnStats()

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.

Parameters
[in]dimFeature dimension of the frames that will be accumulated, e.g. 39 for 39-dim MFCC.
[out]statsThe output stats matrix, resized to 2 x (dim+1).
knf::InitCmvnStats(39, &stats); // stats: 2 x 40, all zeros
See also
AccCmvnStats, ComputeCmvnStats, ApplyCmvn

◆ InnerProduct()

float knf::InnerProduct ( const float * a,
const float * b,
int32_t n )

Compute the inner product of two vectors of size n.

◆ Lcm()

template<typename I>
I knf::Lcm ( I m,
I n )
inline

Least common multiple of two integers.

Mirrors kaldi's Lcm in src/base/kaldi-math.h.

Parameters
[in]mFirst integer.
[in]nSecond integer.
Returns
The least common multiple of m and n (0 if either is 0).

◆ LoadNpy()

bool knf::LoadNpy ( const std::string & path,
MatrixD * out )
inline

Minimal .npy (v1/v2, C-order, float32/float64) reader for golden files.

Parameters
[in]pathPath of the .npy file.
[out]outMatrix filled with the file contents.
Returns
true on success.

◆ Log() [1/2]

double knf::Log ( double x)
inline

Natural logarithm of x (double overload; matches kaldi's Log).

◆ Log() [2/2]

float knf::Log ( float x)
inline

Natural logarithm of x (float overload; matches kaldi's Log).

◆ MaxAbsDiff()

double knf::MaxAbsDiff ( const MatrixF & a,
const MatrixD & b )
inline

Return the maximum absolute difference between a float matrix and a double matrix of the same shape (for golden comparisons).

◆ NumFrames()

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').

Parameters
[in]num_samplesThe number of samples in the wave file.
[in]optsThe frame-extraction options class
[in]flushTrue 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.
Returns
The number of frames that can be extracted.
See also
FirstSampleOfFrame, ExtractWindow

◆ operator<<() [1/6]

std::ostream & knf::operator<< ( std::ostream & os,
const FbankOptions & opts )

Write the options to the stream, one option per line.

◆ operator<<() [2/6]

std::ostream & knf::operator<< ( std::ostream & os,
const FrameExtractionOptions & opts )

Write the options to the stream, one option per line.

◆ operator<<() [3/6]

std::ostream & knf::operator<< ( std::ostream & os,
const MelBanksOptions & opts )

Write the options to the stream, one option per line.

◆ operator<<() [4/6]

std::ostream & knf::operator<< ( std::ostream & os,
const MfccOptions & opts )

Write the options to the stream, one option per line.

◆ operator<<() [5/6]

std::ostream & knf::operator<< ( std::ostream & os,
const NemoFbankOptions & opts )

Write the options to the stream, one option per line.

◆ operator<<() [6/6]

std::ostream & knf::operator<< ( std::ostream & os,
const RawAudioSamplesOptions & opts )

◆ ProcessWindow()

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.

Parameters
[in]optsThe options class to be used
[in]window_functionThe windowing function– should have been initialized using 'opts'.
[in,out]windowA 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_windowIf 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.
See also
ExtractWindow, FeatureWindowFunction

◆ Rand()

int knf::Rand ( struct RandomState * state = nullptr)

Return a random integer between 0 and RAND_MAX, inclusive.

◆ RandGauss()

float knf::RandGauss ( struct RandomState * state = nullptr)
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).

See also
RandUniform, RandomState

◆ RandUniform()

float knf::RandUniform ( struct RandomState * state = nullptr)
inline

Returns a random number strictly between 0 and 1.

See also
Rand, RandGauss, RandomState

◆ ResampleWaveform()

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.

Parameters
[in]orig_freqOriginal sample rate in Hz.
[in]waveThe input waveform.
[in]new_freqDesired sample rate in Hz.
[out]new_waveThe resampled waveform (resized internally).

◆ RoundUpToNearestPowerOfTwo()

int32_t knf::RoundUpToNearestPowerOfTwo ( int32_t n)
inline

Round n up to the nearest power of two.

Requires n > 0.

Copied from src/base/kaldi-math.cc.

◆ SpliceFrames()

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.

Parameters
[in]featsFeature matrix of size T x D (T > 0, D > 0).
[in]optsContexts; see SpliceOptions.
Returns
The spliced matrix of size T x (D * (1 + L + R)).
knf::SpliceOptions opts; // left=3, right=3 -> 7*D dims
knf::MatrixF spliced = knf::SpliceFrames(feats, opts);
MatrixF SpliceFrames(const MatrixF &feats, const SpliceOptions &opts)
Concatenate each frame with its left/right context neighbors.
Options for SpliceFrames(); mirrors kaldi's splice-feats flags.
Definition feature-splice.h:44
Used by:
Pipelines that build xvector/MFA-style features (mfcc -> cmvn -> splice -> lda).
See also
SpliceOptions

◆ Sqrt()

void knf::Sqrt ( float * in_out,
int32_t n )

Compute the square root of each element of an array in place.

Parameters
in_outPointer to an array of size n.
nNumber of elements.

Variable Documentation

◆ kGoldenDotProductTol

double knf::kGoldenDotProductTol = 1e-4
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.