29. Real-Time Display: Two Threads, No Waiting¶
PySDR’s Real-Time GUIs with PyQt chapter builds a spectrum analyzer with a time plot, a spectrum plot and a waterfall, fed by a PlutoSDR, a USRP or a simulated signal. Its structure is the one every SDR display needs: the radio and the DSP run in a worker thread, the drawing runs in the GUI thread, and Qt’s signals and slots carry data one way and settings the other. Most of PySDR’s chapter is about Qt’s widgets. This chapter is about the part between the threads, because that is where a real-time display can go wrong without anyone noticing: samples that are never looked at, a radio that waits for the screen, a burst that the display averages away.
The C++ version uses SDL3 for the window instead of Qt, because the interesting part is not in the GUI library and SDL keeps the GUI code to one short file. GNU Radio’s Qt sinks are the reference for how a flowgraph hands data to a display.
The code is in code/include/cppsdr/waterfall.hpp (everything except the drawing), code/tests/test_waterfall.cpp, and code/gui/waterfall_gui.cpp, the SDL3 program. make gui builds the program and runs its headless check, which draws into memory and opens no window. ./code/gui/build/waterfall_gui opens the interactive version.
The screenshot above came from the headless mode. The top half of the waterfall is PySDR’s FM recording at 250 kS/s, with the stereo pilot and RDS subcarriers on the right; the faint horizontal line is where the 4-second recording loops. Below it is PySDR’s simulated source, a tone at a tenth of the sample rate with the spurs its clipping produces, plus short bursts added for this chapter.
Three Ways to Feed a Waterfall¶
PySDR keeps the two threads in lockstep. The worker’s run() takes one block of fft_size samples, computes its spectrum, rolls the whole spectrogram array down by one row with np.roll, emits the plots’ data, and finally emits end_of_run. The GUI thread answers that signal by starting run() again. Signals between threads are delivered in order, so the next block is read only after the GUI has handled the previous plots. This is simple and never piles up work, but the radio now runs at the screen’s pace. When the GUI is slow, the worker waits, and with a real SDR the samples that arrive meanwhile are lost in the driver, uncounted. Each run also analyses one FFT’s worth of samples, whatever the sample rate.
GNU Radio’s waterfall sink (gr-qtgui/lib/waterfall_sink_c_impl.cc, v3.10.12.0) is the opposite. work() never waits for the GUI. It posts a QEvent with a copy of the data and returns:
if (gr::high_res_timer_now() - d_last_time > d_update_time) {
...
fft(d_fbuf.data(), d_residbufs[n].data(), d_fftsize);
...
d_last_time = gr::high_res_timer_now();
d_qApplication->postEvent(d_main_gui, new WaterfallUpdateEvent(d_magbufs, d_fftsize, d_last_time));
}
d_index = 0;
j += resid;
The flowgraph runs at the radio’s pace, as it must. But look at what happens between updates: the frame is consumed (j += resid) without an FFT. With the default update_time of 0.1 s and no averaging (d_fftavg is 1.0 by default), the display shows one FFT of fftsize samples per tenth of a second. At 1 MS/s with 1024 bins, that is about 1 % of the signal.
This chapter’s version keeps GNU Radio’s decoupling and looks at every sample. The DSP thread transforms every frame and reduces the frames between two display rows to one row. The reduction keeps both the mean power per bin and the peak, the maximum over those frames. The GUI thread takes whatever rows have arrived each time it draws.
The test measures the difference. It uses 4 s of noise at 1 MS/s, at −40 dBFS, with 40 bursts of 0.5 ms at random times, each a tone at −46 dBFS, and 10 display rows per second:
display |
bursts visible |
|---|---|
peak over every frame of the row |
40 of 40 |
mean over every frame of the row |
0 of 40 |
one FFT per update interval (GNU Radio’s policy, 39 936 of 4 000 000 samples analysed) |
at most 0 of 40 |
The mean is what PySDR’s spectrum plot shows (PSD_avg = PSD_avg * 0.99 + PSD * 0.01) and what most displays average to. It spreads a 0.5 ms burst over a 0.1 s row, roughly 20 dB of dilution, and here that sinks it into the noise. Peak hold over every frame is how real-time spectrum analyzers guarantee that any event longer than a frame shows up. The display shows both: the yellow line is the peak, the grey line the mean.
Looking at every sample needs one more detail. Frames are windowed, and a window tapers to zero at its edges, so a burst that falls between two frames would be nearly invisible. With 50 % overlap, the Hann window’s shifted copies add up to a constant, so every sample carries the same total weight. That is a property of the window and the hop, so it is checked at compile time:
template <class Window>
class row_builder {
static constexpr std::size_t N = Window::size, hop = N / 2;
static_assert(overlap_adds_to_constant<Window>(hop), "frames must cover every sample with equal weight");
...
};
static_assert(!gui::overlap_adds_to_constant<hann1024>(1024), "Hann without overlap: frame edges are nearly blind");
static_assert(!gui::overlap_adds_to_constant<blackman1024>(512), "Blackman needs 2/3 overlap");
Swap the window for a Blackman, and the row_builder no longer compiles until the hop is changed.
What Crosses Between the Threads¶
PySDR’s worker emits NumPy arrays through signals; GNU Radio allocates a new event and copies into it for each update. Here a row is a plain value:
template <std::size_t Bins>
struct spectrum_row {
std::array<float, Bins> peak_db{};
std::array<float, Bins> mean_db{};
std::uint64_t first_sample = 0;
std::uint32_t frames = 0;
std::uint32_t dropped_before = 0; // rows lost because the GUI fell behind
};
static_assert(std::is_trivially_copyable_v<spectrum_row<1024>>, "must cross threads by plain copy");
It travels through the lock-free ring of Threads and Lock-Free Queues, which holds eight rows. The other direction, PySDR’s worker slots such as update_gain, becomes a second ring of commands. A command is a std::variant, and the DSP thread applies all pending ones between blocks with std::visit:
using command = std::variant<set_gain, set_rows_per_second, set_source>;
link.apply_commands(gui::overloaded{
[&](gui::set_gain const& c) { sim.gain_db = c.db; },
[&](gui::set_rows_per_second const& c) { rows_per_second = c.rate; },
[&](gui::set_source const& c) { source = c.index; ... }});
Adding a command type without handling it in the visitor is a compile error, which a table of string-keyed callbacks would not give. Applying commands between blocks also answers a question that PySDR’s slots leave to Qt: a setting never changes in the middle of a block.
Neither side ever waits. display_link::publish tries to push the row. If the ring is full because the GUI is behind, it drops the row, counts it, and stores the count in the next row that gets through:
bool publish(row r)
{
r.dropped_before = dropped_;
if (rows_.push(std::span<const row>(&r, 1)) == 1) { dropped_ = 0; return true; }
++dropped_;
dropped_total_.fetch_add(1, std::memory_order_relaxed);
return false;
}
The GUI draws a magenta line where rows are missing, so a gap in the waterfall is visible as a gap, not as a silent jump in time. The test runs both threads and stalls the GUI for 50 ms after 20 rows, as a window resize or a slow redraw would. The DSP thread carries on at its own pace and drops the rows that do not fit (125 to 200 of 400, depending on timing). Every row is either received or counted, the gap appears as one marker, and a command sent afterwards reaches the DSP thread. The same test also runs under ThreadSanitizer, which reports no races.
A Waterfall That Does Not Scroll¶
PySDR’s worker scrolls the waterfall with self.spectrogram[:] = np.roll(self.spectrogram, 1, axis=1), moving every pixel for every new row, and then hands the whole array to the GUI. The image does not have to move. waterfall_image keeps the rows in a ring and writes each new row backwards, one position before the previous one. Then “newest row at the top” is always two contiguous pieces of the ring, the rows from the newest to the end and the rows from the start to the newest:
std::array<piece, 2> layout() const
{
return {piece{newest_, 0, Height - newest_}, piece{0, Height - newest_, newest_}};
}
A new row costs one row of pixels and one SDL_UpdateTexture call for that row; nothing else is copied. On screen, the two pieces are two SDL_RenderTexture calls from the same texture. Written forwards, the newest row would end up at the bottom of each piece, and showing it at the top would need a flip. The test pushes 130 rows, including gap markers, through a 48-row image, wrapping it 2.7 times. After every row it compares the two-piece copy with an image shifted the PySDR way, and they are equal.
The colours come from a 256-entry viridis table, built at compile time by interpolating viridis’s five standard stops, so the colormap is a constexpr array and its end points are static_asserts. Each display column takes the maximum of the bins it covers, so a narrow signal cannot fall between two columns.
Testing a GUI Without a Screen¶
The drawing code is the only part not covered by test_waterfall, and it is where the ring’s two pieces meet the renderer. waterfall_gui --headless N out.bmp runs the full program, both threads, the real sources and the real drawing code, with one difference: the SDL renderer is a software renderer drawing into a surface in memory (SDL_CreateSoftwareRenderer), so no window and no video driver are involved. After \(N\) frames it reads the waterfall area back with SDL_RenderReadPixels and compares it with copy_display_order() of the image in memory. For the screenshot above, 800 frames and 784 rows, the ring had wrapped and the newest row was at storage row 16, and 0 of 409 600 pixels differed. That is ctest in code/gui, so the GUI’s drawing logic is tested with ctest like everything else.
Key Takeaways¶
Never let the radio wait for the screen. PySDR’s lockstep worker reads the next block only after the GUI has drawn, and samples lost meanwhile go uncounted. Decouple the threads with a ring in each direction and make neither side wait.
Decide what the display promises. GNU Radio’s waterfall sink transforms one frame per update interval, 1 % of the samples at 1 MS/s. Transforming every frame and keeping a peak hold per display row showed 40 of 40 short bursts where the row mean showed 0.
Overlapped frames must add up to a constant weight, or the edges of each frame are blind. That is a property of the window type and the hop, so
static_assertit.Send plain values between threads (
static_assert(std::is_trivially_copyable_v<...>)), commands as astd::varianthandled by an exhaustive visitor, and count what you drop.A ring of rows written backwards turns scrolling into two blits, with no data moved.
Test the GUI headless: a software renderer drawing into memory runs the real drawing code, and its pixels can be compared exactly.