|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | +// |
| 4 | +// NeMo-compatible log-mel spectrogram extraction (Slaney scale, matching librosa/NeMo). |
| 5 | +// No ONNX Runtime or other framework dependencies — pure C++ with standard library only. |
| 6 | + |
| 7 | +#include "nemo_mel_spectrogram.h" |
| 8 | + |
| 9 | +#include <algorithm> |
| 10 | +#include <cmath> |
| 11 | +#include <cstring> |
| 12 | +#include <vector> |
| 13 | + |
| 14 | +#ifndef M_PI |
| 15 | +#define M_PI 3.14159265358979323846 |
| 16 | +#endif |
| 17 | + |
| 18 | +namespace nemo_mel { |
| 19 | + |
| 20 | +// ─── Slaney mel scale constants ───────────────────────────────────────────── |
| 21 | + |
| 22 | +static constexpr float kMinLogHz = 1000.0f; |
| 23 | +static constexpr float kMinLogMel = 15.0f; // 1000 / (200/3) |
| 24 | +static constexpr float kLinScale = 200.0f / 3.0f; // Hz per mel (linear region) |
| 25 | +static constexpr float kLogStep = 0.06875177742094912f; // log(6.4) / 27 |
| 26 | + |
| 27 | +// ─── Mel scale conversions ────────────────────────────────────────────────── |
| 28 | + |
| 29 | +float HzToMel(float hz) { |
| 30 | + if (hz < kMinLogHz) return hz / kLinScale; |
| 31 | + return kMinLogMel + std::log(hz / kMinLogHz) / kLogStep; |
| 32 | +} |
| 33 | + |
| 34 | +float MelToHz(float mel) { |
| 35 | + if (mel < kMinLogMel) return mel * kLinScale; |
| 36 | + return kMinLogHz * std::exp((mel - kMinLogMel) * kLogStep); |
| 37 | +} |
| 38 | + |
| 39 | +// ─── Filterbank creation ──────────────────────────────────────────────────── |
| 40 | + |
| 41 | +std::vector<std::vector<float>> CreateMelFilterbank(int num_mels, int fft_size, int sample_rate) { |
| 42 | + int num_bins = fft_size / 2 + 1; |
| 43 | + float mel_low = HzToMel(0.0f); |
| 44 | + float mel_high = HzToMel(static_cast<float>(sample_rate) / 2.0f); |
| 45 | + |
| 46 | + // Compute mel center frequencies in Hz (num_mels + 2 points) |
| 47 | + std::vector<float> mel_f(num_mels + 2); |
| 48 | + for (int i = 0; i < num_mels + 2; ++i) { |
| 49 | + float m = mel_low + (mel_high - mel_low) * i / (num_mels + 1); |
| 50 | + mel_f[i] = MelToHz(m); |
| 51 | + } |
| 52 | + |
| 53 | + // Differences between consecutive mel center frequencies (Hz) |
| 54 | + std::vector<float> fdiff(num_mels + 1); |
| 55 | + for (int i = 0; i < num_mels + 1; ++i) { |
| 56 | + fdiff[i] = mel_f[i + 1] - mel_f[i]; |
| 57 | + } |
| 58 | + |
| 59 | + // FFT bin center frequencies in Hz |
| 60 | + std::vector<float> fft_freqs(num_bins); |
| 61 | + for (int k = 0; k < num_bins; ++k) { |
| 62 | + fft_freqs[k] = static_cast<float>(k) * sample_rate / fft_size; |
| 63 | + } |
| 64 | + |
| 65 | + // Build triangular filterbank with Slaney normalization (matches librosa exactly) |
| 66 | + std::vector<std::vector<float>> filterbank(num_mels, std::vector<float>(num_bins, 0.0f)); |
| 67 | + for (int m = 0; m < num_mels; ++m) { |
| 68 | + for (int k = 0; k < num_bins; ++k) { |
| 69 | + float lower = (fft_freqs[k] - mel_f[m]) / (fdiff[m] + 1e-10f); |
| 70 | + float upper = (mel_f[m + 2] - fft_freqs[k]) / (fdiff[m + 1] + 1e-10f); |
| 71 | + filterbank[m][k] = std::max(0.0f, std::min(lower, upper)); |
| 72 | + } |
| 73 | + // Slaney area normalization: 2 / bandwidth |
| 74 | + float enorm = 2.0f / (mel_f[m + 2] - mel_f[m] + 1e-10f); |
| 75 | + for (int k = 0; k < num_bins; ++k) { |
| 76 | + filterbank[m][k] *= enorm; |
| 77 | + } |
| 78 | + } |
| 79 | + return filterbank; |
| 80 | +} |
| 81 | + |
| 82 | +// ─── Window functions ─────────────────────────────────────────────────────── |
| 83 | + |
| 84 | +std::vector<float> HannWindowSymmetric(int win_length) { |
| 85 | + std::vector<float> window(win_length); |
| 86 | + for (int i = 0; i < win_length; ++i) { |
| 87 | + window[i] = 0.5f * (1.0f - std::cos(2.0f * static_cast<float>(M_PI) * i / (win_length - 1))); |
| 88 | + } |
| 89 | + return window; |
| 90 | +} |
| 91 | + |
| 92 | +std::vector<float> HannWindowPeriodic(int fft_size, int win_length) { |
| 93 | + std::vector<float> window(fft_size, 0.0f); |
| 94 | + int offset = (fft_size - win_length) / 2; |
| 95 | + for (int i = 0; i < win_length; ++i) { |
| 96 | + window[offset + i] = 0.5f * (1.0f - std::cos(2.0f * static_cast<float>(M_PI) * i / win_length)); |
| 97 | + } |
| 98 | + return window; |
| 99 | +} |
| 100 | + |
| 101 | +// ─── Single-frame DFT ────────────────────────────────────────────────────── |
| 102 | + |
| 103 | +void ComputeSTFTFrame(const float* frame, const float* window, int frame_len, |
| 104 | + int fft_size, std::vector<float>& magnitudes) { |
| 105 | + int num_bins = fft_size / 2 + 1; |
| 106 | + magnitudes.resize(num_bins); |
| 107 | + |
| 108 | + for (int k = 0; k < num_bins; ++k) { |
| 109 | + float real_sum = 0.0f, imag_sum = 0.0f; |
| 110 | + for (int n = 0; n < frame_len; ++n) { |
| 111 | + float val = frame[n] * window[n]; |
| 112 | + float angle = 2.0f * static_cast<float>(M_PI) * k * n / fft_size; |
| 113 | + real_sum += val * std::cos(angle); |
| 114 | + imag_sum -= val * std::sin(angle); |
| 115 | + } |
| 116 | + magnitudes[k] = real_sum * real_sum + imag_sum * imag_sum; |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +// ─── Batch (offline) log-mel extraction ───────────────────────────────────── |
| 121 | + |
| 122 | +std::vector<float> NemoComputeLogMelBatch(const float* audio, size_t num_samples, |
| 123 | + const NemoMelConfig& cfg, int& out_num_frames) { |
| 124 | + // Lazily-initialized statics are fine for batch mode (same config per process). |
| 125 | + // If you need thread-safety with multiple configs, pass the filterbank in explicitly. |
| 126 | + static auto mel_filters = CreateMelFilterbank(cfg.num_mels, cfg.fft_size, cfg.sample_rate); |
| 127 | + static auto window = HannWindowPeriodic(cfg.fft_size, cfg.win_length); |
| 128 | + |
| 129 | + int n = static_cast<int>(num_samples); |
| 130 | + |
| 131 | + // Apply pre-emphasis: y[n] = x[n] - preemph * x[n-1] |
| 132 | + std::vector<float> preemphasized(n); |
| 133 | + if (n > 0) { |
| 134 | + preemphasized[0] = audio[0]; // No previous sample for first sample |
| 135 | + for (int i = 1; i < n; ++i) { |
| 136 | + preemphasized[i] = audio[i] - cfg.preemph * audio[i - 1]; |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + // Center-pad both sides: fft_size/2 zeros on each side (matching torch.stft center=True) |
| 141 | + int pad = cfg.fft_size / 2; |
| 142 | + std::vector<float> padded(pad + n + pad, 0.0f); |
| 143 | + if (n > 0) { |
| 144 | + std::memcpy(padded.data() + pad, preemphasized.data(), n * sizeof(float)); |
| 145 | + } |
| 146 | + |
| 147 | + if (static_cast<int>(padded.size()) < cfg.fft_size) { |
| 148 | + padded.resize(cfg.fft_size, 0.0f); |
| 149 | + } |
| 150 | + |
| 151 | + // Frame count using fft_size as frame size (matching torch.stft) |
| 152 | + int num_frames = static_cast<int>((padded.size() - cfg.fft_size) / cfg.hop_length) + 1; |
| 153 | + out_num_frames = num_frames; |
| 154 | + |
| 155 | + int num_bins = cfg.fft_size / 2 + 1; |
| 156 | + std::vector<float> magnitudes; |
| 157 | + std::vector<float> mel_spec(cfg.num_mels * num_frames); |
| 158 | + |
| 159 | + for (int t = 0; t < num_frames; ++t) { |
| 160 | + const float* frame = padded.data() + t * cfg.hop_length; |
| 161 | + ComputeSTFTFrame(frame, window.data(), cfg.fft_size, cfg.fft_size, magnitudes); |
| 162 | + |
| 163 | + for (int m = 0; m < cfg.num_mels; ++m) { |
| 164 | + float val = 0.0f; |
| 165 | + for (int k = 0; k < num_bins; ++k) { |
| 166 | + val += mel_filters[m][k] * magnitudes[k]; |
| 167 | + } |
| 168 | + mel_spec[m * num_frames + t] = std::log(val + cfg.log_eps); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + return mel_spec; |
| 173 | +} |
| 174 | + |
| 175 | +// ─── Streaming log-mel extraction ─────────────────────────────────────────── |
| 176 | + |
| 177 | +NemoStreamingMelExtractor::NemoStreamingMelExtractor(const NemoMelConfig& cfg) |
| 178 | + : cfg_(cfg) { |
| 179 | + mel_filters_ = CreateMelFilterbank(cfg_.num_mels, cfg_.fft_size, cfg_.sample_rate); |
| 180 | + hann_window_ = HannWindowSymmetric(cfg_.win_length); |
| 181 | + audio_overlap_.assign(cfg_.fft_size / 2, 0.0f); |
| 182 | + preemph_last_sample_ = 0.0f; |
| 183 | +} |
| 184 | + |
| 185 | +void NemoStreamingMelExtractor::Reset() { |
| 186 | + audio_overlap_.assign(cfg_.fft_size / 2, 0.0f); |
| 187 | + preemph_last_sample_ = 0.0f; |
| 188 | +} |
| 189 | + |
| 190 | +std::pair<std::vector<float>, int> NemoStreamingMelExtractor::Process( |
| 191 | + const float* audio, size_t num_samples) { |
| 192 | + // Apply pre-emphasis filter: y[n] = x[n] - preemph * x[n-1] |
| 193 | + std::vector<float> preemphasized(num_samples); |
| 194 | + if (num_samples > 0) { |
| 195 | + preemphasized[0] = audio[0] - cfg_.preemph * preemph_last_sample_; |
| 196 | + for (size_t i = 1; i < num_samples; ++i) { |
| 197 | + preemphasized[i] = audio[i] - cfg_.preemph * audio[i - 1]; |
| 198 | + } |
| 199 | + preemph_last_sample_ = audio[num_samples - 1]; |
| 200 | + } |
| 201 | + |
| 202 | + // Left-only center pad for streaming: prepend overlap from previous chunk. |
| 203 | + // For the first chunk this is zeros (matching center=True left edge). |
| 204 | + int pad = cfg_.fft_size / 2; // 256 samples |
| 205 | + std::vector<float> padded(pad + num_samples); |
| 206 | + std::memcpy(padded.data(), audio_overlap_.data(), pad * sizeof(float)); |
| 207 | + std::memcpy(padded.data() + pad, preemphasized.data(), num_samples * sizeof(float)); |
| 208 | + |
| 209 | + // Update overlap buffer for next chunk |
| 210 | + if (num_samples >= static_cast<size_t>(pad)) { |
| 211 | + audio_overlap_.assign(preemphasized.data() + num_samples - pad, |
| 212 | + preemphasized.data() + num_samples); |
| 213 | + } else { |
| 214 | + size_t keep = pad - num_samples; |
| 215 | + std::vector<float> new_overlap(pad, 0.0f); |
| 216 | + std::memcpy(new_overlap.data(), audio_overlap_.data() + num_samples, keep * sizeof(float)); |
| 217 | + std::memcpy(new_overlap.data() + keep, preemphasized.data(), num_samples * sizeof(float)); |
| 218 | + audio_overlap_ = std::move(new_overlap); |
| 219 | + } |
| 220 | + |
| 221 | + // Window centering offset (symmetric window smaller than fft_size) |
| 222 | + int win_offset = (cfg_.fft_size - cfg_.win_length) / 2; // e.g. 56 |
| 223 | + |
| 224 | + // Right-pad to accommodate the window offset for the last frame |
| 225 | + padded.resize(padded.size() + win_offset, 0.0f); |
| 226 | + |
| 227 | + if (static_cast<int>(padded.size()) < win_offset + cfg_.win_length) { |
| 228 | + padded.resize(win_offset + cfg_.win_length, 0.0f); |
| 229 | + } |
| 230 | + |
| 231 | + // Frame count |
| 232 | + int num_frames = static_cast<int>((padded.size() - win_offset - cfg_.win_length) / cfg_.hop_length) + 1; |
| 233 | + |
| 234 | + int num_bins = cfg_.fft_size / 2 + 1; |
| 235 | + std::vector<float> mel_spec(cfg_.num_mels * num_frames); |
| 236 | + |
| 237 | + for (int t = 0; t < num_frames; ++t) { |
| 238 | + const float* frame = padded.data() + t * cfg_.hop_length + win_offset; |
| 239 | + |
| 240 | + // Inline DFT with symmetric Hann window (win_length samples) |
| 241 | + std::vector<float> magnitudes(num_bins); |
| 242 | + for (int k = 0; k < num_bins; ++k) { |
| 243 | + float real_sum = 0.0f, imag_sum = 0.0f; |
| 244 | + for (int n = 0; n < cfg_.win_length; ++n) { |
| 245 | + float val = frame[n] * hann_window_[n]; |
| 246 | + float angle = 2.0f * static_cast<float>(M_PI) * k * n / cfg_.fft_size; |
| 247 | + real_sum += val * std::cos(angle); |
| 248 | + imag_sum -= val * std::sin(angle); |
| 249 | + } |
| 250 | + magnitudes[k] = real_sum * real_sum + imag_sum * imag_sum; |
| 251 | + } |
| 252 | + |
| 253 | + // Apply mel filterbank + log |
| 254 | + for (int m = 0; m < cfg_.num_mels; ++m) { |
| 255 | + float val = 0.0f; |
| 256 | + for (int k = 0; k < num_bins; ++k) { |
| 257 | + val += mel_filters_[m][k] * magnitudes[k]; |
| 258 | + } |
| 259 | + mel_spec[m * num_frames + t] = std::log(val + cfg_.log_eps); |
| 260 | + } |
| 261 | + } |
| 262 | + |
| 263 | + return {mel_spec, num_frames}; |
| 264 | +} |
| 265 | + |
| 266 | +} // namespace nemo_mel |
0 commit comments