Table of Contents
Introduction
OpenMeters is my native audio metering application for Linux, consisting of a spectrogram, spectrum analyzer, oscilloscope, waveform display, stereometer/Lissajous display, and loudness meter.
Beginnings
Local development started around September 20th, 2025, two weeks after the death of my best friend. I needed a distraction and, as I have so many times before, I turned to my computer and the internet.
The first prototype was C with OpenGL, GLFW, and ALSA. In a couple of days I put together a crude but working spectrum analyzer that captured from the default input device. Before this, most of my work had been low-level C programming, where I had to write the utilities I needed myself. For a user-facing application my workflow was painfully inefficient. The architecture was horrific. After a few days I wiped it from my mind and hard drive, but I hadn't given up on the concept.
The second prototype used C++ and Qt, which was only marginally less painful. CMake and Conan were a step above manually vendoring, mostly out of habit and ideology, the libraries I needed. It was not torture, but it was not fun either. After about three days I had a working loudness meter. My PipeWire routing was also a mess. I naively shuffled, created, deleted, and connected nodes without much of a plan. That prototype died too, but at least it died usefully; I kept it around as a reference.
The third prototype became OpenMeters as it exists today, though I can guarantee not a single line has survived unaltered. I moved to Rust, eventually dropped the Qt bindings, and built the application around a native renderer. The project never stopped being a collection of experiments, but it became one I actually wanted to use. That is the standard. If I will not use it, I have no business asking anyone else to.
Spectrogram
The spectrogram starts with a short-time Fourier transform: multiply a frame of audio by a window and compute its discrete Fourier transform (DFT). Each complex coefficient gives the magnitude and phase for one frequency bin. A fast Fourier transform (FFT) computes the DFT efficiently. Repeating this every samples produces the spectrogram's columns:
Here identifies the frame, the frequency bin, and the frame's input after preprocessing. The window contains samples; is the FFT length, including any zero-padding. At sample rate , columns are seconds apart and bins are Hz apart.
OpenMeters defaults to a 4096-sample Hann window with a 256-sample hop and no zero-padding. At 48 kHz, each window covers about 85.3 ms, but a new column arrives every 5.33 ms. Bins are about 11.72 Hz apart.
Windowing spreads a sinusoid's energy across FFT bins. How much lands in each bin depends on the window and the tone's alignment with the FFT grid.
Reassignment
Reassignment uses phase derivatives to estimate the time-frequency coordinate of the energy in each bin. The method dates back to Kodera, Gendrin, and de Villedary,[1] was made practical by Auger and Flandrin,[2] and is surveyed by Auger et al.[3]
OpenMeters computes three spectra from the same input:
- , using the ordinary window .
- , using the window's derivative with respect to sample index.
- , using the time-weighted window , where is the window's weighted center.
Their ratios give a frequency estimate and a time displacement from that center:[4][5]
The frequency correction converts radians per sample to Hz. The time-weighted spectrum's ratio to already gives a displacement in samples. With the default Hann window, neighboring bins of an isolated steady tone should move toward the tone's frequency, while the time displacement stays near zero.
Before the three windowed FFTs, an FFT-based Hilbert pass transforms the real input, zeros its DC and negative-frequency bins, then inverse-transforms it. Near DC, the positive- and negative-frequency lobes of a windowed signal can overlap and bias the reassignment ratios. Removing the negative-frequency image reduces that interference.
The pass reads a longer block of actual audio and keeps its central samples. The FFT treats the block as periodically repeated; negative frequencies are removed on that block's DFT grid, not by taking the ideal Hilbert transform of an indefinitely long stream. Central cropping reduces circular-boundary artifacts but does not eliminate them.
This requires samples of additional lookahead relative to classic analysis. The renderer therefore stores
in columns rather than seconds. Correcting the coordinate does not remove the delay, and does not include the ordinary analysis window's latency.
Writing and , complex division becomes . In this shortened loop from the spectrogram
processor, bin_norm supplies the level calibration described in the
next section, and latency_samples is :
let bin_hz = sample_rate / fft_size as f32;
let radians_to_hz = sample_rate / core::f32::consts::TAU;
for i in 0..bin_count {
let base = spectrum[i];
let pow = base.re * base.re + base.im * base.im;
let power = pow * bin_norm[i];
if power < 1e-14 {
continue;
}
let d = derivative_spectrum[i];
let t = time_weighted_spectrum[i];
let inv_pow = 1.0 / pow;
let d_omega = -(d.im * base.re - d.re * base.im) * inv_pow;
let freq_hz = i as f32 * bin_hz + d_omega * radians_to_hz;
if !(freq_hz > 0.0 && freq_hz < sample_rate * 0.5) {
continue;
}
let time_samples = (t.re * base.re + t.im * base.im) * inv_pow;
points.push(SpectrogramPoint {
time_offset: (time_samples - latency_samples as f32) / hop_size as f32,
freq_hz,
power,
});
}Near a spectral zero these ratios mostly relocate numerical noise. Bins below or with frequencies outside are skipped.
This loop used to have hand-written eight-lane SIMD. A painful weekend of profiling showed it was 2-20 microseconds slower than scalar Rust compiled with native CPU features, so the SIMD went away.
A conventional analytic signal is : it doubles positive-frequency amplitudes and removes negative frequencies. OpenMeters leaves positive bins and Nyquist unchanged. Away from DC and Nyquist, its normalized result is half the conventional analytic signal for that periodic extension. RustFFT leaves the inverse transform unnormalized; the level calibration below accounts for its scale.
The Hilbert FFT length and lookahead come from:
let hilbert_len = (2 * window_size).next_power_of_two();
let latency_samples = (hilbert_len - window_size) / 2;This is surrounding audio, not analysis zero-padding. Classic mode skips this transform pair: it subtracts the block mean, applies the window, and takes a real FFT.
The time-weighted window uses
For the periodic Hann window, . The derivative window is computed spectrally:
Here is the signed DFT frequency in radians per sample, and the inverse DFT includes its normalization. DC and the even-length Nyquist coefficient are zeroed to keep the derivative real. Both auxiliary windows are built only when the analysis configuration changes.
This differentiates the window's periodic trigonometric interpolant, which works especially well with tapers such as Hann, whose underlying continuous window vanishes at the interval boundaries. For a rectangular window, , so frequency reassignment leaves every bin on the FFT grid; only time can be reassigned. With nonzero-endpoint tapers such as Hamming, periodic differentiation omits the boundary contributions of the zero-extended window and can bias frequency estimates.
The phase identity behind the ratios is
With the negative-exponent FFT above, an isolated Hann-windowed tone at gives , where . Subtracting the correction moves toward the tone. Likewise, , where the frequency derivative is taken on the continuous-frequency transform sampled by the FFT. Removing turns an index within the window into a displacement. Window orientation matters when comparing signs with another implementation.
Gardner and Magnasco's paper on sparse time-frequency representations is a good companion here.[6]
Windows and Amplitude
I considered configurable Gaussian, Kaiser, and Planck-Bessel windows (Planck-Bessel used to be the default), but they weren't worth the hassle. The user can choose rectangular, Hann, Hamming, Blackman, or Blackman-Harris. The cosine windows are periodic, using rather than in their phase denominator.
Let . Classic mode calibrates each bin as
Here for ordinary positive-frequency bins and for DC and Nyquist, when present. Four is the squared one-sided amplitude correction. An isolated, bin-centered sinusoid of unit peak amplitude should read approximately 0 dB, provided it is well separated from DC and Nyquist and block-mean subtraction has negligible effect. Near those boundaries, positive- and negative-frequency window lobes can overlap even for a bin-centered tone. The reference is squared amplitude, not power spectral density per Hz.
The reassigned path also divides by , where is the Hilbert FFT length, to cancel its unnormalized inverse. Because the positive bins were not doubled in that pass, the factor of four is still needed. This common scale cancels from the coordinate ratios, but not from the levels.
Several reassigned bins can land on the same pixel. To avoid counting window spread or zero-padding as extra level, the renderer multiplies their accumulated power by
For an unpadded Hann window, ; doubling the FFT length halves . This equivalent-noise-bandwidth correction includes zero-padding and keeps an isolated tone's accumulated level approximately stable across those settings when its relevant bins land on one pixel. It cannot recover power lost to thresholding or the DC and Nyquist boundaries. Nor are arbitrary reassigned pixel values calibrated measurements of power spectral density or instantaneous power.
Frequency Axes
I wanted axis changes to remap the entire history. Reassigned points stay in Hz, and classic bins stay as indices until the renderer maps them to the selected scale.
ERB-rate is based on the equivalent rectangular bandwidths of auditory filters, whereas Mel describes perceptual pitch scaling. I chose ERB-rate because auditory frequency selectivity is the more relevant model for this display.
The ERB-rate axis uses the Glasberg and Moore curve , for in Hz.[7] The logarithmic mode uses instead of : nearly linear near zero, nearly logarithmic higher up, and finite at DC.
The inverse mapping from normalized position to Hz is:
The display starts at 1 Hz. Reassignment can estimate frequencies below the FFT-bin spacing, but very-low-frequency estimates remain sensitive to block and window duration, signal conditions, and finite-block Hilbert artifacts. Sub-bin localization does not guarantee that nearby components can be resolved; overlapping components can interfere with the reassignment estimates.
Zoom, pan, rotation, tilt, piano-roll overlay, and the frequency/note/time crosshair are view operations only.
Storage and Rendering
Reassigned mode stores sparse points:
#[repr(C)]
pub struct SpectrogramPoint {
pub time_offset: f32,
pub freq_hz: f32,
pub power: f32,
}Each is a 12-byte GPU record. Columns live in a ring buffer, with a point count for each slot. Empty columns advance the history without a point upload or draw.
Overlapping points accumulate in linear power before conversion to dB. With spectral tilt disabled, a pixel covered by points gets
Pixels with zero accumulated power stay transparent. An empty source column does not necessarily leave a blank strip: points from other columns can land there through time reassignment.
The renderer first draws small quads into a linear-power accumulation texture. A separate shader pass applies , converts to dB, and maps the result to the palette. Thus changing the palette or display floor needs only that final pass. New audio, a different frequency axis, or spectral tilt changes the accumulation itself, so it must be redrawn. Tilt adjusts power by frequency before summing, relative to 1 kHz.
In classic mode, time and frequency are implicit in the ring slot and bin index, so it stores only packed 16-bit dB values. Its shader interpolates between frequency bins, but not time columns.
A single dense column can make a uniformly sized point ring wasteful.
The ring can therefore split into pages of up to 64 columns, each
sized to its largest live column. If the savings do not justify the
extra bindings, it stays in one buffer. Pages grow as needed and
shrink when sufficiently overallocated, preserving history with
GPU-to-GPU copy_buffer_to_buffer rather than a CPU round trip.
The accumulation target is Rg16Float. One half-float channel cannot
represent the full analysis range, so the shader stores both and
. The resolve pass divides the scaled channel back down for
faint values, falling back to the ordinary channel when the scaled one
saturates. This extends the usable range, not the precision of
half-float addition.
Classic magnitudes cover a fixed -144 to +12 dB range, independently of the live display floor:
fn pack_db(db: f32) -> u16 {
((db + 144.0) * (65535.0 / 156.0))
.round()
.clamp(0.0, 65535.0) as u16
}That gives steps of about 0.00238 dB. The shader reads array<u32>
and uses unpack2x16unorm, recovering two magnitudes per word. Column
strides are rounded to an even number of u16s to keep pairs aligned.
At the default 4096-point FFT, 2049 bins cost 4100 bytes per classic column, versus at most 24,588 bytes of reassigned point records. Sparse pages often use much less. Retention is limited by the view's time-axis extent, an 8192-column cap, and payload budgets of 128 MiB for classic or 256 MiB for reassigned storage. The budget calculation assumes full columns; textures and index buffers are additional.
Spectrum analyzer
The spectrum analyzer shows the current frequency balance rather than its history. Its real-FFT processor handles primary and secondary sources independently, selected from left, right, mid, side, or none.
Averaging and peak hold operate in power, updating on each audio hop. After initialization, exponential averaging retains a fraction of the previous value:
Larger makes a steadier but slower trace. For , empty state starts at the incoming power rather than fading up from silence:
for (avg, &power) in averaged_power.iter_mut().zip(&frame_power) {
*avg = if *avg <= 0.0 {
power
} else {
*avg * alpha + power * (1.0 - alpha)
};
if *avg < state_floor {
*avg = 0.0;
}
}Peak hold instead decays the old value by dB per second and takes the maximum with the incoming power. With , that is
With no new signal, a 12 dB/s decay leaves about 6.3% of the stored power after one second.
Each trace keeps raw and A-weighted levels. A-weighting attenuates low frequencies relative to 1 kHz. The selected power is converted to dB, the weighting is added, and the result is clamped to the display floor:
let db = 10.0 * power.log10();
raw_out[i] = db.max(floor_db);
weighted_out[i] = (db + a_weighting_db[i]).max(floor_db);The smoothing state_floor accounts for the positive part of the
A-weighting curve: a bin below the raw display floor might still be
visible after weighting. Once neither output can show it, the
smoothing state can return to zero.
OpenMeters follows the IEC 61672-1 reference curve. With in Hz,
The corner frequencies are , , , and Hz. The +2 dB term makes the response approximately 0 dB at 1 kHz; DC contributes nothing. These per-bin offsets are prepared when the frequency grid changes.
The spectrum can be drawn as lines[8] or bars. Bar mode takes the maximum level within each bar's frequency range. The peak label fits a parabola through the loudest visible bin's dB level and those of its two neighbors on the linear FFT-frequency grid to estimate frequency and level between bin centers. If the neighbors are not finite or the fit is not concave, the label stays at the bin center.
Oscilloscope
If the oscilloscope shows the newest 20 ms of audio, a periodic waveform drifts unless each capture starts at the same phase.
There are two display channels, selectable from left, right, mid, side, or none, with a shared or channel-dependent trigger. Zero-crossing mode finds recent rising crossings and displays the selected segment between them. The stable trigger estimates the period, then aligns successive captures by phase.
Finding the period
The old stable trigger used YIN and sine/cosine prefix sums. It degraded or failed on many acoustic and atonal signals. Its replacement subtracts the mean from recent audio and compares the resulting probe , of length , with delayed copies of itself:
Here is the delay in samples, and the two terms are the sums of squared samples in the overlapping segments. This is the normalized square difference function (NSDF) used in McLeod and Wyvill's pitch method.[9] It is near one when the segments repeat closely. For a nonzero denominator, it can also be written as
A likely period appears as a peak after the initial lobe around zero delay.
Autocorrelation comes from an inverse FFT of squared FFT magnitudes, with enough zero-padding to avoid circular wraparound at the searched delays. After normalizing that inverse FFT, the score calculation uses cumulative energy:
The two segment energies follow from these prefix sums:
Neither segment needs to be summed again for each delay. If both segments have zero energy, the score is zero.
The estimator searches periods corresponding to 20 Hz through 8 kHz, chooses the first strong peak close to the best candidate's score, refines it parabolically, and smooths nearby estimates.
Holding the phase
To align captures by phase, the trigger combines a Gaussian-weighted rising-edge kernel with a retained waveform reference, then scores candidate offsets against this template using mean-centered, normalized correlation. Mean-centering and normalization keep DC offset and amplitude from deciding the match.
For template and candidate offset , the score is
The overlines denote segment means. Advancing the candidate window by one sample updates its sum and sum of squares by subtracting the outgoing sample's contribution and adding the incoming sample's. After initialization, these rolling statistics give the mean and centered energy in O(1) work per offset. Each correlation score still requires a dot product with the template. A near-zero denominator yields zero to avoid amplifying noise.
The search runs right-to-left to favor recent audio, first coarsely and then around the best candidate, with a fractional offset from parabolic interpolation. The reference is resampled when the period changes by at least one semitone relative to the reference, or when the template length changes. It is updated only on confident detection and discarded when the match becomes poor.
The cycle slider selects one to four periods; higher values can be set
in OpenMeters' settings.json.
Stable mode falls back to the configured duration when no usable period remains or the buffer cannot supply the capture and matching window. Period estimation fails if the mean-removed probe's absolute peak is below , the probe is too short for the lag search, or no NSDF peak reaches 0.5 after the initial positive lobe within the search range. A retained period can bridge four consecutive missed estimates; the fifth unlocks the trigger. Quiet input unlocks immediately. A poor template match instead resets the reference and retries phase alignment.
The capture is resampled via linear interpolation to at most 4096 points per channel and drawn as a line.[8] Optional persistence blends snapshots only when their capture epoch, channel slots, and sample counts agree.
Conclusion
OpenMeters is fast, open source, runs on my Linux desktop, and has already taught me more than any prior project. I never expected it to get more than 5 stars on GitHub, and I never expected people to actually use what I made. I am proud of what this has become.
Footnotes
-
K. Kodera, R. Gendrin, and C. de Villedary, "Analysis of time-varying signals with small BT values," IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 26, no. 1, pp. 64-76, 1978. ↩
-
F. Auger and P. Flandrin, "Improving the readability of time-frequency and time-scale representations by the reassignment method," IEEE Transactions on Signal Processing, vol. 43, no. 5, pp. 1068-1089, 1995. ↩
-
F. Auger et al., "Time-Frequency Reassignment and Synchrosqueezing: An Overview," IEEE Signal Processing Magazine, vol. 30, no. 6, pp. 32-41, 2013. ↩
-
K. R. Fitz and S. A. Fulop, "A Unified Theory of Time-Frequency Reassignment," arXiv:0903.3080, 2009. ↩
-
S. A. Fulop and K. Fitz, "Algorithms for computing the time-corrected instantaneous frequency (reassigned) spectrogram, with applications," Journal of the Acoustical Society of America, vol. 119, no. 1, pp. 360-371, 2006. ↩
-
T. J. Gardner and M. O. Magnasco, "Sparse time-frequency representations," Proceedings of the National Academy of Sciences, vol. 103, no. 16, pp. 6094-6099, 2006. ↩
-
B. R. Glasberg and B. C. J. Moore, "Derivation of auditory filter shapes from notched-noise data," Hearing Research, vol. 47, nos. 1-2, pp. 103-138, 1990. ↩
-
Several visuals share a line-rendering helper that decimates geometry according to display resolution while preserving local extrema. ↩ ↩2
-
P. McLeod and G. Wyvill, "A Smarter Way to Find Pitch," Proceedings of the International Computer Music Conference, Barcelona, Spain, pp. 138-141, 2005. ↩