1. Introduction

This textbook is based on the fantastic PySDR by Dr. Marc Lichtman and is meant as an addition: it shows how to realise the concepts PySDR discusses in C++. PySDR teaches you what a filter, an FFT, a Costas loop or a polyphase resampler does and why. Here we take those same building blocks and ask a different question: what does it take to run them on a real stream of samples, at a real sample rate, without ever falling behind? The answer to that question lives in the C++ language features, the libraries, and the habits of mind that make real-world SDR software (and, one step further down, FPGA firmware) look the way it does.

You will get the most out of this companion if you read the matching PySDR chapter first. We will not re-derive the DSP. Instead, every chapter here starts where a PySDR chapter ends, links back to it, and then turns the Python into C++, measures the result, and compares a few competing implementation strategies.

Why Not Just Python?

Let’s be fair to Python from the start, because PySDR already says it well in its own introduction:

“while Python is ‘slower’ than C/C++ in general, most functions within Python/NumPy are actually implemented in C/C++ under the hood and heavily optimized, so you might be surprised how fast CPU-based DSP can run in Python […] For fielded RF systems, high-rate signal processing is typically implemented in the FPGA anyway!” – PySDR, Introduction

Both halves of that sentence are true, and this whole book lives in the space between them. When you call np.convolve you are already running compiled C. For a lot of work (offline analysis of a recording, prototyping, plotting, education) Python is the right tool and you should stay there. So when does it stop being enough? There are four situations that come up again and again.

1. When the next sample depends on the previous result. NumPy is fast because it hands a whole array to C at once. That only works if each output can be computed independently of the others. A filter’s output depends only on the inputs, so it vectorizes. But a phase-locked loop, a Costas loop, a Mueller and Muller timing recovery, an AGC or an IIR filter all feed their own output back: to process sample \(n\) you need the state left behind by sample \(n-1\). There is no array to hand over; there is a loop, and in Python every iteration of that loop costs on the order of a hundred nanoseconds of interpreter overhead before any math happens. PySDR’s Costas loop in its Synchronization chapter is exactly such a loop, and in the Feedback Loops: the Costas Loop chapter we will measure what moving it to C++ buys (spoiler: a factor of almost ninety, and why it is not more).

2. When “fast on average” is not good enough. Real-time does not mean fast; it means on time, every time. A receiver that processes a block in 1 ms on average but occasionally takes 30 ms because the garbage collector ran, a lock was contended, or memory was allocated, will drop samples. Ross Bencina summarised the consequences for audio software in a single title, “Real-time audio programming 101: time waits for nothing”, and everything he says applies to SDR, only at a thousand times the sample rate. C++ gives you control over exactly the things that cause those stalls: when memory is allocated, which thread runs where, and what happens on the hot path.

3. When you want the compiler on your side. A Python script finds out at run time that a filter has an even number of taps, that a dBm value was added to a dBW value, or that a state flag was read in the wrong state. C++ can move many of these checks to compile time: filter taps computed and verified while compiling, units encoded in types, protocol states as types of their own. Several chapters of this book are about exactly that, and none of it costs anything at run time.

4. When you need to reason about the hardware. How wide are the SIMD registers? Does this buffer fit in the L1 cache? Will this phase accumulator wrap around exactly like the one in the FPGA? C++ lets you say precisely what data layout and what arithmetic you want, and it lets you write bit-true models of hardware that you can test against a VHDL implementation sample by sample.

That last point is also why so much real SDR software is written in C or C++: the GNU Radio blocks are C++ with Python bindings on top, its math kernels come from the VOLK SIMD library, liquid-dsp is written in C, and the UHD driver for USRPs, SDR++ and the srsRAN Project 5G stack are C++. Throughout this book we will open their source code and look at how they solved the problems we meet, with links to the exact file and version.

The Real-Time Budget

Before any code, let’s put a number on “fast enough”. If your SDR delivers \(f_s\) samples per second, then on average you have

\[T_{\text{sample}} = \frac{1}{f_s}\]

seconds to deal with each sample, and not a nanosecond more, or the buffers start to fill up. Read that equation the other way around and it becomes a budget: at a given clock frequency, it tells you how many CPU cycles each sample is allowed to cost. Here is that budget for a few typical sample rates, for one core running at 3.2 GHz (the performance cores of the Apple M1 used for all measurements in this book):

Table 1.1 Time and CPU cycles available per sample, single core at 3.2 GHz

Sample rate

Typical source

Time per sample

Cycles per sample

48 kHz

audio, narrowband baseband

20.8 µs

66 667

2.4 MHz

RTL-SDR

417 ns

1 333

20 MHz

HackRF One

50 ns

160

61.44 MHz

USRP B210 (max.)

16.3 ns

52

250 MHz

high-end ADC / RFSoC

4 ns

13

Let that sink in for a moment. At 20 MHz, a 64-tap FIR filter written in the most obvious way already costs more than the entire budget (we will measure about 50 ns per sample for it in the FIR Filters in C++ chapter), and a single cache miss to main memory costs roughly 100 ns. At 250 MHz a CPU core has thirteen cycles per sample, which is not enough to do anything useful on its own. That is where the FPGA takes over: in fabric, a 64-tap filter is 64 multipliers working in parallel on every clock edge, and the “budget” is one sample per clock by construction.

Where C++ ends and VHDL begins. A useful mental picture is a ladder. Python/NumPy is great up to the point where per-sample loops or latency guarantees matter. C++ on a general-purpose CPU takes you to tens of megasamples per second on one core, more with SIMD and threads. Beyond that, the high-rate front end (digital down-conversion, decimation, channelization) moves into an FPGA, and the CPU only sees the reduced-rate output. In a Zynq or RFSoC system both sides sit on one chip. Many of the C++ techniques in this book (fixed-point phase accumulators, CIC filters, integer arithmetic that wraps around “for free”) were chosen precisely because they map one-to-one onto hardware, so that the C++ model is the reference for the VHDL.

How This Book Is Organized

PySDR is organised around DSP topics, and so is this companion. Each chapter picks up a PySDR topic and asks what C++ lets us do differently, not just how to transliterate the Python. Sometimes the answer is speed, but more often it is something else: numbers the compiler computes and checks, units the compiler tracks, states that cannot be confused, memory that is never allocated on the hot path. The book has three parts:

Part I: The C++ toolbox for DSP.

Part II: PySDR’s DSP in C++.

  • The FFT and the Spectrogram: fftshift as a rotation, windows that carry their own correction factors, PySDR’s recursive FFT as a template, FFTW plans as RAII objects, and a spectrogram as one buffer viewed through std::mdspan.

  • FIR Filters in C++: how to store a delay line and write the dot product so the CPU can run it well, and when to switch to FFT-based fast convolution.

  • IIR Filters and Denormals: feedback filters, the subnormal number that PySDR’s x = 0.99*x + ... gets stuck at, flush-to-zero, and why a stable filter becomes unstable in float.

  • Oscillators and Frequency Shifting: numerically controlled oscillators, and why the integer phase accumulator that every FPGA uses is also the best choice in C++.

  • Pulse Shaping and the Eye Diagram: a polyphase interpolator that skips the zeros of the pulse train, the RRC and its ISI at compile time, and an eye diagram as an std::mdspan view.

  • Feedback Loops: the Costas Loop: the Costas loop from PySDR’s Synchronization chapter, a feedback loop that NumPy cannot vectorize, and how to think about such loops.

  • Timing Recovery with a Compile-Time Filter Bank: Mueller and Muller timing recovery with a compile-time polyphase bank of fractional-delay filters instead of interpolating the whole signal.

  • Digital Modulation, End to End: constellations as types, differential coding at compile time, and a complete coded QPSK link built from the earlier chapters’ blocks.

  • CFAR and Real-Time Packet Detection: PySDR’s real-time packet detector as one streaming object, with CFAR thresholds from running sums.

  • Correlating Under Frequency Offset: correlation under frequency offset: PySDR’s loss formula checked, segmented correlators, the FFT frequency shift trick, and the Zadoff-Chu ridge.

  • Spreading Codes: GPS C/A Codes at Compile Time: GPS C/A codes generated and cross-checked by the compiler, correlation with std::popcount, and PySDR’s GPS acquisition on its recording.

  • Channel Coding: Hamming codes built from PySDR’s rule and proven by the compiler, a convolutional code as a type, and a Viterbi decoder for soft and hard decisions.

  • LDPC Codes: Messages Live on Edges: a quasi-cyclic LDPC code built and checked by the compiler, and sum-product, min-sum and fixed-point layered decoders, cross-checked with GNU Radio’s gr-fec.

  • Bits and State Machines: Decoding RDS: PySDR’s RDS decoder rebuilt with computed code tables, a std::variant state machine and named bit fields.

  • Multipath Fading as a Channel Object: Rayleigh fading as a streaming channel of vectorized rotators, checked against Rayleigh theory, plus a frequency-selective tapped delay line.

  • OFDM: Transmitter and Receiver: PySDR’s OFDM generator as a transmitter, and the receiver it lacks: synchronization from the cyclic prefix, one division per subcarrier, pilots.

  • Cyclostationary Processing: the cyclic autocorrelation as one FFT per lag, frequency smoothing that computes only what it keeps, and a streaming detector for a known cyclic feature.

  • Beamforming and Direction of Arrival: beamforming and DOA with the array size as a template parameter, MVDR by Cholesky, MUSIC with a Jacobi eigensolver.

  • Null Steering and LMS: null steering at compile time with exact nulls, and PySDR’s LMS beamformer, its step size, NLMS and sample-matrix inversion.

  • TDOA: Delays, Peaks and Positions: sub-sample delay estimation compared with GNU Radio’s and PySDR’s methods, weighting as a policy, and positioning as GPS backwards.

  • Delay and Doppler: the Ambiguity Function: joint TDOA/FDOA with the cross-ambiguity function, one FFT per lag or one per Doppler bin, Stein’s decimation, and sub-cell refinement.

Part III: Systems.

An appendix, Appendix: Measuring Before Optimizing, explains how the few measurements in the book were made, and shows what a real-time scheduling policy does for a periodic receiver thread. The Roadmap lists the chapters that are planned next.

About the Code

Every piece of code in this book lives in the code/ directory next to the text, compiles with CMake as C++20, and has tests, usually against PySDR’s own Python output or against SciPy. Where the text quotes a speed, it was measured on an Apple M1 with Apple Clang 21 and -O3 -mcpu=native; your numbers will differ, but the reasons behind them carry over.

To build everything:

# macOS: brew install cmake volk fftw     Debian/Ubuntu: apt install cmake libvolk-dev libfftw3-dev
cmake -S code -B code/build -DCMAKE_BUILD_TYPE=Release
cmake --build code/build -j
ctest --test-dir code/build      # every implementation is checked first
./code/build/bench_fir           # then measured

Acknowledgements and License

The structure, the topics and much of the spirit of this book come from PySDR, which is licensed CC BY-NC-SA 4.0; please read it, support it, and cite it. Where we quote it, we link to the original section. The code in this book is meant to be read, copied and modified.