Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/lib/audio/mel-math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,19 @@ export function melToHz(mel: number): number {
: mel * F_SP;
}

const _melFilterbankCache = new Map<number, Float32Array>();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The _melFilterbankCache is unbounded, which could lead to excessive memory usage if createMelFilterbank is called with many different nMels values. While the number of distinct nMels is likely small in this application, it's a good practice to cap the cache size to prevent potential memory leaks.

A simple eviction strategy could be added after a new entry is cached. For example:

const MAX_CACHE_SIZE = 10; // ... inside createMelFilterbank, after caching a new value: if (_melFilterbankCache.size > MAX_CACHE_SIZE) { // Evict the oldest entry, since Map preserves insertion order. const oldestKey = _melFilterbankCache.keys().next().value; _melFilterbankCache.delete(oldestKey); }

/**
* Create mel filterbank matrix [nMels × N_FREQ_BINS] with Slaney normalization.
* Returns a flat Float32Array in row-major order.
* Results are cached per nMels to avoid recomputation.
*/
export function createMelFilterbank(nMels: number): Float32Array {
const cached = _melFilterbankCache.get(nMels);
if (cached) {
return new Float32Array(cached);
}

const { SAMPLE_RATE, N_FREQ_BINS } = MEL_CONSTANTS;
const fMax = SAMPLE_RATE / 2; // 8000

Expand Down Expand Up @@ -89,7 +97,9 @@ export function createMelFilterbank(nMels: number): Float32Array {
fb[fbOffset + k] = Math.max(0, Math.min(downSlope, upSlope)) * enorm;
}
}
return fb;

_melFilterbankCache.set(nMels, fb);
return new Float32Array(fb);
}

/**
Expand Down