Skip to content

Commit df2e7ee

Browse files
committed
Support Nemo Mel Spectrogram
1 parent 087953c commit df2e7ee

File tree

4 files changed

+703
-0
lines changed

4 files changed

+703
-0
lines changed

CMakeLists.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,13 @@ target_compile_definitions(ocos_operators PRIVATE ${OCOS_COMPILE_DEFINITIONS})
777777
target_link_libraries(ocos_operators PRIVATE ${ocos_libraries})
778778

779779
file(GLOB _TARGET_LIB_SRC "shared/lib/*.cc")
780+
781+
# NeMo mel spectrogram is standalone (no ORT/C API deps) — always compile when audio is enabled
782+
if(OCOS_ENABLE_AUDIO)
783+
file(GLOB nemo_mel_SRC "shared/api/nemo_mel_*")
784+
list(APPEND _TARGET_LIB_SRC ${nemo_mel_SRC})
785+
endif()
786+
780787
if(OCOS_ENABLE_C_API)
781788
file(GLOB utils_TARGET_SRC "shared/api/c_api_utils.*" "shared/api/runner.hpp")
782789
list(APPEND _TARGET_LIB_SRC ${utils_TARGET_SRC})
@@ -874,6 +881,7 @@ endif()
874881
target_compile_definitions(ortcustomops PUBLIC ${OCOS_COMPILE_DEFINITIONS})
875882
target_include_directories(ortcustomops PUBLIC "$<TARGET_PROPERTY:noexcep_operators,INTERFACE_INCLUDE_DIRECTORIES>")
876883
target_include_directories(ortcustomops PUBLIC "$<TARGET_PROPERTY:ocos_operators,INTERFACE_INCLUDE_DIRECTORIES>")
884+
target_include_directories(ortcustomops PUBLIC "${PROJECT_SOURCE_DIR}/shared/api")
877885

878886
target_link_libraries(ortcustomops PUBLIC ocos_operators)
879887

shared/api/nemo_mel_spectrogram.cc

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
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

shared/api/nemo_mel_spectrogram.h

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
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+
// Designed to be portable across repos.
7+
8+
#pragma once
9+
10+
#include <cstddef>
11+
#include <utility>
12+
#include <vector>
13+
14+
namespace nemo_mel {
15+
16+
// ─── Configuration ──────────────────────────────────────────────────────────
17+
18+
struct NemoMelConfig {
19+
int num_mels;
20+
int fft_size;
21+
int hop_length;
22+
int win_length;
23+
int sample_rate;
24+
float preemph;
25+
float log_eps;
26+
};
27+
28+
// ─── Mel scale conversions (Slaney) ────────────────────────────────────────
29+
30+
float HzToMel(float hz);
31+
float MelToHz(float mel);
32+
33+
// ─── Filterbank creation ────────────────────────────────────────────────────
34+
35+
/// Build a triangular mel filterbank with Slaney normalization (matches librosa).
36+
/// Returns shape [num_mels][num_bins] where num_bins = fft_size/2 + 1.
37+
std::vector<std::vector<float>> CreateMelFilterbank(int num_mels, int fft_size, int sample_rate);
38+
39+
// ─── Window functions ───────────────────────────────────────────────────────
40+
41+
/// Symmetric Hann window of length win_length (periodic=False).
42+
/// Matches torch.hann_window(win_length, periodic=False).
43+
std::vector<float> HannWindowSymmetric(int win_length);
44+
45+
/// Periodic Hann window of length win_length centered in an fft_size frame.
46+
/// Matches torch.stft behavior: window placed at offset (fft_size - win_length) / 2.
47+
/// Returns a vector of fft_size elements (zero-padded outside the window).
48+
std::vector<float> HannWindowPeriodic(int fft_size, int win_length);
49+
50+
// ─── Single-frame DFT ──────────────────────────────────────────────────────
51+
52+
/// Compute |DFT|^2 (power spectrum) for a single windowed frame.
53+
/// frame: pointer to fft_size samples (or win_length samples with window applied).
54+
/// window: pointer to window coefficients (same length as frame_len).
55+
/// frame_len: number of samples to read from frame and window.
56+
/// fft_size: DFT size (output has fft_size/2 + 1 bins).
57+
/// magnitudes: output power spectrum (resized to fft_size/2 + 1).
58+
void ComputeSTFTFrame(const float* frame, const float* window, int frame_len,
59+
int fft_size, std::vector<float>& magnitudes);
60+
61+
// ─── Batch (offline) log-mel extraction ─────────────────────────────────────
62+
63+
/// Compute NeMo-compatible log-mel spectrogram for a complete audio buffer.
64+
/// Applies pre-emphasis, center-pads both sides (fft_size/2 zeros), computes STFT
65+
/// with a periodic Hann window, applies mel filterbank, and takes log(mel + eps).
66+
///
67+
/// Output layout: row-major [num_mels, num_frames].
68+
/// out_num_frames is set to the number of time frames produced.
69+
std::vector<float> NemoComputeLogMelBatch(const float* audio, size_t num_samples,
70+
const NemoMelConfig& cfg, int& out_num_frames);
71+
72+
// ─── Streaming log-mel extraction ───────────────────────────────────────────
73+
74+
/// Stateful streaming NeMo-compatible mel extractor that maintains overlap and
75+
/// pre-emphasis state across successive audio chunks.
76+
///
77+
/// Usage:
78+
/// nemo_mel::NemoStreamingMelExtractor extractor(cfg);
79+
/// auto [mel, frames] = extractor.Process(chunk1, n1);
80+
/// auto [mel2, frames2] = extractor.Process(chunk2, n2);
81+
/// extractor.Reset(); // new utterance
82+
///
83+
class NemoStreamingMelExtractor {
84+
public:
85+
explicit NemoStreamingMelExtractor(const NemoMelConfig& cfg);
86+
87+
/// Process one chunk of raw PCM audio (mono, float32).
88+
/// Returns (mel_data, num_frames) where mel_data is row-major [num_mels, num_frames].
89+
std::pair<std::vector<float>, int> Process(const float* audio, size_t num_samples);
90+
91+
/// Reset all streaming state for a new utterance.
92+
void Reset();
93+
94+
const NemoMelConfig& config() const { return cfg_; }
95+
96+
private:
97+
NemoMelConfig cfg_;
98+
std::vector<std::vector<float>> mel_filters_;
99+
std::vector<float> hann_window_; // symmetric, length = win_length
100+
101+
// Streaming state
102+
std::vector<float> audio_overlap_; // last fft_size/2 pre-emphasized samples
103+
float preemph_last_sample_{0.0f};
104+
};
105+
106+
} // namespace nemo_mel

0 commit comments

Comments
 (0)