17. Channel Coding¶
PySDR’s Channel Coding chapter is about ideas rather than code: why we add redundancy, what a code rate is, how a Hamming code places its parity bits, why soft decisions beat hard ones, and how close modern codes get to the Shannon limit. It shows a generator matrix and a trellis but implements neither. This chapter does, and the C++ angle is the one the GPS chapter already hinted at: codes over bits are finite objects. A Hamming(7,4) code has 16 codewords and 128 possible received words, so the compiler can check every claim about it, and a convolutional code’s whole trellis fits in a table computed at compile time.
Along the way we will find that one of the three Hamming properties PySDR lists needs a qualification, and that hard-decision decoding of a strong convolutional code is, at low SNR, worse than no code at all.
The code is in code/include/cppsdr/fec.hpp, tested in code/tests/test_fec.cpp and, against GNU Radio’s gr-fec, in code/gnuradio_block/test_gr_crosscheck.cc.
A Hamming Code from PySDR’s Rule¶
PySDR describes the Hamming code by a rule rather than a matrix: parity bits sit at the positions that are powers of two (1, 2, 4, 8, …), data bits fill the rest, and “each parity bit ‘covers’ all bits where the bitwise AND of the parity and the bit position is non-zero”. That sentence is already an algorithm, and it is a better source for code than a hand-copied matrix, because it works for every size. With \(R\) parity bits there are \(n = 2^R - 1\) positions and \(k = n - R\) data bits: Hamming(7,4) for \(R = 3\), Hamming(15,11) for \(R = 4\).
We store a codeword as an integer whose bit \(p-1\) is position \(p\). Then “the positions covered by parity bit \(2^i\)” is a bit mask, one per parity bit, computed by the compiler straight from the rule:
template <unsigned R>
struct hamming {
static constexpr unsigned n = (1u << R) - 1, k = n - R;
static constexpr std::array<word, R> cover = [] {
std::array<word, R> c{};
for (unsigned i = 0; i < R; ++i)
for (unsigned p = 1; p <= n; ++p)
if (p & (1u << i)) c[i] |= word{1} << (p - 1); // PySDR's rule, verbatim
return c;
}();
...
};
Each mask is one row of what the textbooks call the parity-check matrix \(H\). Encoding places the data bits and then sets each parity bit so that its group has even parity; checking a group is one AND and one std::popcount, the same GF(2) arithmetic as the Gold code correlations in Spreading Codes: GPS C/A Codes at Compile Time:
static constexpr word encode(word data)
{
word c = 0;
for (unsigned j = 0; j < k; ++j) // data bits into positions 3, 5, 6, 7, ...
if (data >> j & 1) c |= word{1} << (data_positions[j] - 1);
for (unsigned i = 0; i < R; ++i) // make every covered group even
if (parity(c & cover[i])) c |= word{1} << ((1u << i) - 1);
return c;
}
PySDR then shows the encoding as a matrix product with a generator matrix \(G\), encoding the data 1011 into 1011010. Its \(G\) lists the columns in a different order (the four data bits first, then the parity bits of positions 1, 2 and 4), but it is the same code. Since the code is linear, row \(j\) of \(G\) is simply the codeword of the \(j\)-th unit vector, so the compiler can derive \(G\) from the rule, and we can check it against PySDR’s matrix and example:
static_assert(H74::generator[0] == bits("1000110") && H74::generator[1] == bits("0100101") &&
H74::generator[2] == bits("0010011") && H74::generator[3] == bits("0001111"),
"the coverage rule gives exactly PySDR's G");
static_assert(H74::to_systematic(H74::encode(bits("1011"))) == bits("1011010"),
"PySDR's example: 1011 encodes to 1011010");
Both hold. Nothing in the code was typed in from the matrix; the matrix was checked against the rule.
The Syndrome Points at the Error¶
At the receiver, we recompute the \(R\) parity checks. The \(R\) results, read as a binary number, are the syndrome:
static constexpr unsigned syndrome(word c)
{
unsigned s = 0;
for (unsigned i = 0; i < R; ++i) s |= parity(c & cover[i]) << i;
return s;
}
Here is the reason for Hamming’s strange-looking placement. Suppose a single bit at position \(p\) flips. Parity check \(i\) fails exactly when that position is covered by parity bit \(2^i\), which by PySDR’s rule means exactly when bit \(i\) of \(p\) is set. So the failing checks spell out \(p\) in binary: the syndrome is the position of the error. Correcting it is one XOR:
static constexpr word correct(word c)
{
const unsigned s = syndrome(c);
return s ? c ^ (word{1} << (s - 1)) : c;
}
The test proves a stronger form at compile time: for every one of the 128 seven-bit words, the syndrome equals the XOR of the positions of all its set bits. This is Hamming’s construction in one line, and the compiler confirms it by trying all of them.
Proving the Code’s Properties¶
PySDR lists three properties of Hamming(7,4):
the minimum number of bit changes between any two codewords is three;
it can correct one-bit errors;
it can detect but not correct two-bit errors.
With 16 codewords, the compiler can check each claim by brute force. For a linear code the minimum distance is the smallest weight of a non-zero codeword:
template <class Code>
constexpr unsigned minimum_distance()
{
unsigned d = 64;
for (std::uint64_t m = 1; m < (std::uint64_t{1} << Code::k); ++m)
d = std::min(d, unsigned(std::popcount(Code::encode(m))));
return d;
}
static_assert(minimum_distance<hamming<3>>() == 3 && minimum_distance<hamming<4>>() == 3);
The second claim is checked for all 16 codewords and all 7 error positions, 112 cases. For Hamming(15,11), trying all 2048 × 15 cases exceeded Clang’s budget for compile-time evaluation (the same limit we met in Spreading Codes: GPS C/A Codes at Compile Time). It is also unnecessary, and the reason is worth knowing: the code is linear, so the syndrome of codeword XOR error is the syndrome of the error alone. It suffices to check that every codeword has syndrome zero and that each of the 15 single-bit errors has a distinct syndrome, a much smaller proof that the compiler accepts.
The third claim needs care. A minimum distance of 3 lets a decoder either correct one error or detect two, not both at once. The decoder above corrects, so what does it do with two errors? The test counts:
// Two errors in Hamming(7,4): the decoder never notices; it "corrects" to a
// different codeword in every one of the 16 x 21 cases.
static_assert(double_errors_miscorrected() == 16 * 21);
Every double error produces a non-zero syndrome, so the decoder sees an error, but it is always a syndrome that a single error could also have produced. The decoder flips a third bit and returns a wrong codeword, and nothing in its output says so. The reason is that Hamming(7,4) is a perfect code: the 16 codewords, each with its 7 single-error neighbours, account for \(16 \times 8 = 128 = 2^7\) words, every word there is (also a static_assert). No syndrome is left over to say “two errors”.
The fix is one more bit: the parity of the whole codeword. This extended Hamming code has minimum distance 4 and is known as SECDED (single error correction, double error detection), the scheme used in ECC memory. A single error flips the overall parity; a double error leaves it even but makes the syndrome non-zero, and the decoder can tell the two apart:
static constexpr result decode(word c)
{
const unsigned s = base::syndrome(inner);
const bool overall = parity(c); // odd number of errors?
if (!s && !overall) return {base::extract(inner), status::ok};
if (overall) return {base::extract(base::correct(inner)), status::corrected};
return {base::extract(inner), status::double_error}; // even, but not zero
}
static_assert(secded_works()); // all 8 single errors corrected, all 28 double errors flagged
So PySDR’s third bullet is true of the extended code, and of the plain code only when it is used as a pure detector. On a binary channel with 1 % bit errors, the plain decoder still cuts the data bit error rate from \(9.8 \cdot 10^{-3}\) to \(8.4 \cdot 10^{-4}\) in the test, because single errors are far more common than double ones.
The RDS chapter used the same machinery at a larger size: RDS’s (26,16) cyclic code is checked with a syndrome, and its offset words are recognized by their syndromes (Bits and State Machines: Decoding RDS).
A Convolutional Code and Its Trellis¶
PySDR mentions that convolutional codes work on streams and are decoded on a trellis, and leaves it there. The best-known one, and GNU Radio’s standard example, is the NASA “Voyager” code: constraint length \(K = 7\) (a 7-bit shift register), rate 1/2 (two output bits per input bit), each output the parity of the register ANDed with one of two polynomials. In C++ the code itself can be the type:
template <unsigned K, unsigned... Polys>
struct conv_code {
static constexpr unsigned rate = sizeof...(Polys);
static constexpr unsigned states = 1u << (K - 1);
static constexpr std::array<unsigned, rate> polys{Polys...};
static constexpr unsigned output(unsigned reg) // all output bits for one register value
{
unsigned o = 0;
for (unsigned j = 0; j < rate; ++j) o |= parity(reg & polys[j]) << j;
return o;
}
static constexpr auto branch = /* output(s) and output(s | 2^(K-1)) for every state s */;
};
using voyager = conv_code<7, 109, 79>;
static_assert(reverse_bits<7>(0133) == 109 && reverse_bits<7>(0171) == 79,
"GNU Radio's 109/79 are the textbook 133/171 (octal), reversed");
The polynomials need a word of explanation, because they are a classic source of confusion. Textbooks write the Voyager code as 133 and 171 in octal. GNU Radio’s cc_encoder takes 109 and 79, and its documentation explains why: its shift register shifts the other way, so the bit order of each polynomial is reversed. The static_assert records that conversion where nobody can miss it. With GNU Radio’s convention, encode_terminated<voyager> produces output bit-identical to gr::fec::code::cc_encoder in its CC_TERMINATED mode (checked in the cross-check program).
The trellis follows from the type. A state is the last \(K-1\) input bits, so there are \(2^{K-1} = 64\) states. Each new state \(s\) can be reached from exactly two old states, \(\lfloor s/2 \rfloor\) and \(\lfloor s/2 \rfloor + 32\), and the two branches produce the outputs output(s) and output(s | 64). All 128 branch outputs are a constexpr table.
Viterbi: Soft and Hard in One Decoder¶
The Viterbi algorithm walks the trellis one input bit at a time. For every state it keeps the score of the best path that ends there. For each new state it adds the scores of the two incoming branches, compares them, and keeps the better one, recording which predecessor won (“add-compare-select”). At the end of a frame it follows the recorded decisions backwards.
PySDR distinguishes soft-decision decoding (use the received values, like 0.3423 or -1.1234) from hard-decision decoding (use only 0s and 1s). In code they need not be two decoders. The branch score is the correlation between the received values and the branch’s expected signs; a hard decision is just a soft value of exactly \(\pm 1\):
for (unsigned o = 0; o < (1u << R); ++o) // score of every possible branch output
for (unsigned j = 0; j < R; ++j) bm[o] += (o >> j & 1) ? -soft[t * R + j] : soft[t * R + j];
for (unsigned i = 0; i < S / 2; ++i) // GNU Radio's (VOLK's) butterfly
for (unsigned b = 0; b < 2; ++b) {
const unsigned s = 2 * i + b;
const float m0 = old[i] + bm[Code::branch[s][0]];
const float m1 = old[i + S / 2] + bm[Code::branch[s][1]];
now[s] = m1 > m0 ? m1 : m0;
dec[s] = m1 > m0; // one bit per state: std::bitset<S>
}
The loop is arranged as a butterfly: predecessors \(i\) and \(i + S/2\) feed successors \(2i\) and \(2i+1\). That is how VOLK’s kernel volk_8u_x4_conv_k7_r2_8u, which GNU Radio’s cc_decoder uses, organizes it (its generic version calls the helper BFLY). Both loads come from contiguous memory, which is what lets the SIMD versions work on 16 (NEON, SSE) or 32 (AVX2) 8-bit metrics per instruction. The decisions of one step are a std::bitset<64>, a single machine word, so a 2000-bit frame needs 16 kB of decision memory.
GNU Radio’s decoder goes further for speed: it quantizes the soft values to 8 bits, keeps the path metrics in 8-bit integers, and renormalizes them after every step so that they cannot overflow. Our float decoder renormalizes too (it subtracts the best metric after each step) but keeps full precision. On the same noisy frames (200 frames of 2048 bits, at 3 and 4 dB), the two decoders agree on all but 38 of the 409 600 decoded bits, and the float version makes slightly fewer errors (109 instead of 125 at 3 dB), the small price of 8-bit metrics.
What Soft Decisions Are Worth¶
How much better is soft decoding? The test sends 200 frames of 2000 bits through the code, BPSK and white noise at a fixed seed, and decodes each frame twice, once with the received values and once with only their signs. The noise is scaled by \(E_b/N_0\), the energy per information bit, so the comparison with uncoded BPSK is fair: the coded system spends the same energy on twice as many channel bits.
\(E_b/N_0\) |
uncoded BPSK |
hard-decision Viterbi |
soft-decision Viterbi |
|---|---|---|---|
2 dB |
\(3.8 \cdot 10^{-2}\) |
\(1.1 \cdot 10^{-1}\) |
\(4.9 \cdot 10^{-3}\) |
3 dB |
\(2.3 \cdot 10^{-2}\) |
\(3.0 \cdot 10^{-2}\) |
\(3.8 \cdot 10^{-4}\) |
4 dB |
\(1.3 \cdot 10^{-2}\) |
\(5.8 \cdot 10^{-3}\) |
\(3.3 \cdot 10^{-5}\) |
These are 400 000 bits per row, enough to see the trend but not to quote the last digit; the soft result at 4 dB rests on 13 errors. Two things stand out. Soft decoding is 20 to 180 times better than hard decoding here, and the gap grows with the SNR. And at 2 and 3 dB, hard decoding is worse than sending the bits uncoded. Rounding each received value to a bit throws away how confident it was, and below a certain SNR the code cannot make up for that loss. PySDR’s remark that soft decoding is “more robust” is, at low SNR, the difference between a working link and a broken one.
The table also shows why codes are judged by \(E_b/N_0\) and not SNR. The Shannon limit from PySDR’s chapter, rewritten per information bit, says that at the spectral efficiency of this system (rate 1/2 on BPSK, 0.5 bit/s/Hz) error-free communication is possible down to \(E_b/N_0 = 10 \log_{10}\frac{2^{0.5}-1}{0.5} \approx -0.8\) dB. This 1970s code needs about 4.5 dB for an error rate of \(10^{-5}\); turbo and LDPC codes get within a fraction of a dB of the limit.
Key Takeaways¶
Build codes from their defining rule, not from copied matrices; then check the matrix against the rule. PySDR’s coverage sentence is the whole Hamming code.
Over GF(2), a matrix-vector product is AND plus
std::popcount; a codeword is an integer.Small codes are finite objects: the compiler can prove minimum distance, single-error correction and perfectness by exhaustion. Use linearity to keep the proofs small.
A Hamming decoder that corrects cannot also detect double errors; it miscorrects all of them. SECDED adds one bit and does both.
A convolutional code can be a type,
conv_code<7, 109, 79>, with its trellis as a compile-time table. Watch the polynomial bit order: GNU Radio’s is reversed relative to the textbooks.One Viterbi decoder handles both cases: hard decisions are soft values of \(\pm 1\). Soft decisions are worth far more than PySDR’s word “robust” suggests.