r/cpp • • May 25 '26

Optimizing a real-time C++17 terminal audio visualizer, what am I missing?

I've been building spectrum, a terminal audio visualizer that hooks into WASAPI and runs FFT analysis via FFTW3. Took heavy inspiration from Winamp's spectral analyzer for the peak physics and decay behavior.

Current pipeline:
- 2400-sample Hann-windowed FFT with 95% window overlap (120-sample hop at 48kHz)
- Producer-consumer architecture, mutex-guarded shared buffers between capture and render thread
- AGC with rolling normalization + gamma contrast for dynamic range
- Logarithmic frequency binning (20Hz–16kHz) with perceptual tilt

It runs at 60 FPS with <5% CPU.

What would you optimize next?
I'm hitting a point of diminishing returns (especially with the bar height logic, and what frequencies should and should not be displayed) and would love some architectural feedback.

Considering:
- Lock-free ring buffer to replace the mutex
- WASAPI exclusive mode for lower latency capture

GitHub: github.com/majockbim/spectrum

18 Upvotes

13 comments sorted by

View all comments

Show parent comment

2

u/Jolly-Addendum-7199 May 25 '26

Your comment on log10() calls is spot on, each of the 1201 FFT bins goes through a log conversion even though not all of them map to UI bars.

I guess I can shift the dB conversions out of the FFT loop and into the render thread logic

4

u/SkoomaDentist Antimodern C++, Embedded, Audio May 25 '26 edited May 25 '26

You can basically completely eliminate the cost of the log calls by using a bit of common sense and realizing that you don't need particularly accurate decibel scale.

Taking that into account, you can write a really_fast_db(float X) that calculates (exponent(x) + mantissa(x)*mscale + bias) * 6.02, where mscale should be so that the mantissa ranges from 0.00f to 0.99..f and bias so that exponent(1.0f) + bias = 0.