33. A Complete Receiver¶
PySDR’s RDS chapter is its capstone: a real FM broadcast recording goes in, and out come the station’s identification, its programme type and the scrolling RadioText. Along the way it uses almost everything the book teaches: FM demodulation, a frequency shift, a low-pass filter and decimation, rational resampling, Mueller and Muller timing recovery, a Costas loop, BPSK decisions, differential decoding, and the RDS block code. Our own Bits and State Machines: Decoding RDS only covered the last part, starting from bits. This chapter runs the whole chain in C++ on PySDR’s own recording, fm_rds_250k_1Msamples.iq, and compares it with PySDR’s code stage by stage.
There is little new DSP in this chapter. Its subject is what happens when the pieces from earlier chapters are put together: whether they still fit when the stream is cut into arbitrary blocks, how the stages are split across threads and how those threads learn that the stream has ended, and what the Python version does in its one-shot style that a streaming receiver cannot do.
The blocks that earlier chapters did not provide are in code/include/cppsdr/receiver.hpp; code/examples/fm_receiver.cpp is the receiver as a program, and code/tests/test_receiver.cpp is the comparison. figure-generating-scripts/receiver_reference.py runs PySDR’s full listing (read from a local PySDR checkout, changed only in the file path) and saves the signal after each stage. The recording is 8 MB and not part of this book’s repository; download it from the link in PySDR’s chapter into code/testdata/receiver/ (without it, the test reports “skipped”).
The Chain, Block by Block¶
PySDR’s receiver is written as a sequence of whole-array operations, each producing a new array x. The C++ receiver is a sequence of objects, each with a process() that takes whatever arrived and appends to its output:
PySDR |
C++ |
from |
|---|---|---|
|
|
this chapter |
|
|
|
|
|
FIR Filters in C++, Compile-Time DSP: Filters, Tables and Constellations |
|
|
this chapter |
M&M loop on |
|
|
Costas loop, |
|
|
|
|
|
de-emphasis, |
|
The new blocks are small, but each of them has a streaming detail that PySDR’s array version does not need to think about.
The demodulator needs the next sample. PySDR’s line multiplies x[n] by the conjugate of x[n+1], so output \(n\) exists only once sample \(n+1\) has arrived. The object remembers the last sample of each block, and the first sample of the next block completes the pair.
The decimator computes only what it keeps. np.convolve(x, taps, 'valid') computes every output, and x[::10] then throws nine out of ten away. fir_decimator<N, D> evaluates the dot product only at the positions that survive, a factor of \(D\) less work. When a block ends in the middle of a decimation step, the object remembers how many of the next block’s samples to step over. That is one counter, but without it every block boundary would shift the decimation phase.
The resampler is a polyphase bank, designed by the compiler. scipy.signal.resample_poly(x, 19, 25) conceptually inserts 18 zeros between samples (to 475 kHz), low-pass filters, and keeps every 25th sample. Its filter is firwin(501, 1/25, window=('kaiser', 5.0)) scaled by 19. resample_poly_design<19, 25> computes the same 501 taps at compile time, including the Kaiser window and its Bessel function \(I_0\) (a power series), and the test confirms the centre tap matches SciPy’s to \(10^{-12}\). Most of the zero-stuffed products are zero, so for each output only every 19th tap meets a real sample. Which ones depends on the output’s position modulo 19, the phase. The design splits the taps into a bank of 19 sub-filters of 27 taps, the same polyphase idea as the timing chapter’s bank:
for (;;) {
const std::size_t t = Down * m_ + design::half_len;
const std::size_t k_max = t / Up, p = t % Up; // newest input used, and the phase
if (k_max >= received_) break; // not yet arrived
const auto& h = design::bank[p];
T acc{};
for (std::size_t j = 0; j < J; ++j) acc += h[j] * x[k_max - j];
out.push_back(acc);
++m_;
}
27 multiply-adds per output instead of 501. The indexing reproduces SciPy’s alignment exactly (SciPy delays nothing; output \(m\) sits at input time \(25m/19\)), so the streaming output can be compared sample by sample with resample_poly. GNU Radio’s rational_resampler block uses the same polyphase structure.
Against PySDR, Stage by Stage¶
The test runs both receivers on the same one million samples and compares:
stage |
C++ vs. PySDR |
|---|---|
demodulation, mixer, low-pass, decimation |
99 990 samples each, relative error \(3.6 \cdot 10^{-7}\) |
|
relative error \(3.5 \cdot 10^{-7}\); C++ has 10 samples fewer (see below) |
RDS groups |
all 34 of PySDR’s groups, plus two more at the start |
station |
PI 0x571D, programme type 9 (“Top 40” in the North American table), as PySDR prints |
The first two rows are float against float64, which is as close as two implementations can be. The ten missing resampler outputs are the end of the recording: SciPy knows the array ends and filters the last samples against zeros, while a streaming resampler waits for samples that never come. A real receiver never reaches the end of its input; a file reader would add a flush().
From the timing loop on, the two receivers deliberately differ: PySDR interpolates the whole signal by 32 and picks samples, the C++ loop uses the compile-time filter bank from Timing Recovery with a Compile-Time Filter Bank. So the comparison moves to what matters, the decoded data. C++ decodes every group PySDR decodes, and two more at the very beginning: it achieves block synchronization earlier because its decoder looks for all offset words, not only for offset A (the misplaced break described in Bits and State Machines: Decoding RDS). PySDR also outputs one group three times in a row where C++ outputs it twice, which matches the duplicate-emission behaviour found in that chapter.
The whole chain processes the 4 seconds of signal in about 60 ms on the M1, single-threaded, roughly 65 times faster than real time. That headroom is what makes the next section a design choice rather than a necessity.
Cut Anywhere, Run Anywhere¶
Every block in this receiver carries its state between calls, and the test checks the whole chain the way earlier chapters checked single blocks. Feeding the recording in random blocks of 1 to 3000 samples produces bit-identical symbols, groups and audio compared with a single call. This is the property that makes a receiver live: an SDR driver delivers blocks of whatever size it likes, and so does GNU Radio’s scheduler (Writing a GNU Radio Block in C++).
The same property lets us split the receiver across threads without changing a line of DSP code. The test runs a three-thread version: one thread demodulates, and the FM signal goes through two queues to an RDS thread and an audio thread. Its output is again identical to the single-threaded run.
The queues are the SPSC rings from Threads and Lock-Free Queues, with one addition that every pipeline needs and that chapter did not cover: how does a consumer learn that the stream has ended? The consumer sleeps until new data arrives, using C++20’s atomic::wait on the ring’s tail index. But wait(old) only returns once the value differs from old. When the producer finishes, it has nothing more to push, so the tail never changes again, and a consumer waiting on it sleeps forever. A separate “done” flag does not help, because the consumer is not waiting on the flag.
The fix is an old pattern called an eventcount: one counter that every event increments, both “data pushed” and “stream closed”, and the consumer waits on that counter instead:
template <class T, std::size_t Capacity>
class channel {
public:
void send(std::span<const T> in); // push, bump epoch_, notify
void close()
{
closed_.store(true, std::memory_order_release);
epoch_.fetch_add(1, std::memory_order_release);
epoch_.notify_one();
}
std::size_t receive(std::span<T> out) // returns 0 only at the end of the stream
{
for (;;) {
const auto e = epoch_.load(std::memory_order_acquire); // 1. remember the epoch
if (const std::size_t n = q_.pop(out)) { q_.notify_producer(); return n; }
if (closed_.load(std::memory_order_acquire)) return q_.pop(out); // drain, then end
epoch_.wait(e, std::memory_order_acquire); // 2. sleep until anything happens
}
}
...
};
The order of the two numbered lines is what makes it correct. The consumer reads the epoch before it checks the queue and the flag. If the producer pushes or closes after that read, the epoch has changed and wait returns immediately; if it happened before, the check sees it. No event can fall between checking and sleeping. Williams makes the same point for condition variables (C++ Concurrency in Action, chapter 4): a waiting thread must check its condition in a way that no notification can slip past, which is why std::condition_variable::wait takes a predicate and a locked mutex. The eventcount gets the same guarantee from a single atomic counter, without a mutex. With it, each thread’s main loop is one line:
while (const std::size_t n = to_rds.receive(block)) rds.process(std::span(block).first(n));
These consumer threads are allowed to sleep. A real-time producer, like an SDR callback, would use only the non-blocking push of the underlying ring, as in Threads and Lock-Free Queues.
The Audio, Filtered Before Decimating¶
PySDR’s audio path de-emphasizes the FM signal at 250 kHz and then takes every sixth sample, x[::6], without a low-pass filter. The de-emphasis is a first-order filter, so everything above the audio band (the 19 kHz pilot, the stereo difference signal around 38 kHz, RDS at 57 kHz and, judging by the spectrum, another subcarrier between 60 and 75 kHz on this station) is only attenuated, and after decimation to 41.7 kHz it folds into the audio band. The C++ audio branch puts a 101-tap, 15 kHz low-pass in front of a decimation by 5 (to 50 kHz), again computing only the outputs it keeps.
How much does it matter? The test measures the band from 16.5 to 18.5 kHz, where an FM broadcast carries no programme audio (it ends at 15 kHz), relative to the programme audio below 15 kHz. In PySDR’s output it is at \(-44\) dB, folded subcarrier energy; with the filter it is at \(-72\) dB. So the filter removes 28 dB of aliasing. On this recording, though, the aliases were already 44 dB below the programme, which is hard to hear. The filter is the right design; whether it is audible depends on the station. fm_receiver writes the result as a 16-bit WAV file, through a 20-line writer that stores every field byte by byte in little-endian order, so the file is the same on every host (the byte-order care from IQ Files Without Copies, and SigMF).
Key Takeaways¶
Blocks that carry their state compose: the whole receiver accepts any block size and produces bit-identical output, which is the test that matters for a live SDR.
Streaming changes small things that array code never sees: a demodulator that needs the next sample, a decimator that must remember its phase across blocks, a resampler that cannot see the end of its input.
Decimators and rational resamplers should compute only the outputs they keep: a polyphase bank turns 501 multiply-adds into 27.
Compared with PySDR’s receiver: the same signal at every DSP stage to \(4 \cdot 10^{-7}\), every RDS group PySDR finds plus two that it misses, about 65 times faster than real time on one core.
A consumer waiting for “data or end of stream” needs one counter that both events bump (an eventcount); waiting on the data index alone can sleep forever.
Filter before decimating, even after a de-emphasis filter: here it removes 28 dB of folded subcarrier energy.