31. Writing a GNU Radio Block in C++

PySDR’s SDR Frameworks chapter introduces GNU Radio: blocks connected into a flowgraph, a scheduler that moves samples between them, and Python on top. Most of the blocks you drag into GNU Radio Companion are C++ underneath, and when PySDR’s algorithms leave the prototype stage, a C++ block is where they often end up. This chapter takes two pieces from earlier chapters, the Costas loop and the FIR filter, wraps each in a GNU Radio block, and runs them in a flowgraph written in C++. Along the way it explains the two scheduler features every block author meets first, the work() contract and set_history(), and one that is easy to get wrong: changing a parameter while the flowgraph runs.

The code is in code/gnuradio_block/, a small CMake project against GNU Radio 3.10 (installed from Homebrew here; any 3.10 package works). It is deliberately separate from the rest of the book’s code so that only this chapter needs GNU Radio. The usual way to start a module is gr_modtool newmod and gr_modtool add, which generate the same structure plus Python bindings and GRC files; we write the C++ by hand to see what each part does.

The Shape of a Block

A GNU Radio block has a public interface and a hidden implementation. The interface is an abstract class with a factory function that returns a std::shared_ptr:

// include/cppsdr_gr/costas_cc.h
class costas_cc : virtual public gr::sync_block {
public:
    using sptr = std::shared_ptr<costas_cc>;
    static sptr make(float alpha = 0.132f, float beta = 0.00932f);
    virtual void set_gains(float alpha, float beta) = 0;   // callable while running
};

The implementation class derives from it, lives in the library’s .cc file, and is created by make(). Users, including the Python bindings, see only the interface; the implementation can change without breaking anyone who compiled against the header. This is the classic pimpl-like separation, and it is why every GNU Radio block comes as a foo.h / foo_impl.h / foo_impl.cc triple.

A gr::sync_block produces exactly one output item per input item, the common case for filters and loops that run at a fixed rate. (Decimators and interpolators derive from sync_decimator / sync_interpolator, and blocks with arbitrary rates, like the timing recovery from Timing Recovery with a Compile-Time Filter Bank, from gr::block with general_work() and forecast().) The constructor declares the item sizes, the “io signatures”:

costas_cc_impl(float alpha, float beta)
    : gr::sync_block("cppsdr_costas_cc",
                     gr::io_signature::make(1, 1, sizeof(gr_complex)),   // one complex input
                     gr::io_signature::make(1, 1, sizeof(gr_complex)))   // one complex output

work(): Chunks of Any Size

The scheduler calls work() whenever input is available and output space is free. The number of items is not fixed; it depends on buffer sizes and on what the neighbouring blocks have done, and it changes from call to call. This is precisely the situation the whole book has been designing for: every process() in cppsdr takes blocks of any size and carries its state across calls. So the block’s work() is a thin adapter, from GNU Radio’s untyped void* buffers to typed std::span:

int work(int noutput_items, gr_vector_const_void_star& input_items,
         gr_vector_void_star& output_items) override
{
    ...
    const auto n = static_cast<std::size_t>(noutput_items);
    std::span<const gr_complex> in(static_cast<const gr_complex*>(input_items[0]), n);
    std::span<gr_complex> out(static_cast<gr_complex*>(output_items[0]), n);
    loop_.process(in, out);      // phase and frequency live in loop_, between calls
    return noutput_items;
}

cppsdr::costas::direct_port<float> loop_;

gr_complex is std::complex<float>, so the casts are the only GNU Radio-specific part. The algorithm itself does not know it is inside GNU Radio, which also means it can be tested without GNU Radio, as we have done in every chapter. GNU Radio’s own blocks follow the same split: the DSP lives in “kernel” classes (gr::filter::kernel::fir_filter, gr::blocks::rotator) that the block wraps.

set_history(): Let the Scheduler Keep the Past

An FIR filter needs the last \(N-1\) inputs to compute its first output. In FIR Filters in C++ our fir_history class kept them in its own buffer. Inside GNU Radio, the scheduler can do that for you:

explicit fir_ccf_impl(std::vector<float> const& taps)
    : gr::sync_block("cppsdr_fir_ccf", ...),
      reversed_(taps.rbegin(), taps.rend())
{
    set_history(static_cast<unsigned>(taps.size()));   // "give me N-1 old samples up front"
}

int work(int noutput_items, gr_vector_const_void_star& input_items,
         gr_vector_void_star& output_items) override
{
    // input_items[0] holds noutput_items + N - 1 samples, oldest first
    const auto* in = static_cast<const gr_complex*>(input_items[0]);
    auto* out = static_cast<gr_complex*>(output_items[0]);
    for (int i = 0; i < noutput_items; ++i)
        out[i] = cppsdr::kernel::dot_omp_simd(in + i, reversed_.data(), reversed_.size());
    return noutput_items;
}

With set_history(N), every input buffer starts \(N-1\) items before the first new item, and the scheduler arranges the doubly mapped buffers so that this window is contiguous. Output \(i\) is then one dot product over in[i .. i+N-1], the contiguous-window layout the FIR chapter argued for, and the block has no state of its own at all. This is how GNU Radio’s own fir_filter_blk works (gr-filter/lib/fir_filter_blk_impl.cc).

Changing Parameters While Running

Flowgraphs are interactive: a GUI slider or a Python script changes a block’s parameters while the scheduler is calling work() from its own thread. So a setter runs concurrently with work(), and if both touch the same variables, that is a data race (Threads and Lock-Free Queues). GNU Radio provides a mutex in every block for this, d_setlock, documented in gnuradio/block.h as “used by block’s setters and work functions to make setting/resetting of parameters thread-safe”. The scheduler does not take it for you; the block author has to lock it in both places. Even GNU Radio’s own blocks are not uniform about this. The Costas loop’s set_loop_bandwidth (in gr-blocks/lib/control_loop.cc) recomputes the loop gains without taking any lock.

A lock in work() is exactly what we wanted to avoid on the real-time path. The alternative comes from audio plugins, where the GUI thread changes parameters of a running audio callback all the time (Pirkle, Designing Audio Effect Plugins in C++, chapters 2 and 8; Kormanyos describes the same “shadow register” idea for PWM duty cycles in Real-Time C++, chapter 9). The setter only stores a request; work() picks it up at the start of the next call:

void set_gains(float alpha, float beta) override        // any thread
{
    pending_alpha_.store(alpha, std::memory_order_relaxed);
    pending_beta_.store(beta, std::memory_order_relaxed);
    pending_.store(true, std::memory_order_release);    // publish the pair
}

int work(...) override                                  // scheduler thread
{
    if (pending_.exchange(false, std::memory_order_acquire)) {
        loop_.alpha = pending_alpha_.load(std::memory_order_relaxed);
        loop_.beta = pending_beta_.load(std::memory_order_relaxed);
    }
    ...
}

The release/acquire pair on the flag makes the two new gains visible together (the same hand-over as in the SPSC queue); the loop variables themselves are only ever touched by the scheduler thread; and the new gains take effect at a block boundary, never in the middle of a computation. work() never waits. If two set_gains calls race with each other from two different threads, the result is one of the two pairs, possibly mixed, so for multiple writers you would publish the pair as one object (for example two floats packed into one 64-bit atomic); with one control thread, this is enough.

A Flowgraph in C++

GNU Radio flowgraphs are usually written in Python or drawn in GNU Radio Companion, but the C++ API is the same, and it makes a convenient test harness (code/gnuradio_block/test_gr_blocks.cc):

auto tb = gr::make_top_block("costas_test");
auto src = gr::blocks::vector_source_c::make(in);       // the test signal from the Costas chapter
auto costas = cppsdr_gr::costas_cc::make();
auto sink = gr::blocks::vector_sink_c::make();
tb->connect(src, 0, costas, 0);
tb->connect(costas, 0, sink, 0);
tb->run();

std::vector<gr_complex> ref(in.size());
cppsdr::costas::direct_port<float> loop;
loop.process(in, ref);                                  // the same loop, one call, no GNU Radio
check(sink->data() == ref, ...);

The scheduler splits the 200 000 samples into chunks of its own choosing, and the output is still bit-identical to a single direct call: the block carries its state correctly. The FIR block with set_history matches fir_history from the FIR chapter. Both checks pass with GNU Radio 3.10.12.

To use the blocks from Python and GNU Radio Companion, a module needs pybind11 bindings and .block.yml files; gr_modtool bind and gr_modtool makeyaml generate them from the headers, which is a good reason to keep the public header as small and plain as ours.

Key Takeaways

  • Keep the DSP in plain, testable C++ classes and make the GNU Radio block a thin adapter: void* buffers in, std::span to the algorithm, state in the algorithm object.

  • work() gets chunks of any size; algorithms written for streaming blocks (every process() in this book) fit without changes.

  • set_history(N) makes the scheduler keep \(N-1\) past samples in front of each buffer, contiguous, so a filter needs no state of its own.

  • Setters run concurrently with work(). Either lock d_setlock in both, or, better on the real-time path, let the setter publish a request with release/acquire atomics and let work() apply it at the next call.

  • A C++ top block with vector_source and vector_sink is a handy test harness: run the block in the real scheduler and compare with a direct call.