19. Bits and State Machines: Decoding RDS¶
PySDR’s End-to-End Example with RDS takes a recording of an FM broadcast station all the way to the station’s name and RadioText. The last three steps are not signal processing anymore but bit processing: differential decoding, block synchronization with a cyclic code, and parsing the resulting groups. This is the part of the chapter with the most code, and it is a long loop with flags (synced, presync, group_assembly_started), counters, tables of magic numbers, and a comment that hints at the friction of doing bit manipulation in NumPy:
reg = np.uint32(0) # was unsigned long in C++ (64 bits) but numpy doesn't support bitwise ops of uint64, I don't think it gets that high anyway
Bit manipulation and state machines are home ground for C++. In this chapter we rebuild these three steps with the tools the language offers for exactly this kind of code: constexpr for the code tables, std::variant for the states, std::optional for “maybe a result”, and small helpers that make bit fields readable. We test the result against PySDR’s own decoder, run on the same bits, and along the way the comparison turned up two small issues in the Python version that the C++ structure makes hard to write in the first place.
You should read PySDR’s chapter first; we do not repeat how RDS works on the air.
The Test Signal¶
To compare two decoders we need bits whose content we know. figure-generating-scripts/rds_reference.py encodes 120 RDS groups (the station name “CPPSDR” in type 0A groups and a RadioText in type 2A groups, with a made-up PI code and program type), adds the checkwords, differentially encodes the bits like a transmitter, and then makes life hard for the receiver: the stream starts 37 bits into a block, all bits are inverted (the 180-degree ambiguity of BPSK that differential coding exists to remove), and 12 random bits are flipped. It then runs PySDR’s receive-side code, unchanged except for its print statements, on these bits and records every group it outputs, together with the bit position at which it was output.
The Code, Computed¶
RDS protects every 16-bit data word with a 10-bit checkword from a shortened cyclic code with generator polynomial \(g(x) = x^{10} + x^8 + x^7 + x^5 + x^4 + x^3 + 1\) (0x5B9), and then XORs a fixed offset word onto the checkword. The offset word tells the receiver which of the four blocks of a group it is looking at (A, B, C or C’, D). PySDR computes the checkword with the shift-register algorithm from Annex B of the standard; in C++ it is the same loop, marked constexpr (code/include/cppsdr/rds.hpp):
inline constexpr std::uint32_t generator = 0x5B9;
constexpr std::uint16_t syndrome(std::uint32_t x, unsigned mlen)
{
std::uint32_t reg = 0;
constexpr unsigned plen = 10;
for (unsigned i = mlen; i > 0; --i) {
reg = (reg << 1) | ((x >> (i - 1)) & 1u);
if (reg & (1u << plen)) reg ^= generator;
}
for (unsigned i = plen; i > 0; --i) {
reg <<= 1;
if (reg & (1u << plen)) reg ^= generator;
}
return static_cast<std::uint16_t>(reg & ((1u << plen) - 1));
}
PySDR’s decoder starts with three tables of constants:
syndrome = [383, 14, 303, 663, 748]
offset_pos = [0, 1, 2, 3, 2]
offset_word = [252, 408, 360, 436, 848]
Only the offset words are genuine constants from the standard. The syndromes follow from them: the code is linear, so a correctly received block with offset \(o\) has exactly the syndrome of the offset word itself. So instead of copying the second table we let the compiler derive it, and check it against PySDR’s numbers:
// Same order as PySDR's tables: A, B, C, D, and C' last.
enum class offset : std::uint8_t { A, B, C, D, Cprime };
inline constexpr std::array<std::uint16_t, 5> offset_word{252, 408, 360, 436, 848};
inline constexpr std::array<std::uint8_t, 5> block_position{0, 1, 2, 3, 2}; // C' sits where C does
inline constexpr auto offset_syndrome = [] {
std::array<std::uint16_t, 5> s{};
for (std::size_t i = 0; i < 5; ++i) s[i] = syndrome(offset_word[i], 26);
return s;
}();
static_assert(offset_syndrome == std::array<std::uint16_t, 5>{383, 14, 303, 663, 748},
"matches the table in PySDR / the standard");
The [] { ... }() is a lambda that is called immediately, a common idiom for initializing a constant with a loop. This check earned its place while the chapter was being written: the first version of the enum listed the offsets in the order A, B, C, C’, D, which is the order of the blocks in a group but not the order of PySDR’s table, and the static_assert refused to compile it. A copied table with the same mistake would have compiled and silently decoded nothing.
One more table makes the search for block boundaries trivial. A syndrome has 10 bits, so there are only 1024 possible values, and we can precompute which offset, if any, each one belongs to:
inline constexpr auto offset_of_syndrome = [] {
std::array<std::optional<offset>, 1024> t{};
for (std::size_t i = 0; i < 5; ++i) t[offset_syndrome[i]] = offset(i);
return t;
}();
std::optional<offset> says in the type that most syndromes belong to no offset at all; there is no magic “-1” to remember. Looking up a block becomes if (auto o = offset_of_syndrome[syndrome(reg, 26)]), one array access and no loop.
That also removes a subtle problem in the Python version. PySDR searches the syndrome table with a loop that ends in a break:
for j in range(5):
if reg_syndrome == syndrome[j]:
...
break # syndrome found, no more cycles
The comment says the break should leave the loop once a syndrome was found, but it is indented at the level of the if, so it leaves the loop after the first iteration every time: only offset A is ever looked for. The decoder still synchronizes (on two A blocks 104 bits apart), just later than it could. This is the kind of bug that a lookup table cannot have, because there is no loop to leave.
Differential Decoding¶
PySDR’s one-liner bits = (bits[1:] - bits[0:-1]) % 2 compares each bit with its predecessor. For a whole array the C++ equivalent is a standard algorithm, std::adjacent_difference(first, last, out, std::bit_xor<>{}). But a receiver gets bits one at a time, and then the cleanest form is a tiny object that remembers one bit:
class differential_decoder {
public:
std::uint8_t operator()(std::uint8_t bit)
{
const std::uint8_t out = bit ^ prev_;
prev_ = bit;
return out;
}
private:
std::uint8_t prev_ = 0;
};
The test feeds it PySDR’s own example (1 1 1 1 0 1 0 0 1 1 must become 0 0 0 1 1 1 0 1 0). Because it has an operator(), it can be passed anywhere a function is expected, for example to std::ranges::transform.
Synchronization as a State Machine¶
The RDS standard (Annex C) describes block synchronization in three situations. Searching: look at every bit position for a 26-bit window whose syndrome matches an offset. Candidate: having found one, wait for a second match at the right distance (26 bits per block in between); if it is there, the block boundaries are known. Locked: check one block every 26 bits, assemble groups, and fall back to searching if too many blocks fail.
PySDR encodes these situations in two booleans, synced and presync, plus a set of counters that are only meaningful in some of the situations: lastseen_offset matters only while presync is true, block_bit_counter only while synced. Nothing prevents reading a counter in the wrong state, and the reader has to work out which combinations of flags can occur. C++17’s std::variant lets us say it directly: the decoder is in exactly one of three states, and each state carries exactly the data that belongs to it:
struct searching {};
struct candidate { // saw one valid block, waiting for a second one at the right distance
offset seen;
std::size_t at; // bit index where it ended
};
struct locked { // block boundaries known
unsigned bit_in_block = 0;
std::uint8_t expected = 0; // block position 0..3 of the next block
unsigned blocks = 0, bad_blocks = 0;
group assembling{};
unsigned good_in_group = 0; // 0 = not assembling
};
using state = std::variant<searching, candidate, locked>;
Each state gets its own step function, which returns the next state. Pushing a bit shifts it into the register and lets std::visit call the right one:
std::optional<group> push(std::uint8_t bit)
{
reg_ = ((reg_ << 1) | (bit & 1u)) & 0x3FFFFFFu; // the last 26 bits, nothing more
++bit_index_;
std::optional<group> out;
state_ = std::visit([&](auto& s) { return step(s, out); }, state_);
return out;
}
The mask keeps exactly the 26 bits of one block in a std::uint32_t, which settles the question in PySDR’s comment about how big the register can get. The return type std::optional<group> says what the caller gets: usually nothing, sometimes a complete group. A group is std::array<std::uint16_t, 4>, the four data words, rather than eight bytes that have to be put back together later.
The two short states read almost like the standard’s description:
state step(searching&, std::optional<group>&)
{
if (auto o = offset_of_syndrome[syndrome(reg_, 26)]) return candidate{*o, bit_index_};
return searching{};
}
state step(candidate& c, std::optional<group>&)
{
const auto o = offset_of_syndrome[syndrome(reg_, 26)];
if (!o) return c;
const unsigned p_old = block_position[std::size_t(c.seen)], p_new = block_position[std::size_t(*o)];
const unsigned blocks_apart = (p_new + 4 - p_old) % 4 == 0 ? 4 : (p_new + 4 - p_old) % 4;
if (bit_index_ - c.at == 26u * blocks_apart) {
++sync_events_;
return locked{.expected = std::uint8_t((p_new + 1) % 4)};
}
return candidate{*o, bit_index_}; // inconsistent: start over from this block
}
locked{.expected = ...} is a C++20 designated initializer: every other member of the new state starts at its default, so leaving the candidate state cannot carry stale counters along. The locked state checks a block every 26 bits, collects good blocks into a group starting at block A, and returns searching{} if more than 35 of 50 blocks failed, the same rule PySDR uses.
Assembling groups is where the second difference to the Python version showed up. In PySDR’s loop, the check that emits a group is if group_good_blocks_counter == 5, and the counter is reset only when a new group starts with a good A block. If the A block right after a complete group is corrupted, the counter is still 5 from before, and the previous group is appended a second time. In our test stream this happened twice: PySDR’s decoder output 109 groups, of which 2 were repeats of the group before. In the C++ version, the group under construction lives inside the locked state and a group is returned exactly once, at the moment its fourth block arrives.
Parsing: Named Bit Fields¶
The parsing step reads fields out of the 16-bit words: the group type is bits 15 to 12 of block B, the program type bits 9 to 5, and so on. PySDR writes these as shift-and-mask expressions such as (group_1 >> 5) & 0x1f, each with the field width encoded a second time in the mask. A small template takes the bit positions as compile-time parameters, so the width is derived and an impossible range does not compile:
template <unsigned Hi, unsigned Lo>
constexpr unsigned field(std::uint16_t w)
{
static_assert(Hi < 16 && Lo <= Hi, "bit range must lie inside a 16-bit word");
return (w >> Lo) & ((1u << (Hi - Lo + 1)) - 1);
}
const unsigned type = field<15, 12>(g[1]); // group type
pty = field<9, 5>(g[1]); // program type
The station keeps its name and RadioText in fixed-size std::array<char, N> buffers, written through std::span views, and hands them out as std::string_view, so the parser never allocates. PySDR’s table of program type names becomes a constexpr std::array<std::string_view, 32>, a table of string literals that lives in read-only memory. We decode the station name (group type 0), which PySDR’s example leaves out, and the RadioText (group type 2) exactly as PySDR does, including its rule that a toggled A/B flag clears the text.
The Result¶
On the test stream, the C++ decoder synchronizes at bit 88, returns 108 of the 120 groups that were sent (the rest were hit by the injected bit errors or passed before synchronization), and recovers the station:
PI 0x54A8, PTY 10 (Country), name "CPPSDR "
RadioText "Hello from C++, decoded with a variant state machine!"
Every one of the 107 distinct groups PySDR’s decoder found comes out of the C++ decoder at the same bit position (code/tests/test_rds.cpp checks this). The C++ decoder finds one group more, the very first one, because it does not skip offsets B to D while searching for synchronization.
None of this needed clever optimization. What made the C++ version shorter to reason about is that each concept got a construct of its own: the code tables are computed and checked rather than copied, each state owns its data, results that may or may not exist are std::optional, and bit fields have names.
Key Takeaways¶
Derive tables from the constants they come from (here: syndromes from offset words) with
constexpr, andstatic_assertthem against the published values. The check caught a real ordering mistake while writing this chapter.Model protocol states as a
std::variantof small structs. Each state carries only its own data, transitions construct the next state fresh (designated initializers help), andstd::visitdispatches.Return “maybe a result” as
std::optional, and use fixed-width unsigned types with explicit masks for shift registers.Give bit fields names and compile-time-checked positions instead of repeating shifts and masks.
Test against the reference implementation on the same input, and compare where outputs occur as well as what they are: that is how the two small issues in the Python version came to light.