6. The FFT and the Spectrogram

PySDR’s Frequency Domain chapter is the one most readers come back to: np.fft.fft, fftshift, a frequency axis, a window, and finally a spectrogram, a stack of FFTs. Each of those steps is one NumPy call, and each of them hides a decision that a C++ implementation has to make explicitly: where the shifted spectrum lives, how the frequency axis is computed, which window and with which normalization, who owns the FFT plan, and how the rows of a spectrogram are laid out in memory. This chapter follows PySDR’s sections in order and makes those decisions, with GNU Radio’s gr-fft as the reference implementation.

The code is in code/include/cppsdr/spectrum.hpp (with the FFTW wrappers in fftw.hpp); code/tests/test_spectrum.cpp checks it against PySDR’s own code, run by figure-generating-scripts/spectrum_reference.py.

fftshift Is a Rotation

PySDR explains the FFT’s output order and then fixes it with np.fft.fftshift, “kind of like a circular shift but more of a ‘put this here and that there’”. In C++ that operation has a name, and it is in <algorithm>:

template <std::ranges::random_access_range R>
constexpr void fftshift(R&& r)
{
    const auto n = std::ranges::size(r);
    std::ranges::rotate(r, std::ranges::begin(r) + (n + 1) / 2);
}

std::rotate(first, middle, last) makes middle the new first element. For an even \(N\) the middle is \(N/2\) and the two halves swap. For an odd \(N\) the definition matters: NumPy puts the zero-frequency bin at index \(\lfloor N/2 \rfloor\), so the element that must come first is the one at \(\lceil N/2 \rceil = (N+1)/2\), and the inverse, ifftshift, rotates by \(\lfloor N/2 \rfloor\) instead. GNU Radio’s fft_v block makes the same distinction (“round up” for the forward shift, “round down” for the inverse, in gr-fft/lib/fft_v_fftw.cc). The test checks both functions against NumPy’s definition for every \(N\) from 1 to 9.

The frequency axis deserves the same care. PySDR writes f = np.arange(Fs/-2, Fs/2, Fs/N), which is fine for its \(N = 100\), but np.arange with a floating-point step accumulates rounding error, and for some sizes it returns \(N+1\) values instead of \(N\) (with \(F_s = 1\), this happens for \(N = 49, 98, 103, \ldots\), 328 sizes below 5000). The FFT Implementation section uses np.linspace(sample_rate/-2, sample_rate/2, N), which always has \(N\) points but spaces them \(F_s/(N-1)\) apart instead of \(F_s/N\), so the labels drift by up to one bin toward the right edge (the 200 kHz tone in that example is labeled 200.88 kHz instead of 200.20 kHz). Neither problem can happen if every frequency is computed from its integer index:

constexpr double bin_frequency(std::size_t j, std::size_t n, double fs)
{
    return (double(j) - double(n / 2)) * fs / double(n);   // index j of the shifted spectrum
}

This is NumPy’s np.fft.fftfreq followed by a shift, and the test checks that it is.

Windows as Compile-Time Objects

PySDR’s advice on windows is “just stick with a Hamming window” and not to worry about the choice, because any taper is far better than none. The figure at the end of this section confirms it. In code, though, a window comes with two decisions that the advice does not cover.

The first is symmetry. np.hamming(N) and GNU Radio’s gr::fft::window::hamming(N) are symmetric: they divide by \(N-1\), so the last sample equals the first. That is the right shape for designing a linear-phase FIR filter. For spectral analysis, Harris showed in his classic paper (F. J. Harris, “On the Use of Windows for Harmonic Analysis with the Discrete Fourier Transform”, Proc. IEEE, 1978) that the window should be periodic (“DFT-even”): divide by \(N\), so that the window is exactly one period of a periodic sequence and its last sample is the one before the first. scipy.signal.get_window returns the periodic form by default. The difference is small for large \(N\), but it is a real difference, and a library should make the caller choose.

The second is normalization. A window reduces the amplitude of a tone by its coherent gain \(\frac{1}{N}\sum w[n]\), and it widens each bin for noise to an equivalent noise bandwidth of \(N \sum w^2 / (\sum w)^2\) bins. Every calibrated spectrum display needs these numbers: GNU Radio’s logpwrfft subtracts 10*log10(window_power/fft_size) for exactly this reason.

Both decisions are fixed when the window is chosen, so the window can be a type that carries its own numbers. All classic windows are sums of cosines, and since C++20 a small struct can be a template parameter:

struct cosine_sum { double a0, a1 = 0, a2 = 0, a3 = 0; };
inline constexpr cosine_sum hann{0.5, 0.5};
inline constexpr cosine_sum hamming{0.54, 0.46};
inline constexpr cosine_sum blackman_harris{0.35875, 0.48829, 0.14128, 0.01168};

template <cosine_sum Shape, std::size_t N, symmetry Sym = symmetry::periodic>
struct window {
    static constexpr std::array<float, N> taps = make();
    static constexpr double coherent_gain = sum() / N;
    static constexpr double enbw_bins = N * sum_sq() / (sum() * sum());
};

using W = window<hann, 1024>;     // taps, gain and ENBW exist before main() runs

The constants are computed by the compiler, so they can be checked by the compiler. The test states Harris’s table as static_asserts, an ENBW of 1.5 bins for Hann, 1.36 for Hamming, 1.73 for Blackman, 2.00 for the 4-term Blackman-Harris, and goes one step further: it checks the highest sidelobe of each window, which needs an FFT. That FFT runs inside the compiler too (the next section shows how):

static_assert(near(highest_sidelobe_db<window<rectangular, 64>>(), -13.26, 0.2));
static_assert(near(highest_sidelobe_db<window<hann, 64>>(), -31.47, 0.2));
static_assert(near(highest_sidelobe_db<window<hamming, 64>>(), -42.5, 0.4));
static_assert(near(highest_sidelobe_db<window<blackman_harris, 64>>(), -92.0, 0.5));

highest_sidelobe_db zero-pads the 64-point window to 512 points, transforms it, walks down the main lobe to its first minimum, and returns the largest value beyond it. If someone mistypes a coefficient, the build fails with the name of the window.

Here is PySDR’s windowing demonstration (a strong tone with a second one 50 dB weaker next to it) computed by the C++ Welch estimator described below, once per window:

Welch power spectral density of two tones 50 dB apart with rectangular, Hann and Blackman-Harris windows; the weak tone is invisible without a window

Without a window, the strong tone’s leakage at 130 kHz is 11 dB above the weak tone; with Hann the weak tone stands 58 dB above the noise floor; Blackman-Harris pulls the skirts down further at the price of a wider main lobe (first nulls at ±4 bins instead of ±2, which is what its larger ENBW means).

PySDR’s Recursive FFT as a Template

PySDR’s FFT Implementation section shows the Cooley-Tukey algorithm in eight lines of Python:

def fft(x):
    N = len(x)
    if N == 1:
        return x
    twiddle_factors = np.exp(-2j * np.pi * np.arange(N//2) / N)
    x_even = fft(x[::2]) # yay recursion!
    x_odd = fft(x[1::2])
    return np.concatenate([x_even + twiddle_factors * x_odd,
                           x_even - twiddle_factors * x_odd])

A direct C++ translation would allocate several vectors per call (the twiddles, the two slices, the products, the concatenation), and an \(N\)-point FFT makes \(2N-1\) calls. None of these allocations is necessary. x[::2] is a view of every other element, which in C++ is “the same pointer, twice the stride”; x[1::2] is the same with the pointer advanced by one. And the concatenation only says where the results go: the even half’s FFT into the first half of the output, the odd half’s into the second. So the recursion can write straight into its output:

template <std::size_t N, class T>
constexpr void fft_recursive(const std::complex<T>* x, std::size_t stride, std::complex<T>* out)
{
    if constexpr (N == 1) {
        out[0] = x[0];
    } else {
        fft_recursive<N / 2>(x, 2 * stride, out);                   // x[::2]  -> out[0 : N/2]
        fft_recursive<N / 2>(x + stride, 2 * stride, out + N / 2);  // x[1::2] -> out[N/2 : N]
        for (std::size_t k = 0; k < N / 2; ++k) {
            const auto e = out[k], t = twiddles<N, T>[k] * out[k + N / 2];
            out[k] = e + t;                                         // the butterfly
            out[k + N / 2] = e - t;
        }
    }
}

The size is a template parameter, so the recursion is unrolled at compile time: fft_recursive<1024> calls fft_recursive<512>, down to fft_recursive<1>, and if constexpr ends it. Each level has its own twiddles<N, T>, a variable template holding the \(N/2\) factors that PySDR recomputes with np.exp on every call; here they are computed once, by the compiler, and stored as constants. (In the actual code the complex product is written out as four real multiplications, for the reason given in Samples in Memory.)

On PySDR’s own test signal (a 200 kHz tone in noise, \(N = 1024\)), this function and PySDR’s Python function agree to \(4.7 \cdot 10^{-13}\) in double precision; the float version agrees with FFTW to float precision. And because everything is constexpr, the same function computes the window sidelobes above at compile time, and checks two textbook identities: the FFT of an impulse is flat, and the FFT of a constant is an impulse.

For real work, use FFTW (or a vendor library). A radix-2 recursion does not use SIMD, split-radix, or cache blocking, and FFTW’s planner picks among dozens of algorithms for your exact size and machine. The recursive template is for understanding and for the compiler: it is what you write when you need an FFT inside a static_assert.

FFT Plans Are Resources

PySDR says that any FFT size works but powers of two are fastest, and that common sizes are 128 to 4096. With FFTW the size is fixed when you create a plan, and creating it is the expensive part: with FFTW_MEASURE, FFTW actually runs candidate algorithms and times them, which can take milliseconds. So plans belong in constructors, not in the streaming path, and they need an owner that destroys them exactly once. fftwf_plan is a pointer to an opaque struct, which is exactly what std::unique_ptr with a custom deleter is for (code/include/cppsdr/fftw.hpp):

struct fftw_plan_deleter {
    void operator()(fftwf_plan p) const
    {
        std::scoped_lock lock(fftw_planner_mutex());   // the planner is not thread-safe
        fftwf_destroy_plan(p);
    }
};
using fftw_plan_ptr = std::unique_ptr<std::remove_pointer_t<fftwf_plan>, fftw_plan_deleter>;

The lock is there because FFTW’s planner, including plan destruction, is not thread-safe; only fftwf_execute is. GNU Radio has the same process-wide lock, gr::fft::planner::mutex() in gr-fft/lib/fft.cc, and additionally saves the planner’s results (“wisdom”) to a file in the user’s home directory so the next run plans instantly.

One FFTW rule surprises almost everyone once. The manual marks it Important: “the planner overwrites the input array during planning unless a saved plan (see Wisdom) is available for that problem, so you should initialize your input data after creating the plan.” A class that plans in its constructor and fills its buffers later follows this rule by construction.

The Spectrogram as One Buffer

PySDR builds its spectrogram row by row:

spectrogram = np.zeros((num_rows, fft_size))
for i in range(num_rows):
    spectrogram[i,:] = 10*np.log10(np.abs(np.fft.fftshift(np.fft.fft(x[i*fft_size:(i+1)*fft_size])))**2)

Each row creates a chain of temporary arrays (the FFT, the shifted copy, the magnitudes, their squares, the logarithms) before the result is copied into the row. The C++ version keeps the rows in one contiguous buffer and changes three things.

One plan for all rows. FFTW can transform many equally spaced arrays with one batched plan, fftwf_plan_many_dft. The spectrogram object plans once for rows transforms of fft_size points, in place, and a single fftwf_execute computes every row.

The shift is fused into the output pass. Instead of rotating each row and then converting it, the conversion to dB simply reads the two halves in shifted order:

const std::size_t lo = (n_ + 1) / 2;                                  // first negative frequency
for (std::size_t k = lo; k < n_; ++k) *out++ = to_db(X[k]);           // negative half first
for (std::size_t k = 0;  k < lo; ++k) *out++ = to_db(X[k]);           // then DC and up

where to_db computes 10*log10(re*re + im*im). It does not call std::abs (a square root that the square immediately undoes) or std::norm (which in libc++ checks for infinities on every call, see Samples in Memory).

The result is a 2-D view, not a list of rows. C++23’s std::mdspan puts a two-dimensional index on top of the flat buffer without owning or copying it:

using view_type = std::mdspan<const float, std::dextents<std::size_t, 2>>;
view_type compute(std::span<const cf32> x);   // returns view_type(db_.data(), rows_, n_)

auto S = spec.compute(x);
float v = S[row, bin];          // C++23 multidimensional subscript

The caller gets the same thing PySDR’s spectrogram[i, :] gives (a row-major matrix of dB values), the storage stays one allocation that is reused for the next spectrogram, and the view can be handed to plotting or detection code without copying. On PySDR’s own test signal (its tone at 50 kHz plus noise, 50 rows of 1024), the C++ spectrogram matches PySDR’s array to \(7 \cdot 10^{-7}\) of each row’s peak power, the difference between float and double.

The constructor also takes a window and a hop size, so the rows can overlap. PySDR’s version uses neither, and its rows are exactly the C++ rows with the defaults.

Averaging: A Streaming Welch Estimate

PySDR notes that for long signals you “can either average them up or plot them over time”. Plotting over time is the spectrogram; averaging is the Welch method: windowed, usually half-overlapping frames, with the squared magnitudes averaged. In a real-time program, samples arrive in blocks of whatever size the SDR delivers, and frames straddle those blocks. As in every chapter of this book, that makes the frame being assembled part of the object’s state:

template <class Window>
class welch {
public:
    static constexpr std::size_t N = Window::size;
    explicit welch(double fs, std::size_t hop = N / 2);
    void process(std::span<const cf32> x);   // any block size
    std::vector<double> psd() const;         // two-sided density, fftshifted
private:
    std::vector<cf32> frame_;                // the frame being assembled, kept between calls
    ...
};

The window is a template parameter, so its taps and its \(\sum w^2\) (needed for the density scaling) are compile-time constants inside process. The test runs the estimator on a complex signal with two tones 50 dB apart and compares it with scipy.signal.welch(x, fs, window='hann', nperseg=1024, noverlap=512, return_onesided=False, detrend=False, scaling='density'): same 63 frames, same values to \(4 \cdot 10^{-8}\) of the peak. Feeding the same samples in random block sizes between 1 and 3000 gives a bit-identical result.

GNU Radio’s logpwrfft (in gr-fft/python/fft/logpwrfft.py) does the averaging differently: instead of a block average it runs every bin through a one-pole IIR filter, single_pole_iir_filter_ff, an exponential moving average that never needs to know how many frames there were. That filter is PySDR’s x = x*0.99 + new_value*0.01, and it is the starting point of IIR Filters and Denormals.

Where does the spectrum go next? Pirkle’s answer for audio plugins (Designing Audio Effect Plugins in C++, chapter 21) is to keep the real-time thread as light as possible: it only pushes samples into a lock-free single-producer, single-consumer queue (Threads and Lock-Free Queues), and the GUI thread, woken by a timer, pulls them out and computes the FFT for the display itself. His chapter 20 wraps FFTW in a small object with the same rules as here: plan once, fixed buffers, no allocation while streaming.

Key Takeaways

  • fftshift is std::rotate by \(\lceil N/2 \rceil\), ifftshift by \(\lfloor N/2 \rfloor\); they differ for odd \(N\).

  • Compute frequency axes from integer bin indices; floating-point arange and linspace axes can have the wrong length or the wrong spacing.

  • A window is a type: its taps, coherent gain and ENBW are compile-time constants, and a compile-time FFT can check its sidelobes. Use periodic windows for spectra and symmetric ones for filter design.

  • PySDR’s recursive FFT becomes a template recursion with strides instead of slices: no allocations, twiddles computed by the compiler, usable in constexpr. For speed, use FFTW.

  • FFTW plans are resources: create them once, own them with std::unique_ptr, guard the planner with a mutex, and fill the buffers after planning.

  • A spectrogram is one buffer, one batched plan, one fused shift-and-dB pass, and an std::mdspan view.