7. FIR Filters in C++¶
PySDR’s Filters chapter explains what an FIR filter does, how to design its taps (we did that at compile time in Compile-Time DSP: Filters, Tables and Constellations), and, in “Filtering in Chunks”, how to run it on a stream by carrying the filter’s memory from one block to the next. It deliberately does not dive into implementation. This chapter does, and it boils down to three design questions: how to store the delay line, how to write the multiply-accumulate loop, and when to stop convolving directly and use the FFT instead.
The operation is
which reads: each output is the newest \(N\) inputs, each weighted by “its” tap, added up. We use the most common case in a receiver, complex samples and real taps (GNU Radio’s fir_filter_ccf), and one interface for every variant:
void process(std::span<const cf32> in, std::span<cf32> out); // in.size() == out.size()
process() may be called on consecutive blocks of any size; each object keeps the last \(N-1\) inputs, PySDR’s “carry the state”. All variants are in code/include/cppsdr/fir.hpp, and code/tests/test_fir.cpp checks every one of them with hand vectors (an impulse must return the taps, a step their running sum) and against a double-precision reference fed in blocks of random size, which is what catches state bugs at block boundaries.
Storing the Delay Line¶
The block diagram in PySDR, a chain of \(z^{-1}\) boxes, translates literally into a circular buffer: an array of \(N\) samples and a write position that wraps around.
cf32 step(cf32 x)
{
const std::size_t n = h_.size();
z_[pos_] = x; // newest sample overwrites the oldest
cf32 acc{};
for (std::size_t k = 0; k < n; ++k)
acc += h_[k] * z_[(pos_ + n - k) % n]; // x[n-k]
pos_ = (pos_ + 1) % n;
return acc;
}
It is correct and never moves data, but the index jumps from the end of the array back to the start in the middle of the dot product. The samples are not one contiguous run of memory, so the compiler cannot use SIMD instructions, and % is an integer division on top. (A power-of-two buffer turns % into &, but the wrap remains.)
Every serious implementation therefore arranges for the window of \(N\) samples to be contiguous, so that each output is an ordinary dot product of two arrays. There are three standard ways to get there, and each has a home in a real code base:
History buffer (per block). GNU Radio does this at the scheduler level: a filter block calls set_history(ntaps) (gr-filter/lib/fir_filter_blk_impl.cc), and every input buffer it receives starts with the previous \(N-1\) samples. Our fir_history does the same inside the object: one linear buffer holds \(N-1\) samples of history followed by the new block, output \(i\) is a dot product starting at &buf[i], and after the block the last \(N-1\) samples are copied to the front:
void process(std::span<const cf32> in, std::span<cf32> out)
{
const std::size_t hist = t_.n4 - 1;
std::copy(in.begin(), in.end(), buf_.begin() + hist); // [ history | new block ]
for (std::size_t i = 0; i < in.size(); ++i)
out[i] = dot(buf_.data() + i, t_.hr.data(), t_.n4); // contiguous window, oldest first
std::copy(buf_.begin() + in.size(), buf_.begin() + in.size() + hist, buf_.begin());
}
The taps are stored reversed so that window and taps run in the same direction (GNU Radio’s fir_filter::set_taps reverses them too), and buf_ is allocated once in the constructor for the largest block the caller promises: process() never allocates.
Sliding window (per sample). liquid-dsp (src/buffer/src/window.proto.c) appends samples to an array of \(2^m + N - 1\) and, when it reaches the end, moves the newest \(N-1\) samples back to the front: one memmove every \(2^m\) samples.
Mirrored delay line (per sample, constant work). A buffer of \(2N\), in which every sample is written twice, at pos and pos + N; the last \(N\) samples are then always contiguous at [pos+1, pos+N]:
z_[pos_] = x;
z_[pos_ + n] = x; // the mirror copy
const cf32* w = z_.data() + pos_ + 1; // oldest ... newest, contiguous
One extra store per sample buys a window that never needs moving. It is the software twin of GNU Radio’s stream buffers, which let the operating system do the mirroring by mapping the same physical memory twice, back to back (gnuradio-runtime/lib/vmcircbuf.h, “doubly mapped virtual memory circular buffers”). fir_static from Compile-Time DSP: Filters, Tables and Constellations uses this layout with a std::array sized by a template parameter, so it needs no heap at all.
Once the window is contiguous, the choice between the three is about the interface (blocks or single samples, bounded or constant work per sample), not about speed: in our tests they were within 15% of each other. What matters much more is the dot product.
Writing the Dot Product¶
The idiomatic C++ dot product is std::inner_product:
return std::inner_product(hr, hr + n, w, cf32{});
and it is the slowest correct way to write it, about three times slower than it could be even before SIMD. The reason is the single accumulator. inner_product is specified to add strictly left to right, so every addition must wait for the previous one to finish. A floating-point addition takes about three to four cycles from start to result (its latency), so a chain of dependent additions runs at a third of the core’s speed even though the core could start one or more additions every cycle. Pikus explains this instruction-level parallelism in The Art of Writing Efficient Programs (Packt 2021, chapter 3).
The compiler is not allowed to fix this for you: floating-point addition is not associative, \((a+b)+c\) may differ from \(a+(b+c)\) in the last bit, and regrouping the sum would change the result your source code specifies. So you have to give permission, and there are three ways to do it, with very different scope.
Write the reordered sum yourself. Keep several independent accumulators and combine them at the end. With 8 to 16 partial sums, the chains overlap and the compiler can map them onto SIMD registers without any flag:
template <std::size_t ACC>
cf32 dot_split(const cf32* w, const float* hh, std::size_t n) // hh: taps duplicated (h0,h0,h1,h1,...)
{
const float* x = reinterpret_cast<const float*>(w); // re,im,re,im,... (see samples chapter)
float acc[ACC] = {};
for (std::size_t k = 0; k < 2 * n; k += ACC)
for (std::size_t l = 0; l < ACC; ++l) acc[l] += hh[k + l] * x[k + l];
float re = 0, im = 0;
for (std::size_t l = 0; l < ACC; l += 2) { re += acc[l]; im += acc[l + 1]; }
return {re, im};
}
Grant permission for one loop. OpenMP’s simd directive with a reduction clause says exactly “the partial sums of these variables may be regrouped”, for this loop and nothing else:
cf32 dot_omp_simd(const cf32* w, const float* hr, std::size_t n)
{
const float* x = reinterpret_cast<const float*>(w);
float re = 0, im = 0;
#pragma omp simd reduction(+ : re, im)
for (std::size_t k = 0; k < n; ++k) {
re += hr[k] * x[2 * k];
im += hr[k] * x[2 * k + 1];
}
return {re, im};
}
Despite the name there are no threads involved: compiling with -fopenmp-simd (GCC and Clang) enables only the SIMD directives, without the OpenMP runtime. This is the shortest code, the most portable, and it was also the fastest version we wrote: on an Apple M1 the compiler loads four complex samples at a time and splits them into real and imaginary parts on the fly (ld2.4s). Without the flag the pragma is silently ignored, so keep an eye on the build files.
Grant permission for everything: -ffast-math. The flag lets the compiler reorder all floating-point arithmetic in the file, and also assume there are no NaNs or infinities. It does make std::inner_product fast, but it is a global switch with global consequences, and in our tests it made the hand-split version slower: with the freedom to reorder everything, Clang’s vectorizer chose a different plan for the nested loop and ended up loading single floats lane by lane. Prefer the local permission.
A fourth option is to call a library. GNU Radio’s FIR filter uses VOLK’s volk_32fc_32f_dot_prod_32fc, which has hand-written kernels for SSE, AVX, AVX-512, NEON and RISC-V and picks one at run time; run volk_profile once on a new machine so it picks well. The dispatch has a small fixed cost per call, which shows for very short filters.
Dot product |
ns per tap |
|---|---|
|
0.95 |
hand-split, 8 accumulators |
0.33 |
VOLK |
0.20 |
|
0.15 |
One more trap on the way: std::transform_reduce is allowed by the standard to regroup the sum, but whether you benefit depends on your standard library. libstdc++ (GCC) adds the products in small groups of four and was four times faster than inner_product; libc++ (Clang, the default on macOS) uses the plain left-to-right loop. Same source, same standard, a factor of four. Say what you want explicitly, as above, and the code behaves the same everywhere.
When to Stop Convolving: Fast Convolution¶
Every direct form costs \(N\) multiply-adds per output. PySDR’s “Filtering in Chunks” introduces the alternative: transform a block, multiply by the precomputed spectrum of the taps, transform back, and handle the block edges with overlap-add or overlap-save. Our fir_overlap_save (fir_fft.hpp) is a transcription of PySDR’s overlap-save code, and the interesting parts are the C++ habits around it:
Plans are made once, in the constructor. FFTW’s planner with
FFTW_MEASUREtimes several algorithms before choosing one, which can take milliseconds, and it is not thread-safe. GNU Radio wraps every plan creation in a process-wide lock,gr::fft::planner::mutex()(gr-fft/lib/fft.cc); we do the same. Plan creation never happens on the streaming path.The 1/N scaling is folded into the taps before their spectrum is computed, instead of dividing every output sample; GNU Radio’s
fft_filterdoes the same.The FFT library is a template parameter.
fir_overlap_save<Backend>works with any class that offerstime(),freq(),forward()andinverse(); we wrote backends for FFTW and Apple’s Accelerate framework. Because the backend is a template parameter rather than a virtual base class, the choice costs nothing per block. This policy-based design lets you swap FFT libraries per platform without touching the filter.
Figure 7.1 Cost per output sample versus filter length (log-log), 8192-sample blocks, with PySDR’s NumPy code in gray for reference.¶
The direct form grows linearly with the number of taps, the FFT filter only logarithmically; on this machine they cross between 32 and 64 taps. Two practical notes. First, check how your FFT library was built: the Homebrew FFTW used here is compiled without NEON on Apple Silicon (its plans use scalar codelets such as n1_32 instead of n1fv_32), which you only find out by printing a plan. Second, the FFT size is a trade-off between efficiency (about 4 to 16 times the filter length was best) and latency: overlap-save can only produce output once a full block has arrived.
What About NumPy?¶
The gray curves show something worth knowing: PySDR’s “carry the state” filter (np.concatenate plus np.convolve) is not slow. np.convolve runs compiled, vectorized C, and for large blocks it beat the first, naive C++ versions in this chapter. A literal port of NumPy code to C++ is often slower than the NumPy code. Where C++ pulls ahead decisively is small blocks, which you want when latency matters: every Python call carries a fixed overhead of microseconds (2 µs for the np.convolve version, 13 µs for scipy.signal.lfilter in our test), so with 16-sample blocks the cost per sample grew 10 to 70 times over the C++ filter, whose cost per sample did not depend on the block size at all.
Key Takeaways¶
Keep the filter window contiguous: a history buffer per block (GNU Radio), a sliding window (liquid-dsp) or a mirrored delay line per sample. Avoid wrapping inside the dot product.
A single accumulator turns the dot product into a latency-bound chain. Grant reassociation locally with
#pragma omp simd reductionand-fopenmp-simd, or write independent accumulators yourself; avoid relying on-ffast-math.Allocate in the constructor, never in
process(); create FFT plans once and under a lock.Make swappable parts (FFT library, dot-product kernel) template parameters: static polymorphism costs nothing at run time.
Above a few dozen taps, use FFT-based fast convolution, sized to your latency budget.
Further Reading¶
GNU Radio 3.10:
gr-filter/lib/fir_filter.cc,gr-filter/lib/fft_filter.cc,gnuradio-runtime/lib/vmcircbuf.h. github.com/gnuradio/gnuradioVOLK: libvolk.org; liquid-dsp: github.com/jgaeddert/liquid-dsp
Frigo and S. G. Johnson, “The Design and Implementation of FFTW3,” Proc. IEEE, vol. 93, no. 2, pp. 216-231, 2005. PDF
Pikus, The Art of Writing Efficient Programs, Packt, 2021, chapters 3 and 10.
Pirkle, Designing Audio Effect Plugins in C++, 2nd ed., Routledge, 2019, chapters 14 and 16.